2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 if (!defined('MOODLE_INTERNAL')) {
27 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
31 * These are read by the administration component to provide default values
35 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
37 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
40 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
42 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
45 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
47 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
49 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
50 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
53 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
55 define('CALENDAR_DEFAULT_WEEKEND', 65);
58 * CALENDAR_URL - path to calendar's folder
60 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
63 * CALENDAR_TF_24 - Calendar time in 24 hours format
65 define('CALENDAR_TF_24', '%H:%M');
68 * CALENDAR_TF_12 - Calendar time in 12 hours format
70 define('CALENDAR_TF_12', '%I:%M %p');
73 * CALENDAR_EVENT_GLOBAL - Global calendar event types
75 define('CALENDAR_EVENT_GLOBAL', 1);
78 * CALENDAR_EVENT_COURSE - Course calendar event types
80 define('CALENDAR_EVENT_COURSE', 2);
83 * CALENDAR_EVENT_GROUP - group calendar event types
85 define('CALENDAR_EVENT_GROUP', 4);
88 * CALENDAR_EVENT_USER - user calendar event types
90 define('CALENDAR_EVENT_USER', 8);
94 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
96 define('CALENDAR_IMPORT_FROM_FILE', 0);
99 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
101 define('CALENDAR_IMPORT_FROM_URL', 1);
104 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
106 define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
109 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
111 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
114 * Return the days of the week
116 * @return array array of days
118 function calendar_get_days() {
119 return array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
123 * Gets the first day of the week
125 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
129 function calendar_get_starting_weekday() {
132 if (isset($CFG->calendar_startwday)) {
133 $firstday = $CFG->calendar_startwday;
135 $firstday = get_string('firstdayofweek', 'langconfig');
138 if(!is_numeric($firstday)) {
139 return CALENDAR_DEFAULT_STARTING_WEEKDAY;
141 return intval($firstday) % 7;
146 * Generates the HTML for a miniature calendar
148 * @param array $courses list of course
149 * @param array $groups list of group
150 * @param array $users user's info
151 * @param int $cal_month calendar month in numeric, default is set to false
152 * @param int $cal_year calendar month in numeric, default is set to false
153 * @return string $content return html table for mini calendar
155 function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
156 global $CFG, $USER, $OUTPUT;
158 $display = new stdClass;
159 $display->minwday = get_user_preferences('calendar_startwday', calendar_get_starting_weekday());
160 $display->maxwday = $display->minwday + 6;
164 if(!empty($cal_month) && !empty($cal_year)) {
165 $thisdate = usergetdate(time()); // Date and time the user sees at his location
166 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
167 // Navigated to this month
169 $display->thismonth = true;
171 // Navigated to other month, let's do a nice trick and save us a lot of work...
172 if(!checkdate($cal_month, 1, $cal_year)) {
173 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
174 $display->thismonth = true;
176 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
177 $display->thismonth = false;
181 $date = usergetdate(time()); // Date and time the user sees at his location
182 $display->thismonth = true;
185 // Fill in the variables we 're going to use, nice and tidy
186 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
187 $display->maxdays = calendar_days_in_month($m, $y);
189 if (get_user_timezone_offset() < 99) {
190 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
191 $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
192 $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
194 // no timezone info specified
195 $display->tstart = mktime(0, 0, 0, $m, 1, $y);
196 $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y);
199 $startwday = dayofweek(1, $m, $y);
201 // Align the starting weekday to fall in our display range
202 // This is simple, not foolproof.
203 if($startwday < $display->minwday) {
207 // TODO: THIS IS TEMPORARY CODE!
208 // [pj] I was just reading through this and realized that I when writing this code I was probably
209 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
210 // make_timestamp would accomplish the same thing. So here goes a test:
211 //$test_start = make_timestamp($y, $m, 1);
212 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
213 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
214 //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);
216 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
217 //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);
221 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
222 $events = calendar_get_events(
223 usertime($display->tstart) - dst_offset_on($display->tstart),
224 usertime($display->tend) - dst_offset_on($display->tend),
225 $users, $groups, $courses);
227 // Set event course class for course events
228 if (!empty($events)) {
229 foreach ($events as $eventid => $event) {
230 if (!empty($event->modulename)) {
231 $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
232 if (!groups_course_module_visible($cm)) {
233 unset($events[$eventid]);
239 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
240 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
241 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
242 // arguments to this function.
244 $hrefparams = array();
245 if(!empty($courses)) {
246 $courses = array_diff($courses, array(SITEID));
247 if(count($courses) == 1) {
248 $hrefparams['course'] = reset($courses);
252 // We want to have easy access by day, since the display is on a per-day basis.
253 // Arguments passed by reference.
254 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
255 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
257 //Accessibility: added summary and <abbr> elements.
258 $days_title = calendar_get_days();
260 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
261 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table
262 $content .= '<tr class="weekdays">'; // Header row: day names
264 // Print out the names of the weekdays
265 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
266 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
267 // This uses the % operator to get the correct weekday no matter what shift we have
268 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
269 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
270 get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
273 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
275 // For the table display. $week is the row; $dayweek is the column.
276 $dayweek = $startwday;
278 // Paddding (the first week may have blank days in the beginning)
279 for($i = $display->minwday; $i < $startwday; ++$i) {
280 $content .= '<td class="dayblank"> </td>'."\n";
283 $weekend = CALENDAR_DEFAULT_WEEKEND;
284 if (isset($CFG->calendar_weekend)) {
285 $weekend = intval($CFG->calendar_weekend);
288 // Now display all the calendar
289 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
290 if($dayweek > $display->maxwday) {
291 // We need to change week (table row)
292 $content .= '</tr><tr>';
293 $dayweek = $display->minwday;
298 if ($weekend & (1 << ($dayweek % 7))) {
299 // Weekend. This is true no matter what the exact range is.
300 $class = 'weekend day';
302 // Normal working day.
306 // Special visual fx if an event is defined
307 if(isset($eventsbyday[$day])) {
308 $class .= ' hasevent';
309 $hrefparams['view'] = 'day';
310 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $hrefparams), $day, $m, $y);
313 foreach($eventsbyday[$day] as $eventid) {
314 if (!isset($events[$eventid])) {
317 $event = $events[$eventid];
319 $component = 'moodle';
320 if(!empty($event->modulename)) {
322 $popupalt = $event->modulename;
323 $component = $event->modulename;
324 } else if ($event->courseid == SITEID) { // Site event
325 $popupicon = 'c/site';
326 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
327 $popupicon = 'c/course';
328 } else if ($event->groupid) { // Group event
329 $popupicon = 'c/group';
330 } else if ($event->userid) { // User event
331 $popupicon = 'c/user';
334 $dayhref->set_anchor('event_'.$event->id);
336 $popupcontent .= html_writer::start_tag('div');
337 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
338 $popupcontent .= html_writer::link($dayhref, format_string($event->name, true));
339 $popupcontent .= html_writer::end_tag('div');
342 //Accessibility: functionality moved to calendar_get_popup.
343 if($display->thismonth && $day == $d) {
344 $popupid = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
346 $popupid = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
349 // Class and cell content
350 if(isset($typesbyday[$day]['startglobal'])) {
351 $class .= ' calendar_event_global';
352 } else if(isset($typesbyday[$day]['startcourse'])) {
353 $class .= ' calendar_event_course';
354 } else if(isset($typesbyday[$day]['startgroup'])) {
355 $class .= ' calendar_event_group';
356 } else if(isset($typesbyday[$day]['startuser'])) {
357 $class .= ' calendar_event_user';
359 $cell = html_writer::link($dayhref, $day, array('aria-controls' => $popupid.'_panel', 'id' => $popupid));
364 $durationclass = false;
365 if (isset($typesbyday[$day]['durationglobal'])) {
366 $durationclass = ' duration_global';
367 } else if(isset($typesbyday[$day]['durationcourse'])) {
368 $durationclass = ' duration_course';
369 } else if(isset($typesbyday[$day]['durationgroup'])) {
370 $durationclass = ' duration_group';
371 } else if(isset($typesbyday[$day]['durationuser'])) {
372 $durationclass = ' duration_user';
374 if ($durationclass) {
375 $class .= ' duration '.$durationclass;
378 // If event has a class set then add it to the table day <td> tag
379 // Note: only one colour for minicalendar
380 if(isset($eventsbyday[$day])) {
381 foreach($eventsbyday[$day] as $eventid) {
382 if (!isset($events[$eventid])) {
385 $event = $events[$eventid];
386 if (!empty($event->class)) {
387 $class .= ' '.$event->class;
393 // Special visual fx for today
394 //Accessibility: hidden text for today, and popup.
395 if($display->thismonth && $day == $d) {
397 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
399 if(! isset($eventsbyday[$day])) {
400 $class .= ' eventnone';
401 $popupid = calendar_get_popup(true, false);
402 $cell = html_writer::link('#', $day, array('aria-controls' => $popupid.'_panel', 'id' => $popupid));
404 $cell = get_accesshide($today.' ').$cell;
409 $class = ' class="'.$class.'"';
411 $content .= '<td'.$class.'>'.$cell."</td>\n";
414 // Paddding (the last week may have blank days at the end)
415 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
416 $content .= '<td class="dayblank"> </td>';
418 $content .= '</tr>'; // Last row ends
420 $content .= '</table>'; // Tabular display of days ends
426 * Gets the calendar popup
428 * It called at multiple points in from calendar_get_mini.
429 * Copied and modified from calendar_get_mini.
431 * @param bool $is_today false except when called on the current day.
432 * @param mixed $event_timestart $events[$eventid]->timestart, OR false if there are no events.
433 * @param string $popupcontent content for the popup window/layout.
434 * @return string eventid for the calendar_tooltip popup window/layout.
436 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
439 if ($popupcount === null) {
444 $popupcaption = get_string('today', 'calendar').' ';
446 if (false === $event_timestart) {
447 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
448 $popupcontent = get_string('eventnone', 'calendar');
451 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
453 $id = 'calendar_tooltip_'.$popupcount;
454 $PAGE->requires->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
461 * Gets the calendar upcoming event
463 * @param array $courses array of courses
464 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
465 * @param array|int|bool $users array of users, user id or boolean for all/no user events
466 * @param int $daysinfuture number of days in the future we 'll look
467 * @param int $maxevents maximum number of events
468 * @param int $fromtime start time
469 * @return array $output array of upcoming events
471 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
472 global $CFG, $COURSE, $DB;
474 $display = new stdClass;
475 $display->range = $daysinfuture; // How many days in the future we 'll look
476 $display->maxevents = $maxevents;
480 // Prepare "course caching", since it may save us a lot of queries
481 $coursecache = array();
484 $now = time(); // We 'll need this later
485 $usermidnighttoday = usergetmidnight($now);
488 $display->tstart = $fromtime;
490 $display->tstart = $usermidnighttoday;
493 // This works correctly with respect to the user's DST, but it is accurate
494 // only because $fromtime is always the exact midnight of some day!
495 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
497 // Get the events matching our criteria
498 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
500 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
501 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
502 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
503 // arguments to this function.
505 $hrefparams = array();
506 if(!empty($courses)) {
507 $courses = array_diff($courses, array(SITEID));
508 if(count($courses) == 1) {
509 $hrefparams['course'] = reset($courses);
513 if ($events !== false) {
515 $modinfo = get_fast_modinfo($COURSE);
517 foreach($events as $event) {
520 if (!empty($event->modulename)) {
521 if ($event->courseid == $COURSE->id) {
522 if (isset($modinfo->instances[$event->modulename][$event->instance])) {
523 $cm = $modinfo->instances[$event->modulename][$event->instance];
524 if (!$cm->uservisible) {
529 if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
532 if (!coursemodule_visible_for_user($cm)) {
536 if ($event->modulename == 'assignment'){
537 // create calendar_event to test edit_event capability
538 // this new event will also prevent double creation of calendar_event object
539 $checkevent = new calendar_event($event);
540 // TODO: rewrite this hack somehow
541 if (!calendar_edit_event_allowed($checkevent)){ // cannot manage entries, eg. student
542 if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance))) {
543 // print_error("invalidid", 'assignment');
546 // assign assignment to assignment object to use hidden_is_hidden method
547 require_once($CFG->dirroot.'/mod/assignment/lib.php');
549 if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php')) {
552 require_once ($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
554 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
555 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm);
557 if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
558 $event->description = get_string('notavailableyet', 'assignment');
564 if ($processed >= $display->maxevents) {
568 $event->time = calendar_format_event_time($event, $now, $hrefparams);
577 * Add calendar event metadata
579 * @param stdClass $event event info
580 * @return stdClass $event metadata
582 function calendar_add_event_metadata($event) {
583 global $CFG, $OUTPUT;
585 //Support multilang in event->name
586 $event->name = format_string($event->name,true);
588 if(!empty($event->modulename)) { // Activity event
589 // The module name is set. I will assume that it has to be displayed, and
590 // also that it is an automatically-generated event. And of course that the
591 // fields for get_coursemodule_from_instance are set correctly.
592 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
594 if ($module === false) {
598 $modulename = get_string('modulename', $event->modulename);
599 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
600 // will be used as alt text if the event icon
601 $eventtype = get_string($event->eventtype, $event->modulename);
605 $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
607 $context = context_course::instance($module->course);
608 $fullname = format_string($coursecache[$module->course]->fullname, true, array('context' => $context));
610 $event->icon = '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
611 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
612 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$fullname.'</a>';
613 $event->cmid = $module->id;
616 } else if($event->courseid == SITEID) { // Site event
617 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/site') . '" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
618 $event->cssclass = 'calendar_event_global';
619 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
620 calendar_get_course_cached($coursecache, $event->courseid);
622 $context = context_course::instance($event->courseid);
623 $fullname = format_string($coursecache[$event->courseid]->fullname, true, array('context' => $context));
625 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/course') . '" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
626 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$fullname.'</a>';
627 $event->cssclass = 'calendar_event_course';
628 } else if ($event->groupid) { // Group event
629 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/group') . '" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
630 $event->cssclass = 'calendar_event_group';
631 } else if($event->userid) { // User event
632 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/user') . '" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
633 $event->cssclass = 'calendar_event_user';
639 * Get calendar events
641 * @param int $tstart Start time of time range for events
642 * @param int $tend End time of time range for events
643 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
644 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
645 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
646 * @param boolean $withduration whether only events starting within time range selected
647 * or events in progress/already started selected as well
648 * @param boolean $ignorehidden whether to select only visible events or all events
649 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
651 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
656 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
660 if(is_array($users) && !empty($users)) {
661 // Events from a number of users
662 if(!empty($whereclause)) $whereclause .= ' OR';
663 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
664 } else if(is_numeric($users)) {
665 // Events from one user
666 if(!empty($whereclause)) $whereclause .= ' OR';
667 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
668 } else if($users === true) {
669 // Events from ALL users
670 if(!empty($whereclause)) $whereclause .= ' OR';
671 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
672 } else if($users === false) {
673 // No user at all, do nothing
676 if(is_array($groups) && !empty($groups)) {
677 // Events from a number of groups
678 if(!empty($whereclause)) $whereclause .= ' OR';
679 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
680 } else if(is_numeric($groups)) {
681 // Events from one group
682 if(!empty($whereclause)) $whereclause .= ' OR ';
683 $whereclause .= ' groupid = '.$groups;
684 } else if($groups === true) {
685 // Events from ALL groups
686 if(!empty($whereclause)) $whereclause .= ' OR ';
687 $whereclause .= ' groupid != 0';
689 // boolean false (no groups at all): we don't need to do anything
691 if(is_array($courses) && !empty($courses)) {
692 if(!empty($whereclause)) {
693 $whereclause .= ' OR';
695 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
696 } else if(is_numeric($courses)) {
698 if(!empty($whereclause)) $whereclause .= ' OR';
699 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
700 } else if ($courses === true) {
701 // Events from ALL courses
702 if(!empty($whereclause)) $whereclause .= ' OR';
703 $whereclause .= ' (groupid = 0 AND courseid != 0)';
706 // Security check: if, by now, we have NOTHING in $whereclause, then it means
707 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
708 // events no matter what. Allowing the code to proceed might return a completely
709 // valid query with only time constraints, thus selecting ALL events in that time frame!
710 if(empty($whereclause)) {
715 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
718 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
720 if(!empty($whereclause)) {
721 // We have additional constraints
722 $whereclause = $timeclause.' AND ('.$whereclause.')';
725 // Just basic time filtering
726 $whereclause = $timeclause;
730 $whereclause .= ' AND visible = 1';
733 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
734 if ($events === false) {
741 * Get control options for Calendar
743 * @param string $type of calendar
744 * @param array $data calendar information
745 * @return string $content return available control for the calender in html
747 function calendar_top_controls($type, $data) {
750 if(!isset($data['d'])) {
754 // Ensure course id passed if relevant
755 // Required due to changes in view/lib.php mainly (calendar_session_vars())
757 if (!empty($data['id'])) {
758 $courseid = '&course='.$data['id'];
761 if(!checkdate($data['m'], $data['d'], $data['y'])) {
765 $time = make_timestamp($data['y'], $data['m'], $data['d']);
767 $date = usergetdate($time);
769 $data['m'] = $date['mon'];
770 $data['y'] = $date['year'];
772 //Accessibility: calendar block controls, replaced <table> with <div>.
773 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
774 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
778 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
779 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
780 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
781 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
783 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
784 if (!empty($data['id'])) {
785 $calendarlink->param('course', $data['id']);
788 if (right_to_left()) {
796 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
797 $content .= $left.'<span class="hide"> | </span>';
798 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
799 $content .= '<span class="hide"> | </span>'. $right;
800 $content .= "<span class=\"clearer\"><!-- --></span>\n";
801 $content .= html_writer::end_tag('div');
805 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
806 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
807 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&', 0, $nextmonth, $nextyear, $accesshide=true);
808 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&', 0, $prevmonth, $prevyear, true);
810 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
811 if (!empty($data['id'])) {
812 $calendarlink->param('course', $data['id']);
815 if (right_to_left()) {
823 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
824 $content .= $left.'<span class="hide"> | </span>';
825 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
826 $content .= '<span class="hide"> | </span>'. $right;
827 $content .= "<span class=\"clearer\"><!-- --></span>";
828 $content .= html_writer::end_tag('div');
831 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'upcoming')), 1, $data['m'], $data['y']);
832 if (!empty($data['id'])) {
833 $calendarlink->param('course', $data['id']);
835 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
836 $content .= html_writer::tag('div', $calendarlink, array('class'=>'centered'));
839 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
840 if (!empty($data['id'])) {
841 $calendarlink->param('course', $data['id']);
843 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
844 $content .= html_writer::tag('h3', $calendarlink);
847 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
848 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
849 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
850 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
851 $prevlink = calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&', 1, $prevmonth, $prevyear);
852 $nextlink = calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&', 1, $nextmonth, $nextyear);
854 if (right_to_left()) {
862 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
863 $content .= $left . '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>";
864 $content .= '<span class="hide"> | </span>' . $right;
865 $content .= '<span class="clearer"><!-- --></span>';
866 $content .= html_writer::end_tag('div')."\n";
869 $days = calendar_get_days();
870 $data['d'] = $date['mday']; // Just for convenience
871 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
872 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
873 $prevname = calendar_wday_name($days[$prevdate['wday']]);
874 $nextname = calendar_wday_name($days[$nextdate['wday']]);
875 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
876 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
878 if (right_to_left()) {
886 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
888 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
889 $content .= '<span class="hide"> | </span>'. $right;
890 $content .= "<span class=\"clearer\"><!-- --></span>";
891 $content .= html_writer::end_tag('div')."\n";
899 * Formats a filter control element.
901 * @param moodle_url $url of the filter
902 * @param int $type constant defining the type filter
903 * @return string html content of the element
905 function calendar_filter_controls_element(moodle_url $url, $type) {
908 case CALENDAR_EVENT_GLOBAL:
909 $typeforhumans = 'global';
910 $class = 'calendar_event_global';
912 case CALENDAR_EVENT_COURSE:
913 $typeforhumans = 'course';
914 $class = 'calendar_event_course';
916 case CALENDAR_EVENT_GROUP:
917 $typeforhumans = 'groups';
918 $class = 'calendar_event_group';
920 case CALENDAR_EVENT_USER:
921 $typeforhumans = 'user';
922 $class = 'calendar_event_user';
925 if (calendar_show_event_type($type)) {
926 $icon = $OUTPUT->pix_icon('t/hide', get_string('hide'));
927 $str = get_string('hide'.$typeforhumans.'events', 'calendar');
929 $icon = $OUTPUT->pix_icon('t/show', get_string('show'));
930 $str = get_string('show'.$typeforhumans.'events', 'calendar');
932 $content = html_writer::start_tag('li', array('class' => 'calendar_event'));
933 $content .= html_writer::start_tag('a', array('href' => $url));
934 $content .= html_writer::tag('span', $icon, array('class' => $class));
935 $content .= html_writer::tag('span', $str, array('class' => 'eventname'));
936 $content .= html_writer::end_tag('a');
937 $content .= html_writer::end_tag('li');
942 * Get the controls filter for calendar.
944 * Filter is used to hide calendar info from the display page
946 * @param moodle_url $returnurl return-url for filter controls
947 * @return string $content return filter controls in html
949 function calendar_filter_controls(moodle_url $returnurl) {
950 global $CFG, $USER, $OUTPUT;
953 $id = optional_param( 'id',0,PARAM_INT );
954 $seturl = new moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out(false)), 'sesskey'=>sesskey()));
955 $content = html_writer::start_tag('ul');
957 $seturl->param('var', 'showglobal');
958 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GLOBAL);
960 $seturl->param('var', 'showcourses');
961 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_COURSE);
963 if (isloggedin() && !isguestuser()) {
965 // This course MIGHT have group events defined, so show the filter
966 $seturl->param('var', 'showgroups');
967 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GROUP);
969 // This course CANNOT have group events, so lose the filter
971 $seturl->param('var', 'showuser');
972 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_USER);
974 $content .= html_writer::end_tag('ul');
980 * Return the representation day
982 * @param int $tstamp Timestamp in GMT
983 * @param int $now current Unix timestamp
984 * @param bool $usecommonwords
985 * @return string the formatted date/time
987 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
990 if(empty($shortformat)) {
991 $shortformat = get_string('strftimedayshort');
998 // To have it in one place, if a change is needed
999 $formal = userdate($tstamp, $shortformat);
1001 $datestamp = usergetdate($tstamp);
1002 $datenow = usergetdate($now);
1004 if($usecommonwords == false) {
1005 // We don't want words, just a date
1008 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1010 return get_string('today', 'calendar');
1013 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1014 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
1017 return get_string('yesterday', 'calendar');
1020 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1021 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
1024 return get_string('tomorrow', 'calendar');
1032 * return the formatted representation time
1034 * @param int $time the timestamp in UTC, as obtained from the database
1035 * @return string the formatted date/time
1037 function calendar_time_representation($time) {
1038 static $langtimeformat = NULL;
1039 if($langtimeformat === NULL) {
1040 $langtimeformat = get_string('strftimetime');
1042 $timeformat = get_user_preferences('calendar_timeformat');
1043 if(empty($timeformat)){
1044 $timeformat = get_config(NULL,'calendar_site_timeformat');
1046 // The ? is needed because the preference might be present, but empty
1047 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1051 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1053 * @param string|moodle_url $linkbase
1054 * @param int $d The number of the day.
1055 * @param int $m The number of the month.
1056 * @param int $y The number of the year.
1057 * @return moodle_url|null $linkbase
1059 function calendar_get_link_href($linkbase, $d, $m, $y) {
1060 if (empty($linkbase)) {
1063 if (!($linkbase instanceof moodle_url)) {
1064 $linkbase = new moodle_url($linkbase);
1067 $linkbase->param('cal_d', $d);
1070 $linkbase->param('cal_m', $m);
1073 $linkbase->param('cal_y', $y);
1079 * Build and return a previous month HTML link, with an arrow.
1081 * @param string $text The text label.
1082 * @param string|moodle_url $linkbase The URL stub.
1083 * @param int $d The number of the date.
1084 * @param int $m The number of the month.
1085 * @param int $y year The number of the year.
1086 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1087 * @return string HTML string.
1089 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
1090 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1094 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
1098 * Build and return a next month HTML link, with an arrow.
1100 * @param string $text The text label.
1101 * @param string|moodle_url $linkbase The URL stub.
1102 * @param int $d the number of the Day
1103 * @param int $m The number of the month.
1104 * @param int $y The number of the year.
1105 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1106 * @return string HTML string.
1108 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
1109 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1113 return link_arrow_right($text, (string)$href, $accesshide, 'next');
1117 * Return the name of the weekday
1119 * @param string $englishname
1120 * @return string of the weekeday
1122 function calendar_wday_name($englishname) {
1123 return get_string(strtolower($englishname), 'calendar');
1127 * Return the number of days in month
1129 * @param int $month the number of the month.
1130 * @param int $year the number of the year
1133 function calendar_days_in_month($month, $year) {
1134 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
1138 * Get the upcoming event block
1140 * @param array $events list of events
1141 * @param moodle_url|string $linkhref link to event referer
1142 * @return string|null $content html block content
1144 function calendar_get_block_upcoming($events, $linkhref = NULL) {
1146 $lines = count($events);
1151 for ($i = 0; $i < $lines; ++$i) {
1152 if (!isset($events[$i]->time)) { // Just for robustness
1155 $events[$i] = calendar_add_event_metadata($events[$i]);
1156 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
1157 if (!empty($events[$i]->referer)) {
1158 // That's an activity event, so let's provide the hyperlink
1159 $content .= $events[$i]->referer;
1161 if(!empty($linkhref)) {
1162 $ed = usergetdate($events[$i]->timestart);
1163 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL.$linkhref), $ed['mday'], $ed['mon'], $ed['year']);
1164 $href->set_anchor('event_'.$events[$i]->id);
1165 $content .= html_writer::link($href, $events[$i]->name);
1168 $content .= $events[$i]->name;
1171 $events[$i]->time = str_replace('»', '<br />»', $events[$i]->time);
1172 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
1173 if ($i < $lines - 1) $content .= '<hr />';
1180 * Get the next following month
1182 * If the current month is December, it will get the first month of the following year.
1185 * @param int $month the number of the month.
1186 * @param int $year the number of the year.
1187 * @return array the following month
1189 function calendar_add_month($month, $year) {
1191 return array(1, $year + 1);
1194 return array($month + 1, $year);
1199 * Get the previous month
1201 * If the current month is January, it will get the last month of the previous year.
1203 * @param int $month the number of the month.
1204 * @param int $year the number of the year.
1205 * @return array previous month
1207 function calendar_sub_month($month, $year) {
1209 return array(12, $year - 1);
1212 return array($month - 1, $year);
1217 * Get per-day basis events
1219 * @param array $events list of events
1220 * @param int $month the number of the month
1221 * @param int $year the number of the year
1222 * @param array $eventsbyday event on specific day
1223 * @param array $durationbyday duration of the event in days
1224 * @param array $typesbyday event type (eg: global, course, user, or group)
1225 * @param array $courses list of courses
1228 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1229 $eventsbyday = array();
1230 $typesbyday = array();
1231 $durationbyday = array();
1233 if($events === false) {
1237 foreach($events as $event) {
1239 $startdate = usergetdate($event->timestart);
1240 // Set end date = start date if no duration
1241 if ($event->timeduration) {
1242 $enddate = usergetdate($event->timestart + $event->timeduration - 1);
1244 $enddate = $startdate;
1247 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1248 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1253 $eventdaystart = intval($startdate['mday']);
1255 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1256 // Give the event to its day
1257 $eventsbyday[$eventdaystart][] = $event->id;
1259 // Mark the day as having such an event
1260 if($event->courseid == SITEID && $event->groupid == 0) {
1261 $typesbyday[$eventdaystart]['startglobal'] = true;
1262 // Set event class for global event
1263 $events[$event->id]->class = 'calendar_event_global';
1265 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1266 $typesbyday[$eventdaystart]['startcourse'] = true;
1267 // Set event class for course event
1268 $events[$event->id]->class = 'calendar_event_course';
1270 else if($event->groupid) {
1271 $typesbyday[$eventdaystart]['startgroup'] = true;
1272 // Set event class for group event
1273 $events[$event->id]->class = 'calendar_event_group';
1275 else if($event->userid) {
1276 $typesbyday[$eventdaystart]['startuser'] = true;
1277 // Set event class for user event
1278 $events[$event->id]->class = 'calendar_event_user';
1282 if($event->timeduration == 0) {
1283 // Proceed with the next
1287 // The event starts on $month $year or before. So...
1288 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
1290 // Also, it ends on $month $year or later...
1291 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1293 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1294 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1295 $durationbyday[$i][] = $event->id;
1296 if($event->courseid == SITEID && $event->groupid == 0) {
1297 $typesbyday[$i]['durationglobal'] = true;
1299 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1300 $typesbyday[$i]['durationcourse'] = true;
1302 else if($event->groupid) {
1303 $typesbyday[$i]['durationgroup'] = true;
1305 else if($event->userid) {
1306 $typesbyday[$i]['durationuser'] = true;
1315 * Get current module cache
1317 * @param array $coursecache list of course cache
1318 * @param string $modulename name of the module
1319 * @param int $instance module instance number
1320 * @return stdClass|bool $module information
1322 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1323 $module = get_coursemodule_from_instance($modulename, $instance);
1325 if($module === false) return false;
1326 if(!calendar_get_course_cached($coursecache, $module->course)) {
1333 * Get current course cache
1335 * @param array $coursecache list of course cache
1336 * @param int $courseid id of the course
1337 * @return stdClass $coursecache[$courseid] return the specific course cache
1339 function calendar_get_course_cached(&$coursecache, $courseid) {
1340 global $COURSE, $DB;
1342 if (!isset($coursecache[$courseid])) {
1343 if ($courseid == $COURSE->id) {
1344 $coursecache[$courseid] = $COURSE;
1346 $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
1349 return $coursecache[$courseid];
1353 * Returns the courses to load events for, the
1355 * @param array $courseeventsfrom An array of courses to load calendar events for
1356 * @param bool $ignorefilters specify the use of filters, false is set as default
1357 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1359 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1360 global $USER, $CFG, $DB;
1362 // For backwards compatability we have to check whether the courses array contains
1363 // just id's in which case we need to load course objects.
1364 $coursestoload = array();
1365 foreach ($courseeventsfrom as $id => $something) {
1366 if (!is_object($something)) {
1367 $coursestoload[] = $id;
1368 unset($courseeventsfrom[$id]);
1371 if (!empty($coursestoload)) {
1372 // TODO remove this in 2.2
1373 debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER);
1374 $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
1381 // capabilities that allow seeing group events from all groups
1382 // TODO: rewrite so that moodle/calendar:manageentries is not necessary here
1383 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
1385 $isloggedin = isloggedin();
1387 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
1388 $courses = array_keys($courseeventsfrom);
1390 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
1391 $courses[] = SITEID;
1393 $courses = array_unique($courses);
1396 if (!empty($courses) && in_array(SITEID, $courses)) {
1397 // Sort courses for consistent colour highlighting
1398 // Effectively ignoring SITEID as setting as last course id
1399 $key = array_search(SITEID, $courses);
1400 unset($courses[$key]);
1401 $courses[] = SITEID;
1404 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
1408 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
1410 if (count($courseeventsfrom)==1) {
1411 $course = reset($courseeventsfrom);
1412 if (has_any_capability($allgroupscaps, context_course::instance($course->id))) {
1413 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
1414 $group = array_keys($coursegroups);
1417 if ($group === false) {
1418 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, get_system_context())) {
1420 } else if ($isloggedin) {
1421 $groupids = array();
1423 // We already have the courses to examine in $courses
1424 // For each course...
1425 foreach ($courseeventsfrom as $courseid => $course) {
1426 // If the user is an editing teacher in there,
1427 if (!empty($USER->groupmember[$course->id])) {
1428 // We've already cached the users groups for this course so we can just use that
1429 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
1430 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1431 // If this course has groups, show events from all of those related to the current user
1432 $coursegroups = groups_get_user_groups($course->id, $USER->id);
1433 $groupids = array_merge($groupids, $coursegroups['0']);
1436 if (!empty($groupids)) {
1442 if (empty($courses)) {
1446 return array($courses, $group, $user);
1450 * Return the capability for editing calendar event
1452 * @param calendar_event $event event object
1453 * @return bool capability to edit event
1455 function calendar_edit_event_allowed($event) {
1458 // Must be logged in
1459 if (!isloggedin()) {
1463 // can not be using guest account
1464 if (isguestuser()) {
1468 // You cannot edit calendar subscription events presently.
1469 if (!empty($event->subscriptionid)) {
1473 $sitecontext = context_system::instance();
1474 // if user has manageentries at site level, return true
1475 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1479 // if groupid is set, it's definitely a group event
1480 if (!empty($event->groupid)) {
1481 // Allow users to add/edit group events if:
1482 // 1) They have manageentries (= entries for whole course)
1483 // 2) They have managegroupentries AND are in the group
1484 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1486 has_capability('moodle/calendar:manageentries', $event->context) ||
1487 (has_capability('moodle/calendar:managegroupentries', $event->context)
1488 && groups_is_member($event->groupid)));
1489 } else if (!empty($event->courseid)) {
1490 // if groupid is not set, but course is set,
1491 // it's definiely a course event
1492 return has_capability('moodle/calendar:manageentries', $event->context);
1493 } else if (!empty($event->userid) && $event->userid == $USER->id) {
1494 // if course is not set, but userid id set, it's a user event
1495 return (has_capability('moodle/calendar:manageownentries', $event->context));
1496 } else if (!empty($event->userid)) {
1497 return (has_capability('moodle/calendar:manageentries', $event->context));
1503 * Returns the default courses to display on the calendar when there isn't a specific
1504 * course to display.
1506 * @return array $courses Array of courses to display
1508 function calendar_get_default_courses() {
1511 if (!isloggedin()) {
1516 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', context_system::instance())) {
1517 list ($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
1518 $sql = "SELECT c.* $select
1521 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
1523 $courses = $DB->get_records_sql($sql, null, 0, 20);
1524 foreach ($courses as $course) {
1525 context_helper::preload_from_record($course);
1530 $courses = enrol_get_my_courses();
1536 * Display calendar preference button
1538 * @param stdClass $course course object
1539 * @return string return preference button in html
1541 function calendar_preferences_button(stdClass $course) {
1544 // Guests have no preferences
1545 if (!isloggedin() || isguestuser()) {
1549 return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id)), get_string("preferences", "calendar"));
1553 * Get event format time
1555 * @param calendar_event $event event object
1556 * @param int $now current time in gmt
1557 * @param array $linkparams list of params for event link
1558 * @param bool $usecommonwords the words as formatted date/time.
1559 * @param int $showtime determine the show time GMT timestamp
1560 * @return string $eventtime link/string for event time
1562 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime=0) {
1563 $startdate = usergetdate($event->timestart);
1564 $enddate = usergetdate($event->timestart + $event->timeduration);
1565 $usermidnightstart = usergetmidnight($event->timestart);
1567 if($event->timeduration) {
1568 // To avoid doing the math if one IF is enough :)
1569 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1572 $usermidnightend = $usermidnightstart;
1575 if (empty($linkparams) || !is_array($linkparams)) {
1576 $linkparams = array();
1578 $linkparams['view'] = 'day';
1580 // OK, now to get a meaningful display...
1581 // First of all we have to construct a human-readable date/time representation
1583 if($event->timeduration) {
1584 // It has a duration
1585 if($usermidnightstart == $usermidnightend ||
1586 ($event->timestart == $usermidnightstart) && ($event->timeduration == 86400 || $event->timeduration == 86399) ||
1587 ($event->timestart + $event->timeduration <= $usermidnightstart + 86400)) {
1588 // But it's all on the same day
1589 $timestart = calendar_time_representation($event->timestart);
1590 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1591 $time = $timestart.' <strong>»</strong> '.$timeend;
1593 if ($event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399)) {
1594 $time = get_string('allday', 'calendar');
1597 // Set printable representation
1599 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1600 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1601 $eventtime = html_writer::link($url, $day).', '.$time;
1606 // It spans two or more days
1607 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords).', ';
1608 if ($showtime == $usermidnightstart) {
1611 $timestart = calendar_time_representation($event->timestart);
1612 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords).', ';
1613 if ($showtime == $usermidnightend) {
1616 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1618 // Set printable representation
1619 if ($now >= $usermidnightstart && $now < ($usermidnightstart + 86400)) {
1620 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1621 $eventtime = $timestart.' <strong>»</strong> '.html_writer::link($url, $dayend).$timeend;
1623 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1624 $eventtime = html_writer::link($url, $daystart).$timestart.' <strong>»</strong> ';
1626 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1627 $eventtime .= html_writer::link($url, $dayend).$timeend;
1631 $time = calendar_time_representation($event->timestart);
1633 // Set printable representation
1635 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1636 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1637 $eventtime = html_writer::link($url, $day).', '.trim($time);
1643 if($event->timestart + $event->timeduration < $now) {
1645 $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
1652 * Display month selector options
1654 * @param string $name for the select element
1655 * @param string|array $selected options for select elements
1657 function calendar_print_month_selector($name, $selected) {
1659 for ($i=1; $i<=12; $i++) {
1660 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1662 echo html_writer::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
1663 echo html_writer::select($months, $name, $selected, false);
1667 * Checks to see if the requested type of event should be shown for the given user.
1669 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1670 * The type to check the display for (default is to display all)
1671 * @param stdClass|int|null $user The user to check for - by default the current user
1672 * @return bool True if the tyep should be displayed false otherwise
1674 function calendar_show_event_type($type, $user = null) {
1675 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1676 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
1678 if (!isset($SESSION->calendarshoweventtype)) {
1679 $SESSION->calendarshoweventtype = $default;
1681 return $SESSION->calendarshoweventtype & $type;
1683 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
1688 * Sets the display of the event type given $display.
1690 * If $display = true the event type will be shown.
1691 * If $display = false the event type will NOT be shown.
1692 * If $display = null the current value will be toggled and saved.
1694 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type object of CALENDAR_EVENT_XXX
1695 * @param bool $display option to display event type
1696 * @param stdClass|int $user moodle user object or id, null means current user
1698 function calendar_set_event_type_display($type, $display = null, $user = null) {
1699 $persist = get_user_preferences('calendar_persistflt', 0, $user);
1700 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1701 if ($persist === 0) {
1703 if (!isset($SESSION->calendarshoweventtype)) {
1704 $SESSION->calendarshoweventtype = $default;
1706 $preference = $SESSION->calendarshoweventtype;
1708 $preference = get_user_preferences('calendar_savedflt', $default, $user);
1710 $current = $preference & $type;
1711 if ($display === null) {
1712 $display = !$current;
1714 if ($display && !$current) {
1715 $preference += $type;
1716 } else if (!$display && $current) {
1717 $preference -= $type;
1719 if ($persist === 0) {
1720 $SESSION->calendarshoweventtype = $preference;
1722 if ($preference == $default) {
1723 unset_user_preference('calendar_savedflt', $user);
1725 set_user_preference('calendar_savedflt', $preference, $user);
1731 * Get calendar's allowed types
1733 * @param stdClass $allowed list of allowed edit for event type
1734 * @param stdClass|int $course object of a course or course id
1736 function calendar_get_allowed_types(&$allowed, $course = null) {
1737 global $USER, $CFG, $DB;
1738 $allowed = new stdClass();
1739 $allowed->user = has_capability('moodle/calendar:manageownentries', get_system_context());
1740 $allowed->groups = false; // This may change just below
1741 $allowed->courses = false; // This may change just below
1742 $allowed->site = has_capability('moodle/calendar:manageentries', context_course::instance(SITEID));
1744 if (!empty($course)) {
1745 if (!is_object($course)) {
1746 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
1748 if ($course->id != SITEID) {
1749 $coursecontext = context_course::instance($course->id);
1750 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
1752 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1753 $allowed->courses = array($course->id => 1);
1755 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1756 $allowed->groups = groups_get_all_groups($course->id);
1758 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1759 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1760 $allowed->groups = groups_get_all_groups($course->id);
1768 * See if user can add calendar entries at all
1769 * used to print the "New Event" button
1771 * @param stdClass $course object of a course or course id
1772 * @return bool has the capability to add at least one event type
1774 function calendar_user_can_add_event($course) {
1775 if (!isloggedin() || isguestuser()) {
1778 calendar_get_allowed_types($allowed, $course);
1779 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
1783 * Check wether the current user is permitted to add events
1785 * @param stdClass $event object of event
1786 * @return bool has the capability to add event
1788 function calendar_add_event_allowed($event) {
1791 // can not be using guest account
1792 if (!isloggedin() or isguestuser()) {
1796 $sitecontext = context_system::instance();
1797 // if user has manageentries at site level, always return true
1798 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1802 switch ($event->eventtype) {
1804 return has_capability('moodle/calendar:manageentries', $event->context);
1807 // Allow users to add/edit group events if:
1808 // 1) They have manageentries (= entries for whole course)
1809 // 2) They have managegroupentries AND are in the group
1810 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1812 has_capability('moodle/calendar:manageentries', $event->context) ||
1813 (has_capability('moodle/calendar:managegroupentries', $event->context)
1814 && groups_is_member($event->groupid)));
1817 if ($event->userid == $USER->id) {
1818 return (has_capability('moodle/calendar:manageownentries', $event->context));
1820 //there is no 'break;' intentionally
1823 return has_capability('moodle/calendar:manageentries', $event->context);
1826 return has_capability('moodle/calendar:manageentries', $event->context);
1831 * Manage calendar events
1833 * This class provides the required functionality in order to manage calendar events.
1834 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1835 * better framework for dealing with calendar events in particular regard to file
1836 * handling through the new file API
1838 * @package core_calendar
1839 * @category calendar
1840 * @copyright 2009 Sam Hemelryk
1841 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1843 * @property int $id The id within the event table
1844 * @property string $name The name of the event
1845 * @property string $description The description of the event
1846 * @property int $format The format of the description FORMAT_?
1847 * @property int $courseid The course the event is associated with (0 if none)
1848 * @property int $groupid The group the event is associated with (0 if none)
1849 * @property int $userid The user the event is associated with (0 if none)
1850 * @property int $repeatid If this is a repeated event this will be set to the
1851 * id of the original
1852 * @property string $modulename If added by a module this will be the module name
1853 * @property int $instance If added by a module this will be the module instance
1854 * @property string $eventtype The event type
1855 * @property int $timestart The start time as a timestamp
1856 * @property int $timeduration The duration of the event in seconds
1857 * @property int $visible 1 if the event is visible
1858 * @property int $uuid ?
1859 * @property int $sequence ?
1860 * @property int $timemodified The time last modified as a timestamp
1862 class calendar_event {
1864 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
1865 protected $properties = null;
1868 * @var string The converted event discription with file paths resolved. This gets populated when someone requests description for the first time */
1869 protected $_description = null;
1871 /** @var array The options to use with this description editor */
1872 protected $editoroptions = array(
1874 'forcehttps'=>false,
1877 'trusttext'=>false);
1879 /** @var object The context to use with the description editor */
1880 protected $editorcontext = null;
1883 * Instantiates a new event and optionally populates its properties with the
1886 * @param stdClass $data Optional. An object containing the properties to for
1889 public function __construct($data=null) {
1892 // First convert to object if it is not already (should either be object or assoc array)
1893 if (!is_object($data)) {
1894 $data = (object)$data;
1897 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
1899 $data->eventrepeats = 0;
1901 if (empty($data->id)) {
1905 // Default to a user event
1906 if (empty($data->eventtype)) {
1907 $data->eventtype = 'user';
1910 // Default to the current user
1911 if (empty($data->userid)) {
1912 $data->userid = $USER->id;
1915 if (!empty($data->timeduration) && is_array($data->timeduration)) {
1916 $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
1918 if (!empty($data->description) && is_array($data->description)) {
1919 $data->format = $data->description['format'];
1920 $data->description = $data->description['text'];
1921 } else if (empty($data->description)) {
1922 $data->description = '';
1923 $data->format = editors_get_preferred_format();
1925 // Ensure form is defaulted correctly
1926 if (empty($data->format)) {
1927 $data->format = editors_get_preferred_format();
1930 if (empty($data->context)) {
1931 $data->context = $this->calculate_context($data);
1933 $this->properties = $data;
1937 * Magic property method
1939 * Attempts to call a set_$key method if one exists otherwise falls back
1940 * to simply set the property
1942 * @param string $key property name
1943 * @param mixed $value value of the property
1945 public function __set($key, $value) {
1946 if (method_exists($this, 'set_'.$key)) {
1947 $this->{'set_'.$key}($value);
1949 $this->properties->{$key} = $value;
1955 * Attempts to call a get_$key method to return the property and ralls over
1956 * to return the raw property
1958 * @param string $key property name
1959 * @return mixed property value
1961 public function __get($key) {
1962 if (method_exists($this, 'get_'.$key)) {
1963 return $this->{'get_'.$key}();
1965 if (!isset($this->properties->{$key})) {
1966 throw new coding_exception('Undefined property requested');
1968 return $this->properties->{$key};
1972 * Stupid PHP needs an isset magic method if you use the get magic method and
1973 * still want empty calls to work.... blah ~!
1975 * @param string $key $key property name
1976 * @return bool|mixed property value, false if property is not exist
1978 public function __isset($key) {
1979 return !empty($this->properties->{$key});
1983 * Calculate the context value needed for calendar_event.
1984 * Event's type can be determine by the available value store in $data
1985 * It is important to check for the existence of course/courseid to determine
1987 * Default value is set to CONTEXT_USER
1989 * @param stdClass $data information about event
1990 * @return stdClass The context object.
1992 protected function calculate_context(stdClass $data) {
1996 if (isset($data->courseid) && $data->courseid > 0) {
1997 $context = context_course::instance($data->courseid);
1998 } else if (isset($data->course) && $data->course > 0) {
1999 $context = context_course::instance($data->course);
2000 } else if (isset($data->groupid) && $data->groupid > 0) {
2001 $group = $DB->get_record('groups', array('id'=>$data->groupid));
2002 $context = context_course::instance($group->courseid);
2003 } else if (isset($data->userid) && $data->userid > 0 && $data->userid == $USER->id) {
2004 $context = context_user::instance($data->userid);
2005 } else if (isset($data->userid) && $data->userid > 0 && $data->userid != $USER->id &&
2006 isset($data->instance) && $data->instance > 0) {
2007 $cm = get_coursemodule_from_instance($data->modulename, $data->instance, 0, false, MUST_EXIST);
2008 $context = context_course::instance($cm->course);
2010 $context = context_user::instance($data->userid);
2017 * Returns an array of editoroptions for this event: Called by __get
2018 * Please use $blah = $event->editoroptions;
2020 * @return array event editor options
2022 protected function get_editoroptions() {
2023 return $this->editoroptions;
2027 * Returns an event description: Called by __get
2028 * Please use $blah = $event->description;
2030 * @return string event description
2032 protected function get_description() {
2035 require_once($CFG->libdir . '/filelib.php');
2037 if ($this->_description === null) {
2038 // Check if we have already resolved the context for this event
2039 if ($this->editorcontext === null) {
2040 // Switch on the event type to decide upon the appropriate context
2041 // to use for this event
2042 $this->editorcontext = $this->properties->context;
2043 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
2044 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
2045 return clean_text($this->properties->description, $this->properties->format);
2049 // Work out the item id for the editor, if this is a repeated event then the files will
2050 // be associated with the original
2051 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2052 $itemid = $this->properties->repeatid;
2054 $itemid = $this->properties->id;
2057 // Convert file paths in the description so that things display correctly
2058 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, 'calendar', 'event_description', $itemid);
2059 // Clean the text so no nasties get through
2060 $this->_description = clean_text($this->_description, $this->properties->format);
2062 // Finally return the description
2063 return $this->_description;
2067 * Return the number of repeat events there are in this events series
2069 * @return int number of event repeated
2071 public function count_repeats() {
2073 if (!empty($this->properties->repeatid)) {
2074 $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
2075 // We don't want to count ourselves
2076 $this->properties->eventrepeats--;
2078 return $this->properties->eventrepeats;
2082 * Update or create an event within the database
2084 * Pass in a object containing the event properties and this function will
2085 * insert it into the database and deal with any associated files
2088 * @see update_event()
2090 * @param stdClass $data object of event
2091 * @param bool $checkcapability if moodle should check calendar managing capability or not
2092 * @return bool event updated
2094 public function update($data, $checkcapability=true) {
2095 global $CFG, $DB, $USER;
2097 foreach ($data as $key=>$value) {
2098 $this->properties->$key = $value;
2101 $this->properties->timemodified = time();
2102 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
2104 if (empty($this->properties->id) || $this->properties->id < 1) {
2106 if ($checkcapability) {
2107 if (!calendar_add_event_allowed($this->properties)) {
2108 print_error('nopermissiontoupdatecalendar');
2113 switch ($this->properties->eventtype) {
2115 $this->editorcontext = $this->properties->context;
2116 $this->properties->courseid = 0;
2117 $this->properties->groupid = 0;
2118 $this->properties->userid = $USER->id;
2121 $this->editorcontext = $this->properties->context;
2122 $this->properties->courseid = SITEID;
2123 $this->properties->groupid = 0;
2124 $this->properties->userid = $USER->id;
2127 $this->editorcontext = $this->properties->context;
2128 $this->properties->groupid = 0;
2129 $this->properties->userid = $USER->id;
2132 $this->editorcontext = $this->properties->context;
2133 $this->properties->userid = $USER->id;
2136 // Ewww we should NEVER get here, but just incase we do lets
2138 $usingeditor = false;
2142 $editor = $this->properties->description;
2143 $this->properties->format = $this->properties->description['format'];
2144 $this->properties->description = $this->properties->description['text'];
2147 // Insert the event into the database
2148 $this->properties->id = $DB->insert_record('event', $this->properties);
2151 $this->properties->description = file_save_draft_area_files(
2153 $this->editorcontext->id,
2155 'event_description',
2156 $this->properties->id,
2157 $this->editoroptions,
2159 $this->editoroptions['forcehttps']);
2161 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
2164 // Log the event entry.
2165 add_to_log($this->properties->courseid, 'calendar', 'add', 'event.php?action=edit&id='.$this->properties->id, $this->properties->name);
2167 $repeatedids = array();
2169 if (!empty($this->properties->repeat)) {
2170 $this->properties->repeatid = $this->properties->id;
2171 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));
2173 $eventcopy = clone($this->properties);
2174 unset($eventcopy->id);
2176 for($i = 1; $i < $eventcopy->repeats; $i++) {
2178 $eventcopy->timestart = ($eventcopy->timestart+WEEKSECS) + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart+WEEKSECS);
2180 // Get the event id for the log record.
2181 $eventcopyid = $DB->insert_record('event', $eventcopy);
2183 // If the context has been set delete all associated files
2185 $fs = get_file_storage();
2186 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2187 foreach ($files as $file) {
2188 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
2192 $repeatedids[] = $eventcopyid;
2193 // Log the event entry.
2194 add_to_log($eventcopy->courseid, 'calendar', 'add', 'event.php?action=edit&id='.$eventcopyid, $eventcopy->name);
2198 // Hook for tracking added events
2199 self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
2203 if ($checkcapability) {
2204 if(!calendar_edit_event_allowed($this->properties)) {
2205 print_error('nopermissiontoupdatecalendar');
2210 if ($this->editorcontext !== null) {
2211 $this->properties->description = file_save_draft_area_files(
2212 $this->properties->description['itemid'],
2213 $this->editorcontext->id,
2215 'event_description',
2216 $this->properties->id,
2217 $this->editoroptions,
2218 $this->properties->description['text'],
2219 $this->editoroptions['forcehttps']);
2221 $this->properties->format = $this->properties->description['format'];
2222 $this->properties->description = $this->properties->description['text'];
2226 $event = $DB->get_record('event', array('id'=>$this->properties->id));
2228 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
2230 if ($updaterepeated) {
2232 if ($this->properties->timestart != $event->timestart) {
2233 $timestartoffset = $this->properties->timestart - $event->timestart;
2234 $sql = "UPDATE {event}
2237 timestart = timestart + ?,
2240 WHERE repeatid = ?";
2241 $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
2243 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2244 $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
2246 $DB->execute($sql, $params);
2248 // Log the event update.
2249 add_to_log($this->properties->courseid, 'calendar', 'edit all', 'event.php?action=edit&id='.$this->properties->id, $this->properties->name);
2251 $DB->update_record('event', $this->properties);
2252 $event = calendar_event::load($this->properties->id);
2253 $this->properties = $event->properties();
2254 add_to_log($this->properties->courseid, 'calendar', 'edit', 'event.php?action=edit&id='.$this->properties->id, $this->properties->name);
2257 // Hook for tracking event updates
2258 self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
2264 * Deletes an event and if selected an repeated events in the same series
2266 * This function deletes an event, any associated events if $deleterepeated=true,
2267 * and cleans up any files associated with the events.
2269 * @see delete_event()
2271 * @param bool $deleterepeated delete event repeatedly
2272 * @return bool succession of deleting event
2274 public function delete($deleterepeated=false) {
2277 // If $this->properties->id is not set then something is wrong
2278 if (empty($this->properties->id)) {
2279 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
2284 $DB->delete_records('event', array('id'=>$this->properties->id));
2286 // If we are deleting parent of a repeated event series, promote the next event in the series as parent
2287 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
2288 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC", array($this->properties->id), IGNORE_MULTIPLE);
2289 if (!empty($newparent)) {
2290 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?", array($newparent, $this->properties->id));
2291 // Get all records where the repeatid is the same as the event being removed
2292 $events = $DB->get_records('event', array('repeatid' => $newparent));
2293 // For each of the returned events trigger the event_update hook.
2294 foreach ($events as $event) {
2295 self::calendar_event_hook('update_event', array($event, false));
2300 // If the editor context hasn't already been set then set it now
2301 if ($this->editorcontext === null) {
2302 $this->editorcontext = $this->properties->context;
2305 // If the context has been set delete all associated files
2306 if ($this->editorcontext !== null) {
2307 $fs = get_file_storage();
2308 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
2309 foreach ($files as $file) {
2314 // Fire the event deleted hook
2315 self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));
2317 // If we need to delete repeated events then we will fetch them all and delete one by one
2318 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2319 // Get all records where the repeatid is the same as the event being removed
2320 $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
2321 // For each of the returned events populate a calendar_event object and call delete
2322 // make sure the arg passed is false as we are already deleting all repeats
2323 foreach ($events as $event) {
2324 $event = new calendar_event($event);
2325 $event->delete(false);
2333 * Fetch all event properties
2335 * This function returns all of the events properties as an object and optionally
2336 * can prepare an editor for the description field at the same time. This is
2337 * designed to work when the properties are going to be used to set the default
2338 * values of a moodle forms form.
2340 * @param bool $prepareeditor If set to true a editor is prepared for use with
2341 * the mforms editor element. (for description)
2342 * @return stdClass Object containing event properties
2344 public function properties($prepareeditor=false) {
2345 global $USER, $CFG, $DB;
2347 // First take a copy of the properties. We don't want to actually change the
2348 // properties or we'd forever be converting back and forwards between an
2349 // editor formatted description and not
2350 $properties = clone($this->properties);
2351 // Clean the description here
2352 $properties->description = clean_text($properties->description, $properties->format);
2354 // If set to true we need to prepare the properties for use with an editor
2355 // and prepare the file area
2356 if ($prepareeditor) {
2358 // We may or may not have a property id. If we do then we need to work
2359 // out the context so we can copy the existing files to the draft area
2360 if (!empty($properties->id)) {
2362 if ($properties->eventtype === 'site') {
2364 $this->editorcontext = $this->properties->context;
2365 } else if ($properties->eventtype === 'user') {
2367 $this->editorcontext = $this->properties->context;
2368 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
2369 // First check the course is valid
2370 $course = $DB->get_record('course', array('id'=>$properties->courseid));
2372 print_error('invalidcourse');
2375 $this->editorcontext = $this->properties->context;
2376 // We have a course and are within the course context so we had
2377 // better use the courses max bytes value
2378 $this->editoroptions['maxbytes'] = $course->maxbytes;
2380 // If we get here we have a custom event type as used by some
2381 // modules. In this case the event will have been added by
2382 // code and we won't need the editor
2383 $this->editoroptions['maxbytes'] = 0;
2384 $this->editoroptions['maxfiles'] = 0;
2387 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2390 // Get the context id that is what we really want
2391 $contextid = $this->editorcontext->id;
2395 // If we get here then this is a new event in which case we don't need a
2396 // context as there is no existing files to copy to the draft area.
2400 // If the contextid === false we don't support files so no preparing
2402 if ($contextid !== false) {
2403 // Just encase it has already been submitted
2404 $draftiddescription = file_get_submitted_draft_itemid('description');
2405 // Prepare the draft area, this copies existing files to the draft area as well
2406 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id, $this->editoroptions, $properties->description);
2408 $draftiddescription = 0;
2411 // Structure the description field as the editor requires
2412 $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2415 // Finally return the properties
2420 * Toggles the visibility of an event
2422 * @param null|bool $force If it is left null the events visibility is flipped,
2423 * If it is false the event is made hidden, if it is true it
2425 * @return bool if event is successfully updated, toggle will be visible
2427 public function toggle_visibility($force=null) {
2430 // Set visible to the default if it is not already set
2431 if (empty($this->properties->visible)) {
2432 $this->properties->visible = 1;
2435 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2436 // Make this event visible
2437 $this->properties->visible = 1;
2439 self::calendar_event_hook('show_event', array($this->properties));
2441 // Make this event hidden
2442 $this->properties->visible = 0;
2444 self::calendar_event_hook('hide_event', array($this->properties));
2447 // Update the database to reflect this change
2448 return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2452 * Attempts to call the hook for the specified action should a calendar type
2453 * by set $CFG->calendar, and the appopriate function defined
2455 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2456 * @param array $args The args to pass to the hook, usually the event is the first element
2457 * @return bool attempts to call event hook
2459 public static function calendar_event_hook($action, array $args) {
2461 static $extcalendarinc;
2462 if ($extcalendarinc === null) {
2463 if (!empty($CFG->calendar)) {
2464 if (is_readable($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
2465 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
2466 $extcalendarinc = true;
2468 debugging("Calendar lib file missing or not readable at /calendar/{$CFG->calendar}/lib.php.",
2470 $extcalendarinc = false;
2473 $extcalendarinc = false;
2476 if($extcalendarinc === false) {
2479 $hook = $CFG->calendar .'_'.$action;
2480 if (function_exists($hook)) {
2481 call_user_func_array($hook, $args);
2488 * Returns a calendar_event object when provided with an event id
2490 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2491 * it will result in an exception being thrown
2493 * @param int|object $param event object or event id
2494 * @return calendar_event|false status for loading calendar_event
2496 public static function load($param) {
2498 if (is_object($param)) {
2499 $event = new calendar_event($param);
2501 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2502 $event = new calendar_event($event);
2508 * Creates a new event and returns a calendar_event object
2510 * @param object|array $properties An object containing event properties
2511 * @return calendar_event|false The event object or false if it failed
2513 public static function create($properties) {
2514 if (is_array($properties)) {
2515 $properties = (object)$properties;
2517 if (!is_object($properties)) {
2518 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2520 $event = new calendar_event($properties);
2521 if ($event->update($properties)) {
2530 * Calendar information class
2532 * This class is used simply to organise the information pertaining to a calendar
2533 * and is used primarily to make information easily available.
2535 * @package core_calendar
2536 * @category calendar
2537 * @copyright 2010 Sam Hemelryk
2538 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2540 class calendar_information {
2541 /** @var int The day */
2544 /** @var int The month */
2547 /** @var int The year */
2550 /** @var int A course id */
2551 public $courseid = null;
2553 /** @var array An array of courses */
2554 public $courses = array();
2556 /** @var array An array of groups */
2557 public $groups = array();
2559 /** @var array An array of users */
2560 public $users = array();
2563 * Creates a new instance
2565 * @param int $day the number of the day
2566 * @param int $month the number of the month
2567 * @param int $year the number of the year
2569 public function __construct($day=0, $month=0, $year=0) {
2571 $date = usergetdate(time());
2574 $day = $date['mday'];
2577 if (empty($month)) {
2578 $month = $date['mon'];
2582 $year = $date['year'];
2586 $this->month = $month;
2587 $this->year = $year;
2591 * Initialize calendar information
2593 * @param stdClass $course object
2594 * @param array $coursestoload An array of courses [$course->id => $course]
2595 * @param bool $ignorefilters options to use filter
2597 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
2598 $this->courseid = $course->id;
2599 $this->course = $course;
2600 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2601 $this->courses = $courses;
2602 $this->groups = $group;
2603 $this->users = $user;
2607 * Ensures the date for the calendar is correct and either sets it to now
2608 * or throws a moodle_exception if not
2610 * @param bool $defaultonow use current time
2611 * @throws moodle_exception
2612 * @return bool validation of checkdate
2614 public function checkdate($defaultonow = true) {
2615 if (!checkdate($this->month, $this->day, $this->year)) {
2617 $now = usergetdate(time());
2618 $this->day = intval($now['mday']);
2619 $this->month = intval($now['mon']);
2620 $this->year = intval($now['year']);
2623 throw new moodle_exception('invaliddate');
2629 * Gets todays timestamp for the calendar
2631 * @return int today timestamp
2633 public function timestamp_today() {
2634 return make_timestamp($this->year, $this->month, $this->day);
2637 * Gets tomorrows timestamp for the calendar
2639 * @return int tomorrow timestamp
2641 public function timestamp_tomorrow() {
2642 return make_timestamp($this->year, $this->month, $this->day+1);
2645 * Adds the pretend blocks for the calendar
2647 * @param core_calendar_renderer $renderer
2648 * @param bool $showfilters display filters, false is set as default
2649 * @param string|null $view preference view options (eg: day, month, upcoming)
2651 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
2653 $filters = new block_contents();
2654 $filters->content = $renderer->fake_block_filters($this->courseid, $this->day, $this->month, $this->year, $view, $this->courses);
2655 $filters->footer = '';
2656 $filters->title = get_string('eventskey', 'calendar');
2657 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
2659 $block = new block_contents;
2660 $block->content = $renderer->fake_block_threemonths($this);
2661 $block->footer = '';
2662 $block->title = get_string('monthlyview', 'calendar');
2663 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
2668 * Returns option list for the poll interval setting.
2670 * @return array An array of poll interval options. Interval => description.
2672 function calendar_get_pollinterval_choices() {
2674 '0' => new lang_string('never', 'calendar'),
2675 '3600' => new lang_string('hourly', 'calendar'),
2676 '86400' => new lang_string('daily', 'calendar'),
2677 '604800' => new lang_string('weekly', 'calendar'),
2678 '2628000' => new lang_string('monthly', 'calendar'),
2679 '31536000' => new lang_string('annually', 'calendar')
2684 * Returns option list of available options for the calendar event type, given the current user and course.
2686 * @param int $courseid The id of the course
2687 * @return array An array containing the event types the user can create.
2689 function calendar_get_eventtype_choices($courseid) {
2691 $allowed = new stdClass;
2692 calendar_get_allowed_types($allowed, $courseid);
2694 if ($allowed->user) {
2695 $choices[0] = get_string('userevents', 'calendar');
2697 if ($allowed->site) {
2698 $choices[SITEID] = get_string('siteevents', 'calendar');
2700 if (!empty($allowed->courses)) {
2701 $choices[$courseid] = get_string('courseevents', 'calendar');
2703 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2704 $choices['group'] = get_string('group');
2707 return array($choices, $allowed->groups);
2711 * Add an iCalendar subscription to the database.
2713 * @param stdClass $sub The subscription object (e.g. from the form)
2714 * @return int The insert ID, if any.
2716 function calendar_add_subscription($sub) {
2719 $sub->courseid = $sub->eventtype;
2720 if ($sub->eventtype == 'group') {
2721 $sub->courseid = $sub->course;
2723 $sub->userid = $USER->id;
2725 // File subscriptions never update.
2726 if (empty($sub->url)) {
2727 $sub->pollinterval = 0;
2730 if (!empty($sub->name)) {
2731 if (empty($sub->id)) {
2732 $id = $DB->insert_record('event_subscriptions', $sub);
2735 $DB->update_record('event_subscriptions', $sub);
2739 print_error('errorbadsubscription', 'importcalendar');
2744 * Add an iCalendar event to the Moodle calendar.
2746 * @param object $event The RFC-2445 iCalendar event
2747 * @param int $courseid The course ID
2748 * @param int $subscriptionid The iCalendar subscription ID
2749 * @return int Code: 1=updated, 2=inserted, 0=error
2751 function calendar_add_icalendar_event($event, $courseid, $subscriptionid = null) {
2754 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2755 if (empty($event->properties['SUMMARY'])) {
2759 $name = $event->properties['SUMMARY'][0]->value;
2760 $name = str_replace('\n', '<br />', $name);
2761 $name = str_replace('\\', '', $name);
2762 $name = preg_replace('/\s+/', ' ', $name);
2764 $eventrecord = new stdClass;
2765 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2767 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2770 $description = $event->properties['DESCRIPTION'][0]->value;
2771 $description = str_replace('\n', '<br />', $description);
2772 $description = str_replace('\\', '', $description);
2773 $description = preg_replace('/\s+/', ' ', $description);
2775 $eventrecord->description = clean_param($description, PARAM_NOTAGS);
2777 // Probably a repeating event with RRULE etc. TODO: skip for now.
2778 if (empty($event->properties['DTSTART'][0]->value)) {
2782 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value);
2783 if (empty($event->properties['DTEND'])) {
2784 $eventrecord->timeduration = 3600; // one hour if no end time specified
2786 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value) - $eventrecord->timestart;
2788 $eventrecord->uuid = $event->properties['UID'][0]->value;
2789 $eventrecord->timemodified = time();
2791 // Add the iCal subscription details if required.
2792 if ($sub = $DB->get_record('event_subscriptions', array('id' => $subscriptionid))) {
2793 $eventrecord->subscriptionid = $subscriptionid;
2794 $eventrecord->userid = $sub->userid;
2795 $eventrecord->groupid = $sub->groupid;
2796 $eventrecord->courseid = $sub->courseid;
2798 $eventrecord->userid = $USER->id;
2799 $eventrecord->groupid = 0; // TODO: ???
2800 $eventrecord->courseid = $courseid;
2803 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid))) {
2804 $eventrecord->id = $updaterecord->id;
2805 if ($DB->update_record('event', $eventrecord)) {
2806 return CALENDAR_IMPORT_EVENT_UPDATED;
2811 if ($DB->insert_record('event', $eventrecord)) {
2812 return CALENDAR_IMPORT_EVENT_INSERTED;
2820 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2822 * @param int $subscriptionid The ID of the subscription we are acting upon.
2823 * @param int $pollinterval The poll interval to use.
2824 * @param int $action The action to be performed. One of update or remove.
2825 * @return string A log of the import progress, including errors
2827 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2830 if (empty($subscriptionid)) {
2834 // Fetch the subscription from the database making sure it exists.
2835 $sub = $DB->get_record('event_subscriptions', array('id' => $subscriptionid), '*', MUST_EXIST);
2837 $strupdate = get_string('update');
2838 $strremove = get_string('remove');
2839 // Update or remove the subscription, based on action.
2842 // Skip updating file subscriptions.
2843 if (empty($sub->url)) {
2846 $sub->pollinterval = $pollinterval;
2847 $DB->update_record('event_subscriptions', $sub);
2849 // Update the events.
2850 return "<p>".get_string('subscriptionupdated', 'calendar', $sub->name)."</p>" . calendar_update_subscription_events($subscriptionid);
2853 $DB->delete_records('event', array('subscriptionid' => $subscriptionid));
2854 $DB->delete_records('event_subscriptions', array('id' => $subscriptionid));
2855 return get_string('subscriptionremoved', 'calendar', $sub->name);
2865 * From a URL, fetch the calendar and return an iCalendar object.
2867 * @param string $url The iCalendar URL
2868 * @return stdClass The iCalendar object
2870 function calendar_get_icalendar($url) {
2873 require_once($CFG->libdir.'/filelib.php');
2876 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
2877 $calendar = $curl->get($url);
2878 // Http code validation should actually be the job of curl class.
2879 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
2880 throw new moodle_exception('errorinvalidicalurl', 'calendar');
2883 $ical = new iCalendar();
2884 $ical->unserialize($calendar);
2889 * Import events from an iCalendar object into a course calendar.
2891 * @param stdClass $ical The iCalendar object.
2892 * @param int $courseid The course ID for the calendar.
2893 * @param int $subscriptionid The subscription ID.
2894 * @return string A log of the import progress, including errors.
2896 function calendar_import_icalendar_events($ical, $courseid, $subscriptionid = null) {
2902 // Large calendars take a while...
2903 set_time_limit(300);
2905 // Mark all events in a subscription with a zero timestamp.
2906 if (!empty($subscriptionid)) {
2907 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
2908 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
2910 foreach ($ical->components['VEVENT'] as $event) {
2911 $res = calendar_add_icalendar_event($event, $courseid, $subscriptionid);
2913 case CALENDAR_IMPORT_EVENT_UPDATED:
2916 case CALENDAR_IMPORT_EVENT_INSERTED:
2920 $return .= '<p>'.get_string('erroraddingevent', 'calendar').': '.(empty($event->properties['SUMMARY'])?'('.get_string('notitle', 'calendar').')':$event->properties['SUMMARY'][0]->value)." </p>\n";
2924 $return .= "<p> ".get_string('eventsimported', 'calendar', $eventcount)."</p>";
2925 $return .= "<p> ".get_string('eventsupdated', 'calendar', $updatecount)."</p>";
2927 // Delete remaining zero-marked events since they're not in remote calendar.
2928 if (!empty($subscriptionid)) {
2929 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
2930 if (!empty($deletecount)) {
2931 $sql = "DELETE FROM {event} WHERE timemodified = :time AND subscriptionid = :id";
2932 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
2933 $return .= "<p> ".get_string('eventsdeleted', 'calendar').": {$deletecount} </p>\n";
2941 * Fetch a calendar subscription and update the events in the calendar.
2943 * @param int $subscriptionid The course ID for the calendar.
2944 * @return string A log of the import progress, including errors.
2946 function calendar_update_subscription_events($subscriptionid) {
2949 $sub = $DB->get_record('event_subscriptions', array('id' => $subscriptionid));
2951 print_error('errorbadsubscription', 'calendar');
2953 // Don't update a file subscription. TODO: Update from a new uploaded file.
2954 if (empty($sub->url)) {
2955 return 'File subscription not updated.';
2957 $ical = calendar_get_icalendar($sub->url);
2958 $return = calendar_import_icalendar_events($ical, $sub->courseid, $subscriptionid);
2959 $sub->lastupdated = time();
2960 $DB->update_record('event_subscriptions', $sub);
2965 * Update calendar subscriptions.
2969 function calendar_cron() {
2972 // In order to execute this we need bennu.
2973 require_once($CFG->libdir.'/bennu/bennu.inc.php');
2975 mtrace('Updating calendar subscriptions:');
2978 $subscriptions = $DB->get_records_sql('SELECT * FROM {event_subscriptions} WHERE pollinterval > 0 AND lastupdated + pollinterval < ?', array($time));
2979 foreach ($subscriptions as $sub) {
2980 mtrace("Updating calendar subscription {$sub->name} in course {$sub->courseid}");
2982 $log = calendar_update_subscription_events($sub->id);
2983 } catch (moodle_exception $ex) {
2986 mtrace(trim(strip_tags($log)));
2989 mtrace('Finished updating calendar subscriptions.');