SCORM MDL-24734 - fix display of grade information on view.php page - also fixes...
[moodle.git] / calendar / lib.php
blob4917100f2c9ebadf7f3180bdbdc6b4078ac56007
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_UPCOMING_DAYS', isset($CFG->calendar_lookahead) ? intval($CFG->calendar_lookahead) : CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD);
49 define('CALENDAR_UPCOMING_MAXEVENTS', isset($CFG->calendar_maxevents) ? intval($CFG->calendar_maxevents) : CALENDAR_DEFAULT_UPCOMING_MAXEVENTS);
50 define('CALENDAR_WEEKEND', isset($CFG->calendar_weekend) ? intval($CFG->calendar_weekend) : CALENDAR_DEFAULT_WEEKEND);
51 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
52 define('CALENDAR_TF_24', '%H:%M');
53 define('CALENDAR_TF_12', '%I:%M %p');
55 /**
56 * CALENDAR_STARTING_WEEKDAY has since been deprecated please call calendar_get_starting_weekday() instead
57 * @deprecated
59 define('CALENDAR_STARTING_WEEKDAY', CALENDAR_DEFAULT_STARTING_WEEKDAY);
61 $CALENDARDAYS = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
63 /**
64 * Gets the first day of the week
66 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
68 * @return int
70 function calendar_get_starting_weekday() {
71 global $CFG;
73 if (isset($CFG->calendar_startwday)) {
74 $firstday = $CFG->calendar_startwday;
75 } else {
76 $firstday = get_string('firstdayofweek', 'langconfig');
79 if(!is_numeric($firstday)) {
80 return CALENDAR_DEFAULT_STARTING_WEEKDAY;
81 } else {
82 return intval($firstday) % 7;
86 /**
87 * Generates the HTML for a miniature calendar
89 * @global core_renderer $OUTPUT
90 * @param array $courses
91 * @param array $groups
92 * @param array $users
93 * @param int $cal_month
94 * @param int $cal_year
95 * @return string
97 function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
98 global $CFG, $USER, $OUTPUT;
100 $display = new stdClass;
101 $display->minwday = get_user_preferences('calendar_startwday', calendar_get_starting_weekday());
102 $display->maxwday = $display->minwday + 6;
104 $content = '';
106 if(!empty($cal_month) && !empty($cal_year)) {
107 $thisdate = usergetdate(time()); // Date and time the user sees at his location
108 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
109 // Navigated to this month
110 $date = $thisdate;
111 $display->thismonth = true;
112 } else {
113 // Navigated to other month, let's do a nice trick and save us a lot of work...
114 if(!checkdate($cal_month, 1, $cal_year)) {
115 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
116 $display->thismonth = true;
117 } else {
118 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
119 $display->thismonth = false;
122 } else {
123 $date = usergetdate(time()); // Date and time the user sees at his location
124 $display->thismonth = true;
127 // Fill in the variables we 're going to use, nice and tidy
128 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
129 $display->maxdays = calendar_days_in_month($m, $y);
131 if (get_user_timezone_offset() < 99) {
132 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
133 $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
134 $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
135 } else {
136 // no timezone info specified
137 $display->tstart = mktime(0, 0, 0, $m, 1, $y);
138 $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y);
141 $startwday = dayofweek(1, $m, $y);
143 // Align the starting weekday to fall in our display range
144 // This is simple, not foolproof.
145 if($startwday < $display->minwday) {
146 $startwday += 7;
149 // TODO: THIS IS TEMPORARY CODE!
150 // [pj] I was just reading through this and realized that I when writing this code I was probably
151 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
152 // make_timestamp would accomplish the same thing. So here goes a test:
153 //$test_start = make_timestamp($y, $m, 1);
154 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
155 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
156 //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);
158 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
159 //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);
163 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
164 $events = calendar_get_events(
165 usertime($display->tstart) - dst_offset_on($display->tstart),
166 usertime($display->tend) - dst_offset_on($display->tend),
167 $users, $groups, $courses);
169 // Set event course class for course events
170 if (!empty($events)) {
171 foreach ($events as $eventid => $event) {
172 if (!empty($event->modulename)) {
173 $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
174 if (!groups_course_module_visible($cm)) {
175 unset($events[$eventid]);
181 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
182 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
183 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
184 // arguments to this function.
186 $hrefparams = array();
187 if(!empty($courses)) {
188 $courses = array_diff($courses, array(SITEID));
189 if(count($courses) == 1) {
190 $hrefparams['course'] = reset($courses);
194 // We want to have easy access by day, since the display is on a per-day basis.
195 // Arguments passed by reference.
196 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
197 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
199 //Accessibility: added summary and <abbr> elements.
200 ///global $CALENDARDAYS; appears to be broken.
201 $days_title = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
203 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
204 $summary = get_string('tabledata', 'access', $summary);
205 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table
206 $content .= '<tr class="weekdays">'; // Header row: day names
208 // Print out the names of the weekdays
209 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
210 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
211 // This uses the % operator to get the correct weekday no matter what shift we have
212 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
213 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
214 get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
217 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
219 // For the table display. $week is the row; $dayweek is the column.
220 $dayweek = $startwday;
222 // Paddding (the first week may have blank days in the beginning)
223 for($i = $display->minwday; $i < $startwday; ++$i) {
224 $content .= '<td class="dayblank">&nbsp;</td>'."\n";
227 // Now display all the calendar
228 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
229 if($dayweek > $display->maxwday) {
230 // We need to change week (table row)
231 $content .= '</tr><tr>';
232 $dayweek = $display->minwday;
235 // Reset vars
236 $cell = '';
237 if(CALENDAR_WEEKEND & (1 << ($dayweek % 7))) {
238 // Weekend. This is true no matter what the exact range is.
239 $class = 'weekend day';
240 } else {
241 // Normal working day.
242 $class = 'day';
245 // Special visual fx if an event is defined
246 if(isset($eventsbyday[$day])) {
247 $class .= ' hasevent';
248 $hrefparams['view'] = 'day';
249 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $hrefparams), $day, $m, $y);
251 $popupcontent = '';
252 foreach($eventsbyday[$day] as $eventid) {
253 if (!isset($events[$eventid])) {
254 continue;
256 $event = $events[$eventid];
257 $popupalt = '';
258 $component = 'moodle';
259 if(!empty($event->modulename)) {
260 $popupicon = 'icon';
261 $popupalt = $event->modulename;
262 $component = $event->modulename;
263 } else if ($event->courseid == SITEID) { // Site event
264 $popupicon = 'c/site';
265 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
266 $popupicon = 'c/course';
267 } else if ($event->groupid) { // Group event
268 $popupicon = 'c/group';
269 } else if ($event->userid) { // User event
270 $popupicon = 'c/user';
273 $dayhref->set_anchor('event_'.$event->id);
275 $popupcontent .= html_writer::start_tag('div');
276 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
277 $popupcontent .= html_writer::link($dayhref, format_string($event->name, true));
278 $popupcontent .= html_writer::end_tag('div');
281 //Accessibility: functionality moved to calendar_get_popup.
282 if($display->thismonth && $day == $d) {
283 $popup = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
284 } else {
285 $popup = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
288 // Class and cell content
289 if(isset($typesbyday[$day]['startglobal'])) {
290 $class .= ' calendar_event_global';
291 } else if(isset($typesbyday[$day]['startcourse'])) {
292 $class .= ' calendar_event_course';
293 } else if(isset($typesbyday[$day]['startgroup'])) {
294 $class .= ' calendar_event_group';
295 } else if(isset($typesbyday[$day]['startuser'])) {
296 $class .= ' calendar_event_user';
298 $cell = '<a href="'.(string)$dayhref.'" '.$popup.'>'.$day.'</a>';
299 } else {
300 $cell = $day;
303 $durationclass = false;
304 if (isset($typesbyday[$day]['durationglobal'])) {
305 $durationclass = ' duration_global';
306 } else if(isset($typesbyday[$day]['durationcourse'])) {
307 $durationclass = ' duration_course';
308 } else if(isset($typesbyday[$day]['durationgroup'])) {
309 $durationclass = ' duration_group';
310 } else if(isset($typesbyday[$day]['durationuser'])) {
311 $durationclass = ' duration_user';
313 if ($durationclass) {
314 $class .= ' duration '.$durationclass;
317 // If event has a class set then add it to the table day <td> tag
318 // Note: only one colour for minicalendar
319 if(isset($eventsbyday[$day])) {
320 foreach($eventsbyday[$day] as $eventid) {
321 if (!isset($events[$eventid])) {
322 continue;
324 $event = $events[$eventid];
325 if (!empty($event->class)) {
326 $class .= ' '.$event->class;
328 break;
332 // Special visual fx for today
333 //Accessibility: hidden text for today, and popup.
334 if($display->thismonth && $day == $d) {
335 $class .= ' today';
336 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
338 if(! isset($eventsbyday[$day])) {
339 $class .= ' eventnone';
340 $popup = calendar_get_popup(true, false);
341 $cell = '<a href="#" '.$popup.'>'.$day.'</a>';
343 $cell = get_accesshide($today.' ').$cell;
346 // Just display it
347 if(!empty($class)) {
348 $class = ' class="'.$class.'"';
350 $content .= '<td'.$class.'>'.$cell."</td>\n";
353 // Paddding (the last week may have blank days at the end)
354 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
355 $content .= '<td class="dayblank">&nbsp;</td>';
357 $content .= '</tr>'; // Last row ends
359 $content .= '</table>'; // Tabular display of days ends
361 return $content;
365 * calendar_get_popup, called at multiple points in from calendar_get_mini.
366 * Copied and modified from calendar_get_mini.
367 * @global moodle_page $PAGE
368 * @param $is_today bool, false except when called on the current day.
369 * @param $event_timestart mixed, $events[$eventid]->timestart, OR false if there are no events.
370 * @param $popupcontent string.
371 * @return $popup string, contains onmousover and onmouseout events.
373 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
374 global $PAGE;
375 static $popupcount;
376 if ($popupcount === null) {
377 $popupcount = 1;
379 $popupcaption = '';
380 if($is_today) {
381 $popupcaption = get_string('today', 'calendar').' ';
383 if (false === $event_timestart) {
384 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
385 $popupcontent = get_string('eventnone', 'calendar');
387 } else {
388 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
390 $id = 'calendar_tooltip_'.$popupcount;
391 $PAGE->requires->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
393 $popupcount++;
394 return 'id="'.$id.'"';
397 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
398 global $CFG, $COURSE, $DB;
400 $display = new stdClass;
401 $display->range = $daysinfuture; // How many days in the future we 'll look
402 $display->maxevents = $maxevents;
404 $output = array();
406 // Prepare "course caching", since it may save us a lot of queries
407 $coursecache = array();
409 $processed = 0;
410 $now = time(); // We 'll need this later
411 $usermidnighttoday = usergetmidnight($now);
413 if ($fromtime) {
414 $display->tstart = $fromtime;
415 } else {
416 $display->tstart = $usermidnighttoday;
419 // This works correctly with respect to the user's DST, but it is accurate
420 // only because $fromtime is always the exact midnight of some day!
421 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
423 // Get the events matching our criteria
424 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
426 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
427 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
428 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
429 // arguments to this function.
431 $hrefparams = array();
432 if(!empty($courses)) {
433 $courses = array_diff($courses, array(SITEID));
434 if(count($courses) == 1) {
435 $hrefparams['course'] = reset($courses);
439 if ($events !== false) {
441 $modinfo =& get_fast_modinfo($COURSE);
443 foreach($events as $event) {
446 if (!empty($event->modulename)) {
447 if ($event->courseid == $COURSE->id) {
448 if (isset($modinfo->instances[$event->modulename][$event->instance])) {
449 $cm = $modinfo->instances[$event->modulename][$event->instance];
450 if (!$cm->uservisible) {
451 continue;
454 } else {
455 if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
456 continue;
458 if (!coursemodule_visible_for_user($cm)) {
459 continue;
462 if ($event->modulename == 'assignment'){
463 // TODO: rewrite this hack somehow
464 if (!calendar_edit_event_allowed($event)){ // cannot manage entries, eg. student
465 if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance))) {
466 // print_error("invalidid", 'assignment');
467 continue;
469 // assign assignment to assignment object to use hidden_is_hidden method
470 require_once($CFG->dirroot.'/mod/assignment/lib.php');
472 if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php')) {
473 continue;
475 require_once ($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
477 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
478 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm);
480 if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
481 $event->description = get_string('notavailableyet', 'assignment');
487 if ($processed >= $display->maxevents) {
488 break;
491 $event->time = calendar_format_event_time($event, $now, $hrefparams);
492 $output[] = $event;
493 ++$processed;
496 return $output;
499 function calendar_add_event_metadata($event) {
500 global $CFG, $OUTPUT;
502 //Support multilang in event->name
503 $event->name = format_string($event->name,true);
505 if(!empty($event->modulename)) { // Activity event
506 // The module name is set. I will assume that it has to be displayed, and
507 // also that it is an automatically-generated event. And of course that the
508 // fields for get_coursemodule_from_instance are set correctly.
509 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
511 if ($module === false) {
512 return;
515 $modulename = get_string('modulename', $event->modulename);
516 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
517 // will be used as alt text if the event icon
518 $eventtype = get_string($event->eventtype, $event->modulename);
519 } else {
520 $eventtype = '';
522 $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
524 $event->icon = '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
525 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
526 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$coursecache[$module->course]->fullname.'</a>';
527 $event->cmid = $module->id;
530 } else if($event->courseid == SITEID) { // Site event
531 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/site') . '" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
532 $event->cssclass = 'calendar_event_global';
533 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
534 calendar_get_course_cached($coursecache, $event->courseid);
535 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/course') . '" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
536 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$coursecache[$event->courseid]->fullname.'</a>';
537 $event->cssclass = 'calendar_event_course';
538 } else if ($event->groupid) { // Group event
539 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/group') . '" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
540 $event->cssclass = 'calendar_event_group';
541 } else if($event->userid) { // User event
542 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/user') . '" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
543 $event->cssclass = 'calendar_event_user';
545 return $event;
549 * Prints a calendar event
551 * @deprecated 2.0
553 function calendar_print_event($event, $showactions=true) {
554 global $CFG, $USER, $OUTPUT, $PAGE;
555 debugging('calendar_print_event is deprecated please update your code', DEBUG_DEVELOPER);
556 $renderer = $PAGE->get_renderer('core_calendar');
557 if (!($event instanceof calendar_event)) {
558 $event = new calendar_event($event);
560 echo $renderer->event($event);
564 * Get calendar events
565 * @param int $tstart Start time of time range for events
566 * @param int $tend End time of time range for events
567 * @param array/int/boolean $users array of users, user id or boolean for all/no user events
568 * @param array/int/boolean $groups array of groups, group id or boolean for all/no group events
569 * @param array/int/boolean $courses array of courses, course id or boolean for all/no course events
570 * @param boolean $withduration whether only events starting within time range selected
571 * or events in progress/already started selected as well
572 * @param boolean $ignorehidden whether to select only visible events or all events
573 * @return array of selected events or an empty array if there aren't any (or there was an error)
575 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
576 global $DB;
578 $whereclause = '';
579 // Quick test
580 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
581 return array();
584 if(is_array($users) && !empty($users)) {
585 // Events from a number of users
586 if(!empty($whereclause)) $whereclause .= ' OR';
587 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
588 } else if(is_numeric($users)) {
589 // Events from one user
590 if(!empty($whereclause)) $whereclause .= ' OR';
591 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
592 } else if($users === true) {
593 // Events from ALL users
594 if(!empty($whereclause)) $whereclause .= ' OR';
595 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
596 } else if($users === false) {
597 // No user at all, do nothing
600 if(is_array($groups) && !empty($groups)) {
601 // Events from a number of groups
602 if(!empty($whereclause)) $whereclause .= ' OR';
603 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
604 } else if(is_numeric($groups)) {
605 // Events from one group
606 if(!empty($whereclause)) $whereclause .= ' OR ';
607 $whereclause .= ' groupid = '.$groups;
608 } else if($groups === true) {
609 // Events from ALL groups
610 if(!empty($whereclause)) $whereclause .= ' OR ';
611 $whereclause .= ' groupid != 0';
613 // boolean false (no groups at all): we don't need to do anything
615 if(is_array($courses) && !empty($courses)) {
616 if(!empty($whereclause)) {
617 $whereclause .= ' OR';
619 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
620 } else if(is_numeric($courses)) {
621 // One course
622 if(!empty($whereclause)) $whereclause .= ' OR';
623 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
624 } else if ($courses === true) {
625 // Events from ALL courses
626 if(!empty($whereclause)) $whereclause .= ' OR';
627 $whereclause .= ' (groupid = 0 AND courseid != 0)';
630 // Security check: if, by now, we have NOTHING in $whereclause, then it means
631 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
632 // events no matter what. Allowing the code to proceed might return a completely
633 // valid query with only time constraints, thus selecting ALL events in that time frame!
634 if(empty($whereclause)) {
635 return array();
638 if($withduration) {
639 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
641 else {
642 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
644 if(!empty($whereclause)) {
645 // We have additional constraints
646 $whereclause = $timeclause.' AND ('.$whereclause.')';
648 else {
649 // Just basic time filtering
650 $whereclause = $timeclause;
653 if ($ignorehidden) {
654 $whereclause .= ' AND visible = 1';
657 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
658 if ($events === false) {
659 $events = array();
661 return $events;
664 function calendar_top_controls($type, $data) {
665 global $CFG, $CALENDARDAYS;
666 $content = '';
667 if(!isset($data['d'])) {
668 $data['d'] = 1;
671 // Ensure course id passed if relevant
672 // Required due to changes in view/lib.php mainly (calendar_session_vars())
673 $courseid = '';
674 if (!empty($data['id'])) {
675 $courseid = '&amp;course='.$data['id'];
678 if(!checkdate($data['m'], $data['d'], $data['y'])) {
679 $time = time();
681 else {
682 $time = make_timestamp($data['y'], $data['m'], $data['d']);
684 $date = usergetdate($time);
686 $data['m'] = $date['mon'];
687 $data['y'] = $date['year'];
689 //Accessibility: calendar block controls, replaced <table> with <div>.
690 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
691 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
693 switch($type) {
694 case 'frontpage':
695 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
696 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
697 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
698 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
700 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
701 if (!empty($data['id'])) {
702 $calendarlink->param('course', $data['id']);
705 if (right_to_left()) {
706 $left = $nextlink;
707 $right = $prevlink;
708 } else {
709 $left = $prevlink;
710 $right = $nextlink;
713 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
714 $content .= $left.'<span class="hide"> | </span>';
715 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
716 $content .= '<span class="hide"> | </span>'. $right;
717 $content .= "<span class=\"clearer\"><!-- --></span>\n";
718 $content .= html_writer::end_tag('div');
720 break;
721 case 'course':
722 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
723 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
724 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $nextmonth, $nextyear, $accesshide=true);
725 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $prevmonth, $prevyear, true);
727 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
728 if (!empty($data['id'])) {
729 $calendarlink->param('course', $data['id']);
732 if (right_to_left()) {
733 $left = $nextlink;
734 $right = $prevlink;
735 } else {
736 $left = $prevlink;
737 $right = $nextlink;
740 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
741 $content .= $left.'<span class="hide"> | </span>';
742 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
743 $content .= '<span class="hide"> | </span>'. $right;
744 $content .= "<span class=\"clearer\"><!-- --></span>";
745 $content .= html_writer::end_tag('div');
746 break;
747 case 'upcoming':
748 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'upcoming')), 1, $data['m'], $data['y']);
749 if (!empty($data['id'])) {
750 $calendarlink->param('course', $data['id']);
752 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
753 $content .= html_writer::tag('div', $calendarlink, array('class'=>'centered'));
754 break;
755 case 'display':
756 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
757 if (!empty($data['id'])) {
758 $calendarlink->param('course', $data['id']);
760 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
761 $content .= html_writer::tag('h3', $calendarlink);
762 break;
763 case 'month':
764 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
765 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
766 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
767 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
768 $prevlink = calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $prevmonth, $prevyear);
769 $nextlink = calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $nextmonth, $nextyear);
771 if (right_to_left()) {
772 $left = $nextlink;
773 $right = $prevlink;
774 } else {
775 $left = $prevlink;
776 $right = $nextlink;
779 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
780 $content .= $left . '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>";
781 $content .= '<span class="hide"> | </span>' . $right;
782 $content .= '<span class="clearer"><!-- --></span>';
783 $content .= html_writer::end_tag('div')."\n";
784 break;
785 case 'day':
786 $data['d'] = $date['mday']; // Just for convenience
787 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
788 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
789 $prevname = calendar_wday_name($CALENDARDAYS[$prevdate['wday']]);
790 $nextname = calendar_wday_name($CALENDARDAYS[$nextdate['wday']]);
791 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
792 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
794 if (right_to_left()) {
795 $left = $nextlink;
796 $right = $prevlink;
797 } else {
798 $left = $prevlink;
799 $right = $nextlink;
802 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
803 $content .= $left;
804 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
805 $content .= '<span class="hide"> | </span>'. $right;
806 $content .= "<span class=\"clearer\"><!-- --></span>";
807 $content .= html_writer::end_tag('div')."\n";
809 break;
811 return $content;
814 function calendar_filter_controls($type, $vars = NULL, $course = NULL, $courses = NULL) {
815 global $CFG, $SESSION, $USER, $OUTPUT;
817 $groupevents = true;
818 $getvars = '';
820 $id = optional_param( 'id',0,PARAM_INT );
822 switch($type) {
823 case 'event':
824 case 'upcoming':
825 case 'day':
826 case 'month':
827 $getvars = '&amp;from='.$type;
828 break;
829 case 'course':
830 if ($id > 0) {
831 $getvars = '&amp;from=course&amp;id='.$id;
832 } else {
833 $getvars = '&amp;from=course';
835 if (isset($course->groupmode) and $course->groupmode == NOGROUPS and $course->groupmodeforce) {
836 $groupevents = false;
838 break;
841 if (!empty($vars)) {
842 $getvars .= '&amp;'.$vars;
845 $content = '<table>';
847 $content .= '<tr>';
848 if($SESSION->cal_show_global) {
849 $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='."'".CALENDAR_URL.'set.php?var=showglobal'.$getvars."'".'" /></td>';
850 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
851 } else {
852 $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='."'".CALENDAR_URL.'set.php?var=showglobal'.$getvars."'".'" /></td>';
853 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
855 if($SESSION->cal_show_course) {
856 $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='."'".CALENDAR_URL.'set.php?var=showcourses'.$getvars."'".'" /></td>';
857 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
858 } else {
859 $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='."'".CALENDAR_URL.'set.php?var=showcourses'.$getvars."'".'" /></td>';
860 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
865 if (isloggedin() && !isguestuser()) {
866 $content .= "</tr>\n<tr>";
868 if($groupevents) {
869 // This course MIGHT have group events defined, so show the filter
870 if($SESSION->cal_show_groups) {
871 $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='."'".CALENDAR_URL.'set.php?var=showgroups'.$getvars."'".'" /></td>';
872 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
873 } else {
874 $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='."'".CALENDAR_URL.'set.php?var=showgroups'.$getvars."'".'" /></td>';
875 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
877 } else {
878 // This course CANNOT have group events, so lose the filter
879 $content .= '<td style="width: 11px;"></td><td>&nbsp;</td>'."\n";
881 if($SESSION->cal_show_user) {
882 $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='."'".CALENDAR_URL.'set.php?var=showuser'.$getvars."'".'" /></td>';
883 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
884 } else {
885 $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='."'".CALENDAR_URL.'set.php?var=showuser'.$getvars."'".'" /></td>';
886 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
889 $content .= "</tr>\n</table>\n";
891 return $content;
894 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
896 static $shortformat;
897 if(empty($shortformat)) {
898 $shortformat = get_string('strftimedayshort');
901 if($now === false) {
902 $now = time();
905 // To have it in one place, if a change is needed
906 $formal = userdate($tstamp, $shortformat);
908 $datestamp = usergetdate($tstamp);
909 $datenow = usergetdate($now);
911 if($usecommonwords == false) {
912 // We don't want words, just a date
913 return $formal;
915 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
916 // Today
917 return get_string('today', 'calendar');
919 else if(
920 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
921 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
923 // Yesterday
924 return get_string('yesterday', 'calendar');
926 else if(
927 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
928 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
930 // Tomorrow
931 return get_string('tomorrow', 'calendar');
933 else {
934 return $formal;
938 function calendar_time_representation($time) {
939 static $langtimeformat = NULL;
940 if($langtimeformat === NULL) {
941 $langtimeformat = get_string('strftimetime');
943 $timeformat = get_user_preferences('calendar_timeformat');
944 if(empty($timeformat)){
945 $timeformat = get_config(NULL,'calendar_site_timeformat');
947 // The ? is needed because the preference might be present, but empty
948 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
952 * Adds day, month, year arguments to a URL and returns a moodle_url object.
954 * @param string|moodle_url $linkbase
955 * @param int $d
956 * @param int $m
957 * @param int $y
958 * @return moodle_url
960 function calendar_get_link_href($linkbase, $d, $m, $y) {
961 if (empty($linkbase)) {
962 return '';
964 if (!($linkbase instanceof moodle_url)) {
965 $linkbase = new moodle_url();
967 if (!empty($d)) {
968 $linkbase->param('cal_d', $d);
970 if (!empty($m)) {
971 $linkbase->param('cal_m', $m);
973 if (!empty($y)) {
974 $linkbase->param('cal_y', $y);
976 return $linkbase;
980 * This function has been deprecated as of Moodle 2.0... DO NOT USE!!!!!
982 * @deprecated
983 * @since 2.0
985 * @param string $text
986 * @param string|moodle_url $linkbase
987 * @param int|null $d
988 * @param int|null $m
989 * @param int|null $y
990 * @return string HTML link
992 function calendar_get_link_tag($text, $linkbase, $d, $m, $y) {
993 $url = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
994 if (empty($url)) {
995 return $text;
997 return html_writer::link($url, $text);
1001 * Build and return a previous month HTML link, with an arrow.
1003 * @param string $text The text label.
1004 * @param string|moodle_url $linkbase The URL stub.
1005 * @param int $d $m $y Day of month, month and year numbers.
1006 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1007 * @return string HTML string.
1009 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
1010 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1011 if (empty($href)) {
1012 return $text;
1014 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
1018 * Build and return a next month HTML link, with an arrow.
1020 * @param string $text The text label.
1021 * @param string|moodle_url $linkbase The URL stub.
1022 * @param int $d $m $y Day of month, month and year numbers.
1023 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1024 * @return string HTML string.
1026 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
1027 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1028 if (empty($href)) {
1029 return $text;
1031 return link_arrow_right($text, (string)$href, $accesshide, 'next');
1034 function calendar_wday_name($englishname) {
1035 return get_string(strtolower($englishname), 'calendar');
1038 function calendar_days_in_month($month, $year) {
1039 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
1042 function calendar_get_block_upcoming($events, $linkhref = NULL) {
1043 $content = '';
1044 $lines = count($events);
1045 if (!$lines) {
1046 return $content;
1049 for ($i = 0; $i < $lines; ++$i) {
1050 if (!isset($events[$i]->time)) { // Just for robustness
1051 continue;
1053 $events[$i] = calendar_add_event_metadata($events[$i]);
1054 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
1055 if (!empty($events[$i]->referer)) {
1056 // That's an activity event, so let's provide the hyperlink
1057 $content .= $events[$i]->referer;
1058 } else {
1059 if(!empty($linkhref)) {
1060 $ed = usergetdate($events[$i]->timestart);
1061 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL.$linkhref), $ed['mday'], $ed['mon'], $ed['year']);
1062 $href->set_anchor('event_'.$events[$i]->id);
1063 $content .= html_writer::link($href, $events[$i]->name);
1065 else {
1066 $content .= $events[$i]->name;
1069 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
1070 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
1071 if ($i < $lines - 1) $content .= '<hr />';
1074 return $content;
1077 function calendar_add_month($month, $year) {
1078 if($month == 12) {
1079 return array(1, $year + 1);
1081 else {
1082 return array($month + 1, $year);
1086 function calendar_sub_month($month, $year) {
1087 if($month == 1) {
1088 return array(12, $year - 1);
1090 else {
1091 return array($month - 1, $year);
1095 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1096 $eventsbyday = array();
1097 $typesbyday = array();
1098 $durationbyday = array();
1100 if($events === false) {
1101 return;
1104 foreach($events as $event) {
1106 $startdate = usergetdate($event->timestart);
1107 // Set end date = start date if no duration
1108 if ($event->timeduration) {
1109 $enddate = usergetdate($event->timestart + $event->timeduration - 1);
1110 } else {
1111 $enddate = $startdate;
1114 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1115 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1116 // Out of bounds
1117 continue;
1120 $eventdaystart = intval($startdate['mday']);
1122 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1123 // Give the event to its day
1124 $eventsbyday[$eventdaystart][] = $event->id;
1126 // Mark the day as having such an event
1127 if($event->courseid == SITEID && $event->groupid == 0) {
1128 $typesbyday[$eventdaystart]['startglobal'] = true;
1129 // Set event class for global event
1130 $events[$event->id]->class = 'calendar_event_global';
1132 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1133 $typesbyday[$eventdaystart]['startcourse'] = true;
1134 // Set event class for course event
1135 $events[$event->id]->class = 'calendar_event_course';
1137 else if($event->groupid) {
1138 $typesbyday[$eventdaystart]['startgroup'] = true;
1139 // Set event class for group event
1140 $events[$event->id]->class = 'calendar_event_group';
1142 else if($event->userid) {
1143 $typesbyday[$eventdaystart]['startuser'] = true;
1144 // Set event class for user event
1145 $events[$event->id]->class = 'calendar_event_user';
1149 if($event->timeduration == 0) {
1150 // Proceed with the next
1151 continue;
1154 // The event starts on $month $year or before. So...
1155 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
1157 // Also, it ends on $month $year or later...
1158 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1160 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1161 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1162 $durationbyday[$i][] = $event->id;
1163 if($event->courseid == SITEID && $event->groupid == 0) {
1164 $typesbyday[$i]['durationglobal'] = true;
1166 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1167 $typesbyday[$i]['durationcourse'] = true;
1169 else if($event->groupid) {
1170 $typesbyday[$i]['durationgroup'] = true;
1172 else if($event->userid) {
1173 $typesbyday[$i]['durationuser'] = true;
1178 return;
1181 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1182 $module = get_coursemodule_from_instance($modulename, $instance);
1184 if($module === false) return false;
1185 if(!calendar_get_course_cached($coursecache, $module->course)) {
1186 return false;
1188 return $module;
1191 function calendar_get_course_cached(&$coursecache, $courseid) {
1192 global $COURSE, $DB;
1194 if (!isset($coursecache[$courseid])) {
1195 if ($courseid == $COURSE->id) {
1196 $coursecache[$courseid] = $COURSE;
1197 } else {
1198 $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
1201 return $coursecache[$courseid];
1204 function calendar_session_vars($course=null) {
1205 global $SESSION, $USER;
1207 if(!isset($SESSION->cal_course_referer)) {
1208 $SESSION->cal_course_referer = 0;
1210 if(!isset($SESSION->cal_show_global)) {
1211 $SESSION->cal_show_global = true;
1213 if(!isset($SESSION->cal_show_groups)) {
1214 $SESSION->cal_show_groups = true;
1216 if(!isset($SESSION->cal_show_course)) {
1217 $SESSION->cal_show_course = true;
1219 if(!isset($SESSION->cal_show_user)) {
1220 $SESSION->cal_show_user = true;
1222 if ($course !== null) {
1223 // speedup hack for calendar related blocks
1224 if(isset($course->coursenode)) {
1225 // coursenode has been set up, which seems to break things further down the line.
1226 // Use a clone of $course with coursenode removed.
1227 $course = clone $course;
1228 unset($course->coursenode);
1230 $SESSION->cal_courses_shown = array($course->id => $course);
1231 } else {
1232 $SESSION->cal_courses_shown = calendar_get_default_courses(true);
1234 if(empty($SESSION->cal_users_shown)) {
1235 // The empty() instead of !isset() here makes a whole world of difference,
1236 // as it will automatically change to the user's id when the user first logs
1237 // in. With !isset(), it would never do that.
1238 $SESSION->cal_users_shown = isloggedin() ? $USER->id : false;
1239 } else if(is_numeric($SESSION->cal_users_shown) && isloggedin() && $SESSION->cal_users_shown != $USER->id) {
1240 // Follow the white rabbit, for example if a teacher logs in as a student
1241 $SESSION->cal_users_shown = $USER->id;
1245 function calendar_set_referring_course($courseid) {
1246 global $SESSION;
1247 $SESSION->cal_course_referer = intval($courseid);
1250 function calendar_set_filters(&$courses, &$group, &$user, $courseeventsfrom = NULL, $groupeventsfrom = NULL, $ignorefilters = false) {
1251 global $SESSION, $USER, $CFG, $DB;
1253 // Insidious bug-wannabe: setting $SESSION->cal_courses_shown to $course->id would cause
1254 // the code to function incorrectly UNLESS we convert it to an integer. One case where
1255 // PHP's loose type system works against us.
1256 if(is_string($SESSION->cal_courses_shown)) {
1257 $SESSION->cal_courses_shown = intval($SESSION->cal_courses_shown);
1259 if($courseeventsfrom === NULL) {
1260 $courseeventsfrom = $SESSION->cal_courses_shown;
1263 // MDL-9059, $courseeventsfrom can be an int, or an array of ints, or an array of course objects
1264 // convert all to array of objects
1265 // we probably should do some clean up and make sure that session is set to use the proper form
1266 if (is_int($courseeventsfrom)) { // case of an int, e.g. calendar view page
1267 $c = array();
1268 $c[$courseeventsfrom] = $DB->get_record('course', array('id'=>$courseeventsfrom));
1269 $courseeventsfrom = $c;
1270 } else if (is_array($courseeventsfrom)) { // case of an array of ints, e.g. course home page
1271 foreach ($courseeventsfrom as $i=>$courseid) { // TODO: this seems wrong, the array is often constructed as [courseid] => 1 ???
1272 if (is_int($courseid)) {
1273 $courseeventsfrom[$i] = $DB->get_record('course', array('id'=>$courseid));
1278 if($groupeventsfrom === NULL) {
1279 $groupeventsfrom = $SESSION->cal_courses_shown;
1282 if(($SESSION->cal_show_course && $SESSION->cal_show_global) || $ignorefilters) {
1283 if(is_int($courseeventsfrom)) {
1284 $courses = array(SITEID, $courseeventsfrom);
1286 else if(is_array($courseeventsfrom)) {
1287 $courses = array_keys($courseeventsfrom);
1288 $courses[] = SITEID;
1291 else if($SESSION->cal_show_course) {
1292 if(is_int($courseeventsfrom)) {
1293 $courses = array($courseeventsfrom);
1295 else if(is_array($courseeventsfrom)) {
1296 $courses = array_keys($courseeventsfrom);
1298 $courses = array_diff($courses, array(SITEID));
1300 else if($SESSION->cal_show_global) {
1301 $courses = array(SITEID);
1303 else {
1304 $courses = false;
1306 //BUG 6130 clean $courses array as SESSION has bad entries.
1307 // [pj] TODO: See if this has to do with my new change in get_default_courses and can be taken out
1308 if (is_array($courses)) {
1309 foreach ($courses as $index => $value) {
1310 if (empty($value)) unset($courses[$index]);
1313 // Sort courses for consistent colour highlighting
1314 // Effectively ignoring SITEID as setting as last course id
1315 $key = array_search(SITEID, $courses);
1316 if ($key !== false) {
1317 unset($courses[$key]);
1318 sort($courses);
1319 $courses[] = SITEID;
1320 } else {
1321 sort($courses);
1325 if($SESSION->cal_show_user || $ignorefilters) {
1326 // This doesn't work for arrays yet (maybe someday it will)
1327 $user = $SESSION->cal_users_shown;
1329 else {
1330 $user = false;
1332 if($SESSION->cal_show_groups || $ignorefilters) {
1333 if(is_int($groupeventsfrom)) {
1334 $groupcourses = array($groupeventsfrom);
1336 else if(is_array($groupeventsfrom)) {
1337 $groupcourses = array_keys($groupeventsfrom);
1340 // XXX TODO: not sure how to replace $CFG->calendar_adminseesall
1341 if(has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM)) && !empty($CFG->calendar_adminseesall)) {
1342 $group = true;
1344 else {
1345 $grouparray = array();
1347 // We already have the courses to examine in $courses
1348 // For each course...
1350 foreach($groupcourses as $courseid) {
1352 if (!isset($courseeventsfrom[$courseid]->context)) { // SHOULD be set MDL-11221
1353 if (is_object($courseeventsfrom[$courseid])) {
1354 $courseeventsfrom[$courseid]->context = get_context_instance(CONTEXT_COURSE, $courseid);
1358 // If the user is an editing teacher in there,
1359 if (isloggedin() && isset($courseeventsfrom[$courseid]->context) && has_capability('moodle/calendar:manageentries', $courseeventsfrom[$courseid]->context)) {
1360 // If this course has groups, show events from all of them
1361 if(is_int($groupeventsfrom)) {
1362 if (is_object($courseeventsfrom[$courseid])) { // SHOULD be set MDL-11221
1363 $courserecord = $courseeventsfrom[$courseid];
1364 } else {
1365 $courserecord = $DB->get_record('course', array('id'=>$courseid));
1367 $courserecord = $DB->get_record('course', array('id'=>$courseid));
1368 if ($courserecord->groupmode != NOGROUPS || !$courserecord->groupmodeforce) {
1369 $groupids[] = $courseid;
1372 else if(isset($SESSION->cal_courses_shown[$courseid]) && ($SESSION->cal_courses_shown[$courseid]->groupmode != NOGROUPS || !$SESSION->cal_courses_shown[$courseid]->groupmodeforce)) {
1373 $groupids[] = $courseid;
1377 // Otherwise (not editing teacher) show events from the group he is a member of
1378 else if(isset($USER->groupmember[$courseid])) {
1379 //changed to 2D array
1380 foreach ($USER->groupmember[$courseid] as $groupid){
1381 $grouparray[] = $groupid;
1386 if (!empty($groupids)) {
1387 $sql = "SELECT *
1388 FROM {groups}
1389 WHERE courseid IN (".implode(',', $groupids).')';
1391 if ($grouprecords = $DB->get_records_sql($sql, null)) {
1392 foreach ($grouprecords as $grouprecord) {
1393 $grouparray[] = $grouprecord->id;
1398 if(empty($grouparray)) {
1399 $group = false;
1401 else {
1402 $group = $grouparray;
1407 else {
1408 $group = false;
1412 function calendar_edit_event_allowed($event) {
1413 global $USER, $DB;
1415 // Must be logged in
1416 if (!isloggedin()) {
1417 return false;
1420 // can not be using guest account
1421 if (isguestuser()) {
1422 return false;
1425 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1426 // if user has manageentries at site level, return true
1427 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1428 return true;
1431 // if groupid is set, it's definitely a group event
1432 if (!empty($event->groupid)) {
1433 // Allow users to add/edit group events if:
1434 // 1) They have manageentries (= entries for whole course)
1435 // 2) They have managegroupentries AND are in the group
1436 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1437 return $group && (
1438 has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $group->courseid)) ||
1439 (has_capability('moodle/calendar:managegroupentries', get_context_instance(CONTEXT_COURSE, $group->courseid))
1440 && groups_is_member($event->groupid)));
1441 } else if (!empty($event->courseid)) {
1442 // if groupid is not set, but course is set,
1443 // it's definiely a course event
1444 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1445 } else if (!empty($event->userid) && $event->userid == $USER->id) {
1446 // if course is not set, but userid id set, it's a user event
1447 return (has_capability('moodle/calendar:manageownentries', $sitecontext));
1449 return false;
1452 function calendar_get_default_courses($ignoreref = false) {
1453 global $USER, $CFG, $SESSION, $DB;
1455 if(!empty($SESSION->cal_course_referer) && !$ignoreref) {
1456 return array($SESSION->cal_course_referer => 1);
1459 if (!isloggedin()) {
1460 return array();
1463 $courses = array();
1464 if (has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
1465 if (!empty($CFG->calendar_adminseesall)) {
1466 $courses = $DB->get_records_sql('SELECT id, 1 FROM {course}');
1467 return $courses;
1471 $courses = enrol_get_my_courses();
1473 return $courses;
1476 function calendar_preferences_button() {
1477 global $CFG, $USER;
1479 // Guests have no preferences
1480 if (!isloggedin() || isguestuser()) {
1481 return '';
1484 return "<form method=\"get\" ".
1485 " action=\"$CFG->wwwroot/calendar/preferences.php\">".
1486 "<div><input type=\"submit\" value=\"".get_string("preferences", "calendar")." ...\" /></div></form>";
1489 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime=0) {
1490 $startdate = usergetdate($event->timestart);
1491 $enddate = usergetdate($event->timestart + $event->timeduration);
1492 $usermidnightstart = usergetmidnight($event->timestart);
1494 if($event->timeduration) {
1495 // To avoid doing the math if one IF is enough :)
1496 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1498 else {
1499 $usermidnightend = $usermidnightstart;
1502 if (empty($linkparams) || !is_array($linkparams)) {
1503 $linkparams = array();
1505 $linkparams['view'] = 'day';
1507 // OK, now to get a meaningful display...
1508 // First of all we have to construct a human-readable date/time representation
1510 if($event->timeduration) {
1511 // It has a duration
1512 if($usermidnightstart == $usermidnightend ||
1513 ($event->timestart == $usermidnightstart) && ($event->timeduration == 86400 || $event->timeduration == 86399) ||
1514 ($event->timestart + $event->timeduration <= $usermidnightstart + 86400)) {
1515 // But it's all on the same day
1516 $timestart = calendar_time_representation($event->timestart);
1517 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1518 $time = $timestart.' <strong>&raquo;</strong> '.$timeend;
1520 if ($event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399)) {
1521 $time = get_string('allday', 'calendar');
1524 // Set printable representation
1525 if (!$showtime) {
1526 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1527 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1528 $eventtime = html_writer::link($url, $day).', '.$time;
1529 } else {
1530 $eventtime = $time;
1532 } else {
1533 // It spans two or more days
1534 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords).', ';
1535 if ($showtime == $usermidnightstart) {
1536 $daystart = '';
1538 $timestart = calendar_time_representation($event->timestart);
1539 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords).', ';
1540 if ($showtime == $usermidnightend) {
1541 $dayend = '';
1543 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1545 // Set printable representation
1546 if ($now >= $usermidnightstart && $now < ($usermidnightstart + 86400)) {
1547 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1548 $eventtime = $timestart.' <strong>&raquo;</strong> '.html_writer::link($url, $dayend).$timeend;
1549 } else {
1550 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1551 $eventtime = html_writer::link($url, $daystart).$timestart.' <strong>&raquo;</strong> ';
1553 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1554 $eventtime .= html_writer::link($url, $dayend).$timeend;
1557 } else {
1558 $time = ' ';
1560 // Set printable representation
1561 if (!$showtime) {
1562 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1563 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1564 $eventtime = html_writer::link($url, $day).trim($time);
1565 } else {
1566 $eventtime = $time;
1570 if($event->timestart + $event->timeduration < $now) {
1571 // It has expired
1572 $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
1575 return $eventtime;
1578 function calendar_print_month_selector($name, $selected) {
1579 $months = array();
1580 for ($i=1; $i<=12; $i++) {
1581 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1583 echo html_writer::select($months, $name, $selected, false);
1586 function calendar_get_filters_status() {
1587 global $SESSION;
1589 $status = 0;
1590 if($SESSION->cal_show_global) {
1591 $status += 1;
1593 if($SESSION->cal_show_course) {
1594 $status += 2;
1596 if($SESSION->cal_show_groups) {
1597 $status += 4;
1599 if($SESSION->cal_show_user) {
1600 $status += 8;
1602 return $status;
1605 function calendar_set_filters_status($packed_bitfield) {
1606 global $SESSION, $USER;
1608 if (!isloggedin()) {
1609 return false;
1612 $SESSION->cal_show_global = ($packed_bitfield & 1);
1613 $SESSION->cal_show_course = ($packed_bitfield & 2);
1614 $SESSION->cal_show_groups = ($packed_bitfield & 4);
1615 $SESSION->cal_show_user = ($packed_bitfield & 8);
1617 return true;
1620 function calendar_get_allowed_types(&$allowed) {
1621 global $USER, $CFG, $SESSION, $DB;
1622 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1623 $allowed->user = has_capability('moodle/calendar:manageownentries', $sitecontext);
1624 $allowed->groups = false; // This may change just below
1625 $allowed->courses = false; // This may change just below
1626 $allowed->site = has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
1628 if(!empty($SESSION->cal_course_referer) && $SESSION->cal_course_referer != SITEID) {
1629 $course = $DB->get_record('course', array('id'=>$SESSION->cal_course_referer));
1630 $coursecontext = get_context_instance(CONTEXT_COURSE, $SESSION->cal_course_referer);
1632 if(has_capability('moodle/calendar:manageentries', $coursecontext)) {
1633 $allowed->courses = array($course->id => 1);
1635 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1636 $allowed->groups = groups_get_all_groups($SESSION->cal_course_referer);
1638 } else if(has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1639 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1640 $allowed->groups = groups_get_all_groups($SESSION->cal_course_referer, $USER->id);
1647 * see if user can add calendar entries at all
1648 * used to print the "New Event" button
1649 * @return bool
1651 function calendar_user_can_add_event() {
1652 calendar_get_allowed_types($allowed);
1653 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
1657 * Check wether the current user is permitted to add events
1659 * @param object $event
1660 * @return bool
1662 function calendar_add_event_allowed($event) {
1663 global $USER, $DB;
1665 // can not be using guest account
1666 if (!isloggedin() or isguestuser()) {
1667 return false;
1670 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1671 // if user has manageentries at site level, always return true
1672 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1673 return true;
1676 switch ($event->eventtype) {
1677 case 'course':
1678 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1680 case 'group':
1681 // Allow users to add/edit group events if:
1682 // 1) They have manageentries (= entries for whole course)
1683 // 2) They have managegroupentries AND are in the group
1684 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1685 return $group && (
1686 has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $group->courseid)) ||
1687 (has_capability('moodle/calendar:managegroupentries', get_context_instance(CONTEXT_COURSE, $group->courseid))
1688 && groups_is_member($event->groupid)));
1690 case 'user':
1691 if ($event->userid == $USER->id) {
1692 return (has_capability('moodle/calendar:manageownentries', $sitecontext));
1694 //there is no 'break;' intentionally
1696 case 'site':
1697 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
1699 default:
1700 if (isset($event->courseid) && $event->courseid > 0) {
1701 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1703 return false;
1708 * A class to manage calendar events
1710 * This class provides the required functionality in order to manage calendar events.
1711 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1712 * better framework for dealing with calendar events in particular regard to file
1713 * handling through the new file API
1715 * @property int $id The id within the event table
1716 * @property string $name The name of the event
1717 * @property string $description The description of the event
1718 * @property int $format The format of the description FORMAT_?
1719 * @property int $courseid The course the event is associated with (0 if none)
1720 * @property int $groupid The group the event is associated with (0 if none)
1721 * @property int $userid The user the event is associated with (0 if none)
1722 * @property int $repeatid If this is a repeated event this will be set to the
1723 * id of the original
1724 * @property string $modulename If added by a module this will be the module name
1725 * @property int $instance If added by a module this will be the module instance
1726 * @property string $eventtype The event type
1727 * @property int $timestart The start time as a timestamp
1728 * @property int $timeduration The duration of the event in seconds
1729 * @property int $visible 1 if the event is visible
1730 * @property int $uuid ?
1731 * @property int $sequence ?
1732 * @property int $timemodified The time last modified as a timestamp
1734 class calendar_event {
1737 * An object containing the event properties can be accessed via the
1738 * magic __get/set methods
1739 * @var array
1741 protected $properties = null;
1743 * The converted event discription with file paths resolved
1744 * This gets populated when someone requests description for the first time
1745 * @var string
1747 protected $_description = null;
1749 * The options to use with this description editor
1750 * @var array
1752 protected $editoroptions = array(
1753 'subdirs'=>false,
1754 'forcehttps'=>false,
1755 'maxfiles'=>-1,
1756 'maxbytes'=>null,
1757 'trusttext'=>false);
1759 * The context to use with the description editor
1760 * @var object
1762 protected $editorcontext = null;
1765 * Instantiates a new event and optionally populates its properties with the
1766 * data provided
1768 * @param stdClass $data Optional. An object containing the properties to for
1769 * an event
1771 public function __construct($data=null) {
1772 global $CFG, $USER;
1774 // First convert to object if it is not already (should either be object or assoc array)
1775 if (!is_object($data)) {
1776 $data = (object)$data;
1779 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
1781 $data->eventrepeats = 0;
1783 if (empty($data->id)) {
1784 $data->id = null;
1787 // Default to a user event
1788 if (empty($data->eventtype)) {
1789 $data->eventtype = 'user';
1792 // Default to the current user
1793 if (empty($data->userid)) {
1794 $data->userid = $USER->id;
1797 if (!empty($data->timeduration) && is_array($data->timeduration)) {
1798 $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
1800 if (!empty($data->description) && is_array($data->description)) {
1801 $data->format = $data->description['format'];
1802 $data->description = $data->description['text'];
1803 } else if (empty($data->description)) {
1804 $data->description = '';
1805 $data->format = editors_get_preferred_format();
1807 // Ensure form is defaulted correctly
1808 if (empty($data->format)) {
1809 $data->format = editors_get_preferred_format();
1812 $this->properties = $data;
1816 * Magic property method
1818 * Attempts to call a set_$key method if one exists otherwise falls back
1819 * to simply set the property
1821 * @param string $key
1822 * @param mixed $value
1824 public function __set($key, $value) {
1825 if (method_exists($this, 'set_'.$key)) {
1826 $this->{'set_'.$key}($value);
1828 $this->properties->{$key} = $value;
1832 * Magic get method
1834 * Attempts to call a get_$key method to return the property and ralls over
1835 * to return the raw property
1837 * @param str $key
1838 * @return mixed
1840 public function __get($key) {
1841 if (method_exists($this, 'get_'.$key)) {
1842 return $this->{'get_'.$key}();
1844 if (!isset($this->properties->{$key})) {
1845 throw new coding_exception('Undefined property requested');
1847 return $this->properties->{$key};
1851 * Stupid PHP needs an isset magic method if you use the get magic method and
1852 * still want empty calls to work.... blah ~!
1854 * @param string $key
1855 * @return bool
1857 public function __isset($key) {
1858 return !empty($this->properties->{$key});
1862 * Returns an array of editoroptions for this event: Called by __get
1863 * Please use $blah = $event->editoroptions;
1864 * @return array
1866 protected function get_editoroptions() {
1867 return $this->editoroptions;
1871 * Returns an event description: Called by __get
1872 * Please use $blah = $event->description;
1874 * @return string
1876 protected function get_description() {
1877 global $USER, $CFG;
1879 require_once($CFG->libdir . '/filelib.php');
1881 if ($this->_description === null) {
1882 // Check if we have already resolved the context for this event
1883 if ($this->editorcontext === null) {
1884 // Switch on the event type to decide upon the appropriate context
1885 // to use for this event
1886 switch ($this->properties->eventtype) {
1887 case 'course':
1888 case 'group':
1889 // Course and group event files are served from the course context
1890 // and there are checks in plugin.php to ensure permissions are
1891 // followed
1892 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
1893 break;
1894 case 'user':
1895 // User context
1896 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
1897 break;
1898 case 'site':
1899 // Site context
1900 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
1901 break;
1902 default:
1903 // Hmmmm some modules use custom eventtype strings, if that is the
1904 // case we are going to abandon using files. Anything that uses a
1905 // custom type is being added manually through code
1906 return clean_text($this->properties->description, $this->properties->format);
1907 break;
1911 // Work out the item id for the editor, if this is a repeated event then the files will
1912 // be associated with the original
1913 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
1914 $itemid = $this->properties->repeatid;
1915 } else {
1916 $itemid = $this->properties->id;
1919 // Convert file paths in the description so that things display correctly
1920 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, 'calendar', 'event_description', $itemid);
1921 // Clean the text so no nasties get through
1922 $this->_description = clean_text($this->_description, $this->properties->format);
1924 // Finally return the description
1925 return $this->_description;
1929 * Return the number of repeat events there are in this events series
1931 * @return int
1933 public function count_repeats() {
1934 global $DB;
1935 if (!empty($this->properties->repeatid)) {
1936 $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
1937 // We don't want to count ourselves
1938 $this->properties->eventrepeats--;
1940 return $this->properties->eventrepeats;
1944 * Update or create an event within the database
1946 * Pass in a object containing the event properties and this function will
1947 * insert it into the database and deal with any associated files
1949 * @see add_event()
1950 * @see update_event()
1952 * @param stdClass $data
1953 * @param boolean $checkcapability if moodle should check calendar managing capability or not
1955 public function update($data, $checkcapability=true) {
1956 global $CFG, $DB, $USER;
1958 foreach ($data as $key=>$value) {
1959 $this->properties->$key = $value;
1962 $this->properties->timemodified = time();
1963 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
1965 if (empty($this->properties->id) || $this->properties->id < 1) {
1967 if ($checkcapability) {
1968 if (!calendar_add_event_allowed($this->properties)) {
1969 print_error('nopermissiontoupdatecalendar');
1973 if ($usingeditor) {
1974 switch ($this->properties->eventtype) {
1975 case 'user':
1976 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
1977 $this->properties->courseid = 0;
1978 $this->properties->groupid = 0;
1979 $this->properties->userid = $USER->id;
1980 break;
1981 case 'site':
1982 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
1983 $this->properties->courseid = SITEID;
1984 $this->properties->groupid = 0;
1985 $this->properties->userid = $USER->id;
1986 break;
1987 case 'course':
1988 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
1989 $this->properties->groupid = 0;
1990 $this->properties->userid = $USER->id;
1991 break;
1992 case 'group':
1993 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
1994 $this->properties->userid = $USER->id;
1995 break;
1996 default:
1997 // Ewww we should NEVER get here, but just incase we do lets
1998 // fail gracefully
1999 $usingeditor = false;
2000 break;
2003 $editor = $this->properties->description;
2004 $this->properties->format = $this->properties->description['format'];
2005 $this->properties->description = $this->properties->description['text'];
2008 // Insert the event into the database
2009 $this->properties->id = $DB->insert_record('event', $this->properties);
2011 if ($usingeditor) {
2012 $this->properties->description = file_save_draft_area_files(
2013 $editor['itemid'],
2014 $this->editorcontext->id,
2015 'calendar',
2016 'event_description',
2017 $this->properties->id,
2018 $this->editoroptions,
2019 $editor['text'],
2020 $this->editoroptions['forcehttps']);
2022 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
2025 // Log the event entry.
2026 add_to_log($this->properties->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2028 $repeatedids = array();
2030 if (!empty($this->properties->repeat)) {
2031 $this->properties->repeatid = $this->properties->id;
2032 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));
2034 $eventcopy = clone($this->properties);
2035 unset($eventcopy->id);
2037 for($i = 1; $i < $eventcopy->repeats; $i++) {
2039 $eventcopy->timestart = ($eventcopy->timestart+WEEKSECS) + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart+WEEKSECS);
2041 // Get the event id for the log record.
2042 $eventcopyid = $DB->insert_record('event', $eventcopy);
2044 // If the context has been set delete all associated files
2045 if ($usingeditor) {
2046 $fs = get_file_storage();
2047 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2048 foreach ($files as $file) {
2049 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
2053 $repeatedids[] = $eventcopyid;
2054 // Log the event entry.
2055 add_to_log($eventcopy->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$eventcopyid, $eventcopy->name);
2059 // Hook for tracking added events
2060 self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
2061 return true;
2062 } else {
2064 if ($checkcapability) {
2065 if(!calendar_edit_event_allowed($this->properties)) {
2066 print_error('nopermissiontoupdatecalendar');
2070 if ($usingeditor) {
2071 if ($this->editorcontext !== null) {
2072 $this->properties->description = file_save_draft_area_files(
2073 $this->properties->description['itemid'],
2074 $this->editorcontext->id,
2075 'calendar',
2076 'event_description',
2077 $this->properties->id,
2078 $this->editoroptions,
2079 $this->properties->description['text'],
2080 $this->editoroptions['forcehttps']);
2081 } else {
2082 $this->properties->format = $this->properties->description['format'];
2083 $this->properties->description = $this->properties->description['text'];
2087 $event = $DB->get_record('event', array('id'=>$this->properties->id));
2089 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
2091 if ($updaterepeated) {
2092 // Update all
2093 if ($this->properties->timestart != $event->timestart) {
2094 $timestartoffset = $this->properties->timestart - $event->timestart;
2095 $sql = "UPDATE {event}
2096 SET name = ?,
2097 description = ?,
2098 timestart = timestart + ?,
2099 timeduration = ?,
2100 timemodified = ?
2101 WHERE repeatid = ?";
2102 $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
2103 } else {
2104 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2105 $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
2107 $DB->execute($sql, $params);
2109 // Log the event update.
2110 add_to_log($this->properties->courseid, 'calendar', 'edit all', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2111 } else {
2112 $DB->update_record('event', $this->properties);
2113 $event = calendar_event::load($this->properties->id);
2114 $this->properties = $event->properties();
2115 add_to_log($this->properties->courseid, 'calendar', 'edit', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2118 // Hook for tracking event updates
2119 self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
2120 return true;
2125 * Deletes an event and if selected an repeated events in the same series
2127 * This function deletes an event, any associated events if $deleterepeated=true,
2128 * and cleans up any files associated with the events.
2130 * @see delete_event()
2132 * @param bool $deleterepeated
2133 * @return bool
2135 public function delete($deleterepeated=false) {
2136 global $DB, $USER, $CFG;
2138 // If $this->properties->id is not set then something is wrong
2139 if (empty($this->properties->id)) {
2140 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
2141 return false;
2144 // Delete the event
2145 $DB->delete_records('event', array('id'=>$this->properties->id));
2147 // If the editor context hasn't already been set then set it now
2148 if ($this->editorcontext === null) {
2149 switch ($this->properties->eventtype) {
2150 case 'course':
2151 case 'group':
2152 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
2153 break;
2154 case 'user':
2155 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
2156 break;
2157 case 'site':
2158 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
2159 break;
2160 default:
2161 // There is a chance we can get here as some modules use there own
2162 // eventtype strings. In this case the event has been added by code
2163 // and we don't need to worry about it anyway
2164 break;
2168 // If the context has been set delete all associated files
2169 if ($this->editorcontext !== null) {
2170 $fs = get_file_storage();
2171 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2172 foreach ($files as $file) {
2173 $file->delete();
2177 // Fire the event deleted hook
2178 self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));
2180 // If we need to delete repeated events then we will fetch them all and delete one by one
2181 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2182 // Get all records where the repeatid is the same as the event being removed
2183 $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
2184 // For each of the returned events populate a calendar_event object and call delete
2185 // make sure the arg passed is false as we are already deleting all repeats
2186 foreach ($events as $event) {
2187 $event = new calendar_event($event);
2188 $event->delete(false);
2192 return true;
2196 * Fetch all event properties
2198 * This function returns all of the events properties as an object and optionally
2199 * can prepare an editor for the description field at the same time. This is
2200 * designed to work when the properties are going to be used to set the default
2201 * values of a moodle forms form.
2203 * @param bool $prepareeditor If set to true a editor is prepared for use with
2204 * the mforms editor element. (for description)
2205 * @return stdClass Object containing event properties
2207 public function properties($prepareeditor=false) {
2208 global $USER, $CFG, $DB;
2210 // First take a copy of the properties. We don't want to actually change the
2211 // properties or we'd forever be converting back and forwards between an
2212 // editor formatted description and not
2213 $properties = clone($this->properties);
2214 // Clean the description here
2215 $properties->description = clean_text($properties->description, $properties->format);
2217 // If set to true we need to prepare the properties for use with an editor
2218 // and prepare the file area
2219 if ($prepareeditor) {
2221 // We may or may not have a property id. If we do then we need to work
2222 // out the context so we can copy the existing files to the draft area
2223 if (!empty($properties->id)) {
2225 if ($properties->eventtype === 'site') {
2226 // Site context
2227 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
2228 } else if ($properties->eventtype === 'user') {
2229 // User context
2230 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
2231 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
2232 // First check the course is valid
2233 $course = $DB->get_record('course', array('id'=>$properties->courseid));
2234 if (!$course) {
2235 print_error('invalidcourse');
2237 // Course context
2238 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $course->id);
2239 // We have a course and are within the course context so we had
2240 // better use the courses max bytes value
2241 $this->editoroptions['maxbytes'] = $course->maxbytes;
2242 } else {
2243 // If we get here we have a custom event type as used by some
2244 // modules. In this case the event will have been added by
2245 // code and we won't need the editor
2246 $this->editoroptions['maxbytes'] = 0;
2247 $this->editoroptions['maxfiles'] = 0;
2250 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2251 $contextid = false;
2252 } else {
2253 // Get the context id that is what we really want
2254 $contextid = $this->editorcontext->id;
2256 } else {
2258 // If we get here then this is a new event in which case we don't need a
2259 // context as there is no existing files to copy to the draft area.
2260 $contextid = null;
2263 // If the contextid === false we don't support files so no preparing
2264 // a draft area
2265 if ($contextid !== false) {
2266 // Just encase it has already been submitted
2267 $draftiddescription = file_get_submitted_draft_itemid('description');
2268 // Prepare the draft area, this copies existing files to the draft area as well
2269 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id, $this->editoroptions, $properties->description);
2270 } else {
2271 $draftiddescription = 0;
2274 // Structure the description field as the editor requires
2275 $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2278 // Finally return the properties
2279 return $properties;
2283 * Toggles the visibility of an event
2285 * @param null|bool $force If it is left null the events visibility is flipped,
2286 * If it is false the event is made hidden, if it is true it
2287 * is made visible.
2289 public function toggle_visibility($force=null) {
2290 global $CFG, $DB;
2292 // Set visible to the default if it is not already set
2293 if (empty($this->properties->visible)) {
2294 $this->properties->visible = 1;
2297 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2298 // Make this event visible
2299 $this->properties->visible = 1;
2300 // Fire the hook
2301 self::calendar_event_hook('show_event', array($this->properties));
2302 } else {
2303 // Make this event hidden
2304 $this->properties->visible = 0;
2305 // Fire the hook
2306 self::calendar_event_hook('hide_event', array($this->properties));
2309 // Update the database to reflect this change
2310 return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2314 * Attempts to call the hook for the specified action should a calendar type
2315 * by set $CFG->calendar, and the appopriate function defined
2317 * @static
2318 * @staticvar bool $extcalendarinc Used to track the inclusion of the calendar lib
2319 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2320 * @param array $args The args to pass to the hook, usually the event is the first element
2321 * @return bool
2323 public static function calendar_event_hook($action, array $args) {
2324 global $CFG;
2325 static $extcalendarinc;
2326 if ($extcalendarinc === null) {
2327 if (!empty($CFG->calendar) && file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
2328 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
2329 $extcalendarinc = true;
2330 } else {
2331 $extcalendarinc = false;
2334 if($extcalendarinc === false) {
2335 return false;
2337 $hook = $CFG->calendar .'_'.$action;
2338 if (function_exists($hook)) {
2339 call_user_func_array($hook, $args);
2340 return true;
2342 return false;
2346 * Returns a calendar_event object when provided with an event id
2348 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2349 * it will result in an exception being thrown
2351 * @param int|object $param
2352 * @return calendar_event|false
2354 public static function load($param) {
2355 global $DB;
2356 if (is_object($param)) {
2357 $event = new calendar_event($param);
2358 } else {
2359 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2360 $event = new calendar_event($event);
2362 return $event;
2366 * Creates a new event and returns a calendar_event object
2368 * @param object|array $properties An object containing event properties
2369 * @return calendar_event|false The event object or false if it failed
2371 public static function create($properties) {
2372 if (is_array($properties)) {
2373 $properties = (object)$properties;
2375 if (!is_object($properties)) {
2376 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2378 $event = new calendar_event();
2379 if ($event->update($properties)) {
2380 return $event;
2381 } else {
2382 return false;
2388 * Calendar information class
2390 * This class is used simply to organise the information pertaining to a calendar
2391 * and is used primarily to make information easily available.
2393 class calendar_information {
2395 * The day
2396 * @var int
2398 public $day;
2400 * The month
2401 * @var int
2403 public $month;
2405 * The year
2406 * @var int
2408 public $year;
2411 * A course id
2412 * @var int
2414 public $courseid = null;
2416 * An array of courses
2417 * @var array
2419 public $courses = array();
2421 * An array of groups
2422 * @var array
2424 public $groups = array();
2426 * An array of users
2427 * @var array
2429 public $users = array();
2432 * Creates a new instance
2434 * @param int $day
2435 * @param int $month
2436 * @param int $year
2438 public function __construct($day=0, $month=0, $year=0) {
2440 $date = usergetdate(time());
2442 if (empty($day)) {
2443 $day = $date['mday'];
2446 if (empty($month)) {
2447 $month = $date['mon'];
2450 if (empty($year)) {
2451 $year = $date['year'];
2454 $this->day = $day;
2455 $this->month = $month;
2456 $this->year = $year;
2460 * Ensures the date for the calendar is correct and either sets it to now
2461 * or throws a moodle_exception if not
2463 * @param bool $defaultonow
2464 * @return bool
2466 public function checkdate($defaultonow = true) {
2467 if (!checkdate($this->month, $this->day, $this->year)) {
2468 if ($defaultonow) {
2469 $now = usergetdate(time());
2470 $this->day = intval($now['mday']);
2471 $this->month = intval($now['mon']);
2472 $this->year = intval($now['year']);
2473 return true;
2474 } else {
2475 throw new moodle_exception('invaliddate');
2478 return true;
2481 * Gets todays timestamp for the calendar
2482 * @return int
2484 public function timestamp_today() {
2485 return make_timestamp($this->year, $this->month, $this->day);
2488 * Gets tomorrows timestamp for the calendar
2489 * @return int
2491 public function timestamp_tomorrow() {
2492 return make_timestamp($this->year, $this->month, $this->day+1);
2495 * Adds the pretend blocks for teh calendar
2497 * @param core_calendar_renderer $renderer
2498 * @param bool $showfilters
2499 * @param string|null $view
2501 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
2502 if ($showfilters) {
2503 $filters = new block_contents();
2504 $filters->content = $renderer->fake_block_filters($this->courseid, $this->day, $this->month, $this->year, $view, $this->courses);
2505 $filters->footer = '';
2506 $filters->title = get_string('eventskey', 'calendar');
2507 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
2509 $block = new block_contents;
2510 $block->content = $renderer->fake_block_threemonths($this);
2511 $block->footer = '';
2512 $block->title = get_string('monthlyview', 'calendar');
2513 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);