Merge branch 'MDL-36679-master' of github.com:damyon/moodle
[moodle.git] / calendar / lib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * Calendar extension
19  *
20  * @package    core_calendar
21  * @copyright  2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
22  *             Avgoustos Tsinakos
23  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24  */
26 if (!defined('MOODLE_INTERNAL')) {
27     die('Direct access to this script is forbidden.');    ///  It must be included from a Moodle page
28 }
30 /**
31  *  These are read by the administration component to provide default values
32  */
34 /**
35  * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
36  */
37 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
39 /**
40  * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
41  */
42 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
44 /**
45  * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
46  */
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
52 /**
53  * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
54  */
55 define('CALENDAR_DEFAULT_WEEKEND', 65);
57 /**
58  * CALENDAR_URL - path to calendar's folder
59  */
60 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
62 /**
63  * CALENDAR_TF_24 - Calendar time in 24 hours format
64  */
65 define('CALENDAR_TF_24', '%H:%M');
67 /**
68  * CALENDAR_TF_12 - Calendar time in 12 hours format
69  */
70 define('CALENDAR_TF_12', '%I:%M %p');
72 /**
73  * CALENDAR_EVENT_GLOBAL - Global calendar event types
74  */
75 define('CALENDAR_EVENT_GLOBAL', 1);
77 /**
78  * CALENDAR_EVENT_COURSE - Course calendar event types
79  */
80 define('CALENDAR_EVENT_COURSE', 2);
82 /**
83  * CALENDAR_EVENT_GROUP - group calendar event types
84  */
85 define('CALENDAR_EVENT_GROUP', 4);
87 /**
88  * CALENDAR_EVENT_USER - user calendar event types
89  */
90 define('CALENDAR_EVENT_USER', 8);
93 /**
94  * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
95  */
96 define('CALENDAR_IMPORT_FROM_FILE', 0);
98 /**
99  * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
100  */
101 define('CALENDAR_IMPORT_FROM_URL',  1);
103 /**
104  * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
105  */
106 define('CALENDAR_IMPORT_EVENT_UPDATED',  1);
108 /**
109  * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
110  */
111 define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
113 /**
114  * Return the days of the week
115  *
116  * @return array array of days
117  */
118 function calendar_get_days() {
119     return array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
122 /**
123  * Gets the first day of the week
124  *
125  * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
126  *
127  * @return int
128  */
129 function calendar_get_starting_weekday() {
130     global $CFG;
132     if (isset($CFG->calendar_startwday)) {
133         $firstday = $CFG->calendar_startwday;
134     } else {
135         $firstday = get_string('firstdayofweek', 'langconfig');
136     }
138     if(!is_numeric($firstday)) {
139         return CALENDAR_DEFAULT_STARTING_WEEKDAY;
140     } else {
141         return intval($firstday) % 7;
142     }
145 /**
146  * Generates the HTML for a miniature calendar
147  *
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
154  */
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;
162     $content = '';
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
168             $date = $thisdate;
169             $display->thismonth = true;
170         } else {
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;
175             } else {
176                 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
177                 $display->thismonth = false;
178             }
179         }
180     } else {
181         $date = usergetdate(time()); // Date and time the user sees at his location
182         $display->thismonth = true;
183     }
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
193     } else {
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);
197     }
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) {
204         $startwday += 7;
205     }
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);
215     //}
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);
218     //}
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]);
234                 }
235             }
236         }
237     }
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);
249         }
250     }
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";
271     }
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">&nbsp;</td>'."\n";
281     }
283     $weekend = CALENDAR_DEFAULT_WEEKEND;
284     if (isset($CFG->calendar_weekend)) {
285         $weekend = intval($CFG->calendar_weekend);
286     }
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;
294         }
296         // Reset vars
297         $cell = '';
298         if ($weekend & (1 << ($dayweek % 7))) {
299             // Weekend. This is true no matter what the exact range is.
300             $class = 'weekend day';
301         } else {
302             // Normal working day.
303             $class = 'day';
304         }
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);
312             $popupcontent = '';
313             foreach($eventsbyday[$day] as $eventid) {
314                 if (!isset($events[$eventid])) {
315                     continue;
316                 }
317                 $event = $events[$eventid];
318                 $popupalt  = '';
319                 $component = 'moodle';
320                 if(!empty($event->modulename)) {
321                     $popupicon = 'icon';
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';
332                 }
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');
340             }
342             //Accessibility: functionality moved to calendar_get_popup.
343             if($display->thismonth && $day == $d) {
344                 $popupid = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
345             } else {
346                 $popupid = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
347             }
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';
358             }
359             $cell = html_writer::link($dayhref, $day, array('aria-controls' => $popupid.'_panel', 'id' => $popupid));
360         } else {
361             $cell = $day;
362         }
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';
373         }
374         if ($durationclass) {
375             $class .= ' duration '.$durationclass;
376         }
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])) {
383                     continue;
384                 }
385                 $event = $events[$eventid];
386                 if (!empty($event->class)) {
387                     $class .= ' '.$event->class;
388                 }
389                 break;
390             }
391         }
393         // Special visual fx for today
394         //Accessibility: hidden text for today, and popup.
395         if($display->thismonth && $day == $d) {
396             $class .= ' today';
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));
403             }
404             $cell = get_accesshide($today.' ').$cell;
405         }
407         // Just display it
408         if(!empty($class)) {
409             $class = ' class="'.$class.'"';
410         }
411         $content .= '<td'.$class.'>'.$cell."</td>\n";
412     }
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">&nbsp;</td>';
417     }
418     $content .= '</tr>'; // Last row ends
420     $content .= '</table>'; // Tabular display of days ends
422     return $content;
425 /**
426  * Gets the calendar popup
427  *
428  * It called at multiple points in from calendar_get_mini.
429  * Copied and modified from calendar_get_mini.
430  *
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.
435  */
436 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
437     global $PAGE;
438     static $popupcount;
439     if ($popupcount === null) {
440         $popupcount = 1;
441     }
442     $popupcaption = '';
443     if($is_today) {
444         $popupcaption = get_string('today', 'calendar').' ';
445     }
446     if (false === $event_timestart) {
447         $popupcaption .= userdate(time(), get_string('strftimedayshort'));
448         $popupcontent = get_string('eventnone', 'calendar');
450     } else {
451         $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
452     }
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)));
456     $popupcount++;
457     return $id;
460 /**
461  * Gets the calendar upcoming event
462  *
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
470  */
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;
478     $output = array();
480     // Prepare "course caching", since it may save us a lot of queries
481     $coursecache = array();
483     $processed = 0;
484     $now = time(); // We 'll need this later
485     $usermidnighttoday = usergetmidnight($now);
487     if ($fromtime) {
488         $display->tstart = $fromtime;
489     } else {
490         $display->tstart = $usermidnighttoday;
491     }
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);
510         }
511     }
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) {
525                             continue;
526                         }
527                     }
528                 } else {
529                     if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
530                         continue;
531                     }
532                     if (!coursemodule_visible_for_user($cm)) {
533                         continue;
534                     }
535                 }
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');
544                             continue;
545                         }
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')) {
550                             continue;
551                         }
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');
559                         }
560                     }
561                 }
562             }
564             if ($processed >= $display->maxevents) {
565                 break;
566             }
568             $event->time = calendar_format_event_time($event, $now, $hrefparams);
569             $output[] = $event;
570             ++$processed;
571         }
572     }
573     return $output;
576 /**
577  * Add calendar event metadata
578  *
579  * @param stdClass $event event info
580  * @return stdClass $event metadata
581  */
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) {
595             return;
596         }
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);
602         } else {
603             $eventtype = '';
604         }
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';
634     }
635     return $event;
638 /**
639  * Get calendar events
640  *
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)
650  */
651 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
652     global $DB;
654     $whereclause = '';
655     // Quick test
656     if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
657         return array();
658     }
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
674     }
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';
688     }
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';
694         }
695         $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
696     } else if(is_numeric($courses)) {
697         // One course
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)';
704     }
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)) {
711         return array();
712     }
714     if($withduration) {
715         $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
716     }
717     else {
718         $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
719     }
720     if(!empty($whereclause)) {
721         // We have additional constraints
722         $whereclause = $timeclause.' AND ('.$whereclause.')';
723     }
724     else {
725         // Just basic time filtering
726         $whereclause = $timeclause;
727     }
729     if ($ignorehidden) {
730         $whereclause .= ' AND visible = 1';
731     }
733     $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
734     if ($events === false) {
735         $events = array();
736     }
737     return $events;
740 /**
741  * Get control options for Calendar
742  *
743  * @param string $type of calendar
744  * @param array $data calendar information
745  * @return string $content return available control for the calender in html
746  */
747 function calendar_top_controls($type, $data) {
748     global $CFG;
749     $content = '';
750     if(!isset($data['d'])) {
751         $data['d'] = 1;
752     }
754     // Ensure course id passed if relevant
755     // Required due to changes in view/lib.php mainly (calendar_session_vars())
756     $courseid = '';
757     if (!empty($data['id'])) {
758         $courseid = '&amp;course='.$data['id'];
759     }
761     if(!checkdate($data['m'], $data['d'], $data['y'])) {
762         $time = time();
763     }
764     else {
765         $time = make_timestamp($data['y'], $data['m'], $data['d']);
766     }
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);
776     switch($type) {
777         case 'frontpage':
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']);
786             }
788             if (right_to_left()) {
789                 $left = $nextlink;
790                 $right = $prevlink;
791             } else {
792                 $left = $prevlink;
793                 $right = $nextlink;
794             }
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');
803             break;
804         case 'course':
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'].'&amp;', 0, $nextmonth, $nextyear, $accesshide=true);
808             $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&amp;', 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']);
813             }
815             if (right_to_left()) {
816                 $left = $nextlink;
817                 $right = $prevlink;
818             } else {
819                 $left = $prevlink;
820                 $right = $nextlink;
821             }
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');
829             break;
830         case 'upcoming':
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']);
834             }
835             $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
836             $content .= html_writer::tag('div', $calendarlink, array('class'=>'centered'));
837             break;
838         case 'display':
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']);
842             }
843             $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
844             $content .= html_writer::tag('h3', $calendarlink);
845             break;
846         case 'month':
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.'&amp;', 1, $prevmonth, $prevyear);
852             $nextlink = calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $nextmonth, $nextyear);
854             if (right_to_left()) {
855                 $left = $nextlink;
856                 $right = $prevlink;
857             } else {
858                 $left = $prevlink;
859                 $right = $nextlink;
860             }
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";
867             break;
868         case 'day':
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.'&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
876             $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
878             if (right_to_left()) {
879                 $left = $nextlink;
880                 $right = $prevlink;
881             } else {
882                 $left = $prevlink;
883                 $right = $nextlink;
884             }
886             $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
887             $content .= $left;
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";
893             break;
894     }
895     return $content;
898 /**
899  * Formats a filter control element.
900  *
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
904  */
905 function calendar_filter_controls_element(moodle_url $url, $type) {
906     global $OUTPUT;
907     switch ($type) {
908         case CALENDAR_EVENT_GLOBAL:
909             $typeforhumans = 'global';
910             $class = 'calendar_event_global';
911             break;
912         case CALENDAR_EVENT_COURSE:
913             $typeforhumans = 'course';
914             $class = 'calendar_event_course';
915             break;
916         case CALENDAR_EVENT_GROUP:
917             $typeforhumans = 'groups';
918             $class = 'calendar_event_group';
919             break;
920         case CALENDAR_EVENT_USER:
921             $typeforhumans = 'user';
922             $class = 'calendar_event_user';
923             break;
924     }
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');
928     } else {
929         $icon = $OUTPUT->pix_icon('t/show', get_string('show'));
930         $str = get_string('show'.$typeforhumans.'events', 'calendar');
931     }
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');
938     return $content;
941 /**
942  * Get the controls filter for calendar.
943  *
944  * Filter is used to hide calendar info from the display page
945  *
946  * @param moodle_url $returnurl return-url for filter controls
947  * @return string $content return filter controls in html
948  */
949 function calendar_filter_controls(moodle_url $returnurl) {
950     global $CFG, $USER, $OUTPUT;
952     $groupevents = true;
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()) {
964         if ($groupevents) {
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);
968         } else {
969             // This course CANNOT have group events, so lose the filter
970         }
971         $seturl->param('var', 'showuser');
972         $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_USER);
973     }
974     $content .= html_writer::end_tag('ul');
976     return $content;
979 /**
980  * Return the representation day
981  *
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
986  */
987 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
989     static $shortformat;
990     if(empty($shortformat)) {
991         $shortformat = get_string('strftimedayshort');
992     }
994     if($now === false) {
995         $now = time();
996     }
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
1006         return $formal;
1007     }
1008     else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1009         // Today
1010         return get_string('today', 'calendar');
1011     }
1012     else if(
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)
1015         ) {
1016         // Yesterday
1017         return get_string('yesterday', 'calendar');
1018     }
1019     else if(
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)
1022         ) {
1023         // Tomorrow
1024         return get_string('tomorrow', 'calendar');
1025     }
1026     else {
1027         return $formal;
1028     }
1031 /**
1032  * return the formatted representation time
1033  *
1034  * @param int $time the timestamp in UTC, as obtained from the database
1035  * @return string the formatted date/time
1036  */
1037 function calendar_time_representation($time) {
1038     static $langtimeformat = NULL;
1039     if($langtimeformat === NULL) {
1040         $langtimeformat = get_string('strftimetime');
1041     }
1042     $timeformat = get_user_preferences('calendar_timeformat');
1043     if(empty($timeformat)){
1044         $timeformat = get_config(NULL,'calendar_site_timeformat');
1045     }
1046     // The ? is needed because the preference might be present, but empty
1047     return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
1050 /**
1051  * Adds day, month, year arguments to a URL and returns a moodle_url object.
1052  *
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
1058  */
1059 function calendar_get_link_href($linkbase, $d, $m, $y) {
1060     if (empty($linkbase)) {
1061         return '';
1062     }
1063     if (!($linkbase instanceof moodle_url)) {
1064         $linkbase = new moodle_url($linkbase);
1065     }
1066     if (!empty($d)) {
1067         $linkbase->param('cal_d', $d);
1068     }
1069     if (!empty($m)) {
1070         $linkbase->param('cal_m', $m);
1071     }
1072     if (!empty($y)) {
1073         $linkbase->param('cal_y', $y);
1074     }
1075     return $linkbase;
1078 /**
1079  * Build and return a previous month HTML link, with an arrow.
1080  *
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.
1088  */
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);
1091     if (empty($href)) {
1092         return $text;
1093     }
1094     return link_arrow_left($text, (string)$href, $accesshide, 'previous');
1097 /**
1098  * Build and return a next month HTML link, with an arrow.
1099  *
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.
1107  */
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);
1110     if (empty($href)) {
1111         return $text;
1112     }
1113     return link_arrow_right($text, (string)$href, $accesshide, 'next');
1116 /**
1117  * Return the name of the weekday
1118  *
1119  * @param string $englishname
1120  * @return string of the weekeday
1121  */
1122 function calendar_wday_name($englishname) {
1123     return get_string(strtolower($englishname), 'calendar');
1126 /**
1127  * Return the number of days in month
1128  *
1129  * @param int $month the number of the month.
1130  * @param int $year the number of the year
1131  * @return int
1132  */
1133 function calendar_days_in_month($month, $year) {
1134    return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
1137 /**
1138  * Get the upcoming event block
1139  *
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
1143  */
1144 function calendar_get_block_upcoming($events, $linkhref = NULL) {
1145     $content = '';
1146     $lines = count($events);
1147     if (!$lines) {
1148         return $content;
1149     }
1151     for ($i = 0; $i < $lines; ++$i) {
1152         if (!isset($events[$i]->time)) {   // Just for robustness
1153             continue;
1154         }
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;
1160         } else {
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);
1166             }
1167             else {
1168                 $content .= $events[$i]->name;
1169             }
1170         }
1171         $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
1172         $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
1173         if ($i < $lines - 1) $content .= '<hr />';
1174     }
1176     return $content;
1179 /**
1180  * Get the next following month
1181  *
1182  * If the current month is December, it will get the first month of the following year.
1183  *
1184  *
1185  * @param int $month the number of the month.
1186  * @param int $year the number of the year.
1187  * @return array the following month
1188  */
1189 function calendar_add_month($month, $year) {
1190     if($month == 12) {
1191         return array(1, $year + 1);
1192     }
1193     else {
1194         return array($month + 1, $year);
1195     }
1198 /**
1199  * Get the previous month
1200  *
1201  * If the current month is January, it will get the last month of the previous year.
1202  *
1203  * @param int $month the number of the month.
1204  * @param int $year the number of the year.
1205  * @return array previous month
1206  */
1207 function calendar_sub_month($month, $year) {
1208     if($month == 1) {
1209         return array(12, $year - 1);
1210     }
1211     else {
1212         return array($month - 1, $year);
1213     }
1216 /**
1217  * Get per-day basis events
1218  *
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
1226  * @return void
1227  */
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) {
1234         return;
1235     }
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);
1243         } else {
1244             $enddate = $startdate;
1245         }
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)) {
1249             // Out of bounds
1250             continue;
1251         }
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';
1264             }
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';
1269             }
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';
1274             }
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';
1279             }
1280         }
1282         if($event->timeduration == 0) {
1283             // Proceed with the next
1284             continue;
1285         }
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;
1298             }
1299             else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1300                 $typesbyday[$i]['durationcourse'] = true;
1301             }
1302             else if($event->groupid) {
1303                 $typesbyday[$i]['durationgroup'] = true;
1304             }
1305             else if($event->userid) {
1306                 $typesbyday[$i]['durationuser'] = true;
1307             }
1308         }
1310     }
1311     return;
1314 /**
1315  * Get current module cache
1316  *
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
1321  */
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)) {
1327         return false;
1328     }
1329     return $module;
1332 /**
1333  * Get current course cache
1334  *
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
1338  */
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;
1345         } else {
1346             $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
1347         }
1348     }
1349     return $coursecache[$courseid];
1352 /**
1353  * Returns the courses to load events for, the
1354  *
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
1358  */
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]);
1369         }
1370     }
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));
1375     }
1377     $courses = array();
1378     $user = false;
1379     $group = false;
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);
1389     }
1390     if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
1391         $courses[] = SITEID;
1392     }
1393     $courses = array_unique($courses);
1394     sort($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;
1402     }
1404     if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
1405         $user = $USER->id;
1406     }
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);
1415             }
1416         }
1417         if ($group === false) {
1418             if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, get_system_context())) {
1419                 $group = true;
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']);
1434                     }
1435                 }
1436                 if (!empty($groupids)) {
1437                     $group = $groupids;
1438                 }
1439             }
1440         }
1441     }
1442     if (empty($courses)) {
1443         $courses = false;
1444     }
1446     return array($courses, $group, $user);
1449 /**
1450  * Return the capability for editing calendar event
1451  *
1452  * @param calendar_event $event event object
1453  * @return bool capability to edit event
1454  */
1455 function calendar_edit_event_allowed($event) {
1456     global $USER, $DB;
1458     // Must be logged in
1459     if (!isloggedin()) {
1460         return false;
1461     }
1463     // can not be using guest account
1464     if (isguestuser()) {
1465         return false;
1466     }
1468     // You cannot edit calendar subscription events presently.
1469     if (!empty($event->subscriptionid)) {
1470         return false;
1471     }
1473     $sitecontext = context_system::instance();
1474     // if user has manageentries at site level, return true
1475     if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1476         return true;
1477     }
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));
1485         return $group && (
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));
1498     }
1499     return false;
1502 /**
1503  * Returns the default courses to display on the calendar when there isn't a specific
1504  * course to display.
1505  *
1506  * @return array $courses Array of courses to display
1507  */
1508 function calendar_get_default_courses() {
1509     global $CFG, $DB;
1511     if (!isloggedin()) {
1512         return array();
1513     }
1515     $courses = array();
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
1519                   FROM {course} c
1520                   $join
1521                   WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
1522                   ";
1523         $courses = $DB->get_records_sql($sql, null, 0, 20);
1524         foreach ($courses as $course) {
1525             context_helper::preload_from_record($course);
1526         }
1527         return $courses;
1528     }
1530     $courses = enrol_get_my_courses();
1532     return $courses;
1535 /**
1536  * Display calendar preference button
1537  *
1538  * @param stdClass $course course object
1539  * @return string return preference button in html
1540  */
1541 function calendar_preferences_button(stdClass $course) {
1542     global $OUTPUT;
1544     // Guests have no preferences
1545     if (!isloggedin() || isguestuser()) {
1546         return '';
1547     }
1549     return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id)), get_string("preferences", "calendar"));
1552 /**
1553  * Get event format time
1554  *
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
1561  */
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);
1570     }
1571     else {
1572         $usermidnightend = $usermidnightstart;
1573     }
1575     if (empty($linkparams) || !is_array($linkparams)) {
1576         $linkparams = array();
1577     }
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>&raquo;</strong> '.$timeend;
1593             if ($event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399)) {
1594                 $time = get_string('allday', 'calendar');
1595             }
1597             // Set printable representation
1598             if (!$showtime) {
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;
1602             } else {
1603                 $eventtime = $time;
1604             }
1605         } else {
1606             // It spans two or more days
1607             $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords).', ';
1608             if ($showtime == $usermidnightstart) {
1609                 $daystart = '';
1610             }
1611             $timestart = calendar_time_representation($event->timestart);
1612             $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords).', ';
1613             if ($showtime == $usermidnightend) {
1614                 $dayend = '';
1615             }
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>&raquo;</strong> '.html_writer::link($url, $dayend).$timeend;
1622             } else {
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>&raquo;</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;
1628             }
1629         }
1630     } else {
1631         $time = calendar_time_representation($event->timestart);
1633         // Set printable representation
1634         if (!$showtime) {
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);
1638         } else {
1639             $eventtime = $time;
1640         }
1641     }
1643     if($event->timestart + $event->timeduration < $now) {
1644         // It has expired
1645         $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
1646     }
1648     return $eventtime;
1651 /**
1652  * Display month selector options
1653  *
1654  * @param string $name for the select element
1655  * @param string|array $selected options for select elements
1656  */
1657 function calendar_print_month_selector($name, $selected) {
1658     $months = array();
1659     for ($i=1; $i<=12; $i++) {
1660         $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1661     }
1662     echo html_writer::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
1663     echo html_writer::select($months, $name, $selected, false);
1666 /**
1667  * Checks to see if the requested type of event should be shown for the given user.
1668  *
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
1673  */
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) {
1677         global $SESSION;
1678         if (!isset($SESSION->calendarshoweventtype)) {
1679             $SESSION->calendarshoweventtype = $default;
1680         }
1681         return $SESSION->calendarshoweventtype & $type;
1682     } else {
1683         return get_user_preferences('calendar_savedflt', $default, $user) & $type;
1684     }
1687 /**
1688  * Sets the display of the event type given $display.
1689  *
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.
1693  *
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
1697  */
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) {
1702         global $SESSION;
1703         if (!isset($SESSION->calendarshoweventtype)) {
1704             $SESSION->calendarshoweventtype = $default;
1705         }
1706         $preference = $SESSION->calendarshoweventtype;
1707     } else {
1708         $preference = get_user_preferences('calendar_savedflt', $default, $user);
1709     }
1710     $current = $preference & $type;
1711     if ($display === null) {
1712         $display = !$current;
1713     }
1714     if ($display && !$current) {
1715         $preference += $type;
1716     } else if (!$display && $current) {
1717         $preference -= $type;
1718     }
1719     if ($persist === 0) {
1720         $SESSION->calendarshoweventtype = $preference;
1721     } else {
1722         if ($preference == $default) {
1723             unset_user_preference('calendar_savedflt', $user);
1724         } else {
1725             set_user_preference('calendar_savedflt', $preference, $user);
1726         }
1727     }
1730 /**
1731  * Get calendar's allowed types
1732  *
1733  * @param stdClass $allowed list of allowed edit for event  type
1734  * @param stdClass|int $course object of a course or course id
1735  */
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);
1747         }
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);
1757                 }
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);
1761                 }
1762             }
1763         }
1764     }
1767 /**
1768  * See if user can add calendar entries at all
1769  * used to print the "New Event" button
1770  *
1771  * @param stdClass $course object of a course or course id
1772  * @return bool has the capability to add at least one event type
1773  */
1774 function calendar_user_can_add_event($course) {
1775     if (!isloggedin() || isguestuser()) {
1776         return false;
1777     }
1778     calendar_get_allowed_types($allowed, $course);
1779     return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
1782 /**
1783  * Check wether the current user is permitted to add events
1784  *
1785  * @param stdClass $event object of event
1786  * @return bool has the capability to add event
1787  */
1788 function calendar_add_event_allowed($event) {
1789     global $USER, $DB;
1791     // can not be using guest account
1792     if (!isloggedin() or isguestuser()) {
1793         return false;
1794     }
1796     $sitecontext = context_system::instance();
1797     // if user has manageentries at site level, always return true
1798     if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1799         return true;
1800     }
1802     switch ($event->eventtype) {
1803         case 'course':
1804             return has_capability('moodle/calendar:manageentries', $event->context);
1806         case 'group':
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));
1811             return $group && (
1812                 has_capability('moodle/calendar:manageentries', $event->context) ||
1813                 (has_capability('moodle/calendar:managegroupentries', $event->context)
1814                     && groups_is_member($event->groupid)));
1816         case 'user':
1817             if ($event->userid == $USER->id) {
1818                 return (has_capability('moodle/calendar:manageownentries', $event->context));
1819             }
1820             //there is no 'break;' intentionally
1822         case 'site':
1823             return has_capability('moodle/calendar:manageentries', $event->context);
1825         default:
1826             return has_capability('moodle/calendar:manageentries', $event->context);
1827     }
1830 /**
1831  * Manage calendar events
1832  *
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
1837  *
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
1842  *
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
1861  */
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;
1867     /**
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(
1873             'subdirs'=>false,
1874             'forcehttps'=>false,
1875             'maxfiles'=>-1,
1876             'maxbytes'=>null,
1877             'trusttext'=>false);
1879     /** @var object The context to use with the description editor */
1880     protected $editorcontext = null;
1882     /**
1883      * Instantiates a new event and optionally populates its properties with the
1884      * data provided
1885      *
1886      * @param stdClass $data Optional. An object containing the properties to for
1887      *                  an event
1888      */
1889     public function __construct($data=null) {
1890         global $CFG, $USER;
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;
1895         }
1897         $this->editoroptions['maxbytes'] = $CFG->maxbytes;
1899         $data->eventrepeats = 0;
1901         if (empty($data->id)) {
1902             $data->id = null;
1903         }
1905         // Default to a user event
1906         if (empty($data->eventtype)) {
1907             $data->eventtype = 'user';
1908         }
1910         // Default to the current user
1911         if (empty($data->userid)) {
1912             $data->userid = $USER->id;
1913         }
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;
1917         }
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();
1924         }
1925         // Ensure form is defaulted correctly
1926         if (empty($data->format)) {
1927             $data->format = editors_get_preferred_format();
1928         }
1930         if (empty($data->context)) {
1931             $data->context = $this->calculate_context($data);
1932         }
1933         $this->properties = $data;
1934     }
1936     /**
1937      * Magic property method
1938      *
1939      * Attempts to call a set_$key method if one exists otherwise falls back
1940      * to simply set the property
1941      *
1942      * @param string $key property name
1943      * @param mixed $value value of the property
1944      */
1945     public function __set($key, $value) {
1946         if (method_exists($this, 'set_'.$key)) {
1947             $this->{'set_'.$key}($value);
1948         }
1949         $this->properties->{$key} = $value;
1950     }
1952     /**
1953      * Magic get method
1954      *
1955      * Attempts to call a get_$key method to return the property and ralls over
1956      * to return the raw property
1957      *
1958      * @param string $key property name
1959      * @return mixed property value
1960      */
1961     public function __get($key) {
1962         if (method_exists($this, 'get_'.$key)) {
1963             return $this->{'get_'.$key}();
1964         }
1965         if (!isset($this->properties->{$key})) {
1966             throw new coding_exception('Undefined property requested');
1967         }
1968         return $this->properties->{$key};
1969     }
1971     /**
1972      * Stupid PHP needs an isset magic method if you use the get magic method and
1973      * still want empty calls to work.... blah ~!
1974      *
1975      * @param string $key $key property name
1976      * @return bool|mixed property value, false if property is not exist
1977      */
1978     public function __isset($key) {
1979         return !empty($this->properties->{$key});
1980     }
1982     /**
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
1986      * the course event.
1987      * Default value is set to CONTEXT_USER
1988      *
1989      * @param stdClass $data information about event
1990      * @return stdClass The context object.
1991      */
1992     protected function calculate_context(stdClass $data) {
1993         global $USER, $DB;
1995         $context = null;
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);
2009         } else {
2010             $context =  context_user::instance($data->userid);
2011         }
2013         return $context;
2014     }
2016     /**
2017      * Returns an array of editoroptions for this event: Called by __get
2018      * Please use $blah = $event->editoroptions;
2019      *
2020      * @return array event editor options
2021      */
2022     protected function get_editoroptions() {
2023         return $this->editoroptions;
2024     }
2026     /**
2027      * Returns an event description: Called by __get
2028      * Please use $blah = $event->description;
2029      *
2030      * @return string event description
2031      */
2032     protected function get_description() {
2033         global $CFG;
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);
2046                 }
2047             }
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;
2053             } else {
2054                 $itemid = $this->properties->id;
2055             }
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);
2061         }
2062         // Finally return the description
2063         return $this->_description;
2064     }
2066     /**
2067      * Return the number of repeat events there are in this events series
2068      *
2069      * @return int number of event repeated
2070      */
2071     public function count_repeats() {
2072         global $DB;
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--;
2077         }
2078         return $this->properties->eventrepeats;
2079     }
2081     /**
2082      * Update or create an event within the database
2083      *
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
2086      *
2087      * @see add_event()
2088      * @see update_event()
2089      *
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
2093      */
2094     public function update($data, $checkcapability=true) {
2095         global $CFG, $DB, $USER;
2097         foreach ($data as $key=>$value) {
2098             $this->properties->$key = $value;
2099         }
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');
2109                 }
2110             }
2112             if ($usingeditor) {
2113                 switch ($this->properties->eventtype) {
2114                     case 'user':
2115                         $this->editorcontext = $this->properties->context;
2116                         $this->properties->courseid = 0;
2117                         $this->properties->groupid = 0;
2118                         $this->properties->userid = $USER->id;
2119                         break;
2120                     case 'site':
2121                         $this->editorcontext = $this->properties->context;
2122                         $this->properties->courseid = SITEID;
2123                         $this->properties->groupid = 0;
2124                         $this->properties->userid = $USER->id;
2125                         break;
2126                     case 'course':
2127                         $this->editorcontext = $this->properties->context;
2128                         $this->properties->groupid = 0;
2129                         $this->properties->userid = $USER->id;
2130                         break;
2131                     case 'group':
2132                         $this->editorcontext = $this->properties->context;
2133                         $this->properties->userid = $USER->id;
2134                         break;
2135                     default:
2136                         // Ewww we should NEVER get here, but just incase we do lets
2137                         // fail gracefully
2138                         $usingeditor = false;
2139                         break;
2140                 }
2142                 $editor = $this->properties->description;
2143                 $this->properties->format = $this->properties->description['format'];
2144                 $this->properties->description = $this->properties->description['text'];
2145             }
2147             // Insert the event into the database
2148             $this->properties->id = $DB->insert_record('event', $this->properties);
2150             if ($usingeditor) {
2151                 $this->properties->description = file_save_draft_area_files(
2152                                                 $editor['itemid'],
2153                                                 $this->editorcontext->id,
2154                                                 'calendar',
2155                                                 'event_description',
2156                                                 $this->properties->id,
2157                                                 $this->editoroptions,
2158                                                 $editor['text'],
2159                                                 $this->editoroptions['forcehttps']);
2161                 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
2162             }
2164             // Log the event entry.
2165             add_to_log($this->properties->courseid, 'calendar', 'add', 'event.php?action=edit&amp;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
2184                     if ($usingeditor) {
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);
2189                         }
2190                     }
2192                     $repeatedids[] = $eventcopyid;
2193                     // Log the event entry.
2194                     add_to_log($eventcopy->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$eventcopyid, $eventcopy->name);
2195                 }
2196             }
2198             // Hook for tracking added events
2199             self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
2200             return true;
2201         } else {
2203             if ($checkcapability) {
2204                 if(!calendar_edit_event_allowed($this->properties)) {
2205                     print_error('nopermissiontoupdatecalendar');
2206                 }
2207             }
2209             if ($usingeditor) {
2210                 if ($this->editorcontext !== null) {
2211                     $this->properties->description = file_save_draft_area_files(
2212                                                     $this->properties->description['itemid'],
2213                                                     $this->editorcontext->id,
2214                                                     'calendar',
2215                                                     'event_description',
2216                                                     $this->properties->id,
2217                                                     $this->editoroptions,
2218                                                     $this->properties->description['text'],
2219                                                     $this->editoroptions['forcehttps']);
2220                 } else {
2221                     $this->properties->format = $this->properties->description['format'];
2222                     $this->properties->description = $this->properties->description['text'];
2223                 }
2224             }
2226             $event = $DB->get_record('event', array('id'=>$this->properties->id));
2228             $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
2230             if ($updaterepeated) {
2231                 // Update all
2232                 if ($this->properties->timestart != $event->timestart) {
2233                     $timestartoffset = $this->properties->timestart - $event->timestart;
2234                     $sql = "UPDATE {event}
2235                                SET name = ?,
2236                                    description = ?,
2237                                    timestart = timestart + ?,
2238                                    timeduration = ?,
2239                                    timemodified = ?
2240                              WHERE repeatid = ?";
2241                     $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
2242                 } else {
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);
2245                 }
2246                 $DB->execute($sql, $params);
2248                 // Log the event update.
2249                 add_to_log($this->properties->courseid, 'calendar', 'edit all', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2250             } else {
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&amp;id='.$this->properties->id, $this->properties->name);
2255             }
2257             // Hook for tracking event updates
2258             self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
2259             return true;
2260         }
2261     }
2263     /**
2264      * Deletes an event and if selected an repeated events in the same series
2265      *
2266      * This function deletes an event, any associated events if $deleterepeated=true,
2267      * and cleans up any files associated with the events.
2268      *
2269      * @see delete_event()
2270      *
2271      * @param bool $deleterepeated  delete event repeatedly
2272      * @return bool succession of deleting event
2273      */
2274     public function delete($deleterepeated=false) {
2275         global $DB;
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);
2280             return false;
2281         }
2283         // Delete the event
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));
2296                 }
2297             }
2298         }
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;
2303         }
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) {
2310                 $file->delete();
2311             }
2312         }
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);
2326             }
2327         }
2329         return true;
2330     }
2332     /**
2333      * Fetch all event properties
2334      *
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.
2339      *
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
2343      */
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') {
2363                     // Site context
2364                     $this->editorcontext = $this->properties->context;
2365                 } else if ($properties->eventtype === 'user') {
2366                     // User context
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));
2371                     if (!$course) {
2372                         print_error('invalidcourse');
2373                     }
2374                     // Course context
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;
2379                 } else {
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;
2385                 }
2387                 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2388                     $contextid = false;
2389                 } else {
2390                     // Get the context id that is what we really want
2391                     $contextid = $this->editorcontext->id;
2392                 }
2393             } else {
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.
2397                 $contextid = null;
2398             }
2400             // If the contextid === false we don't support files so no preparing
2401             // a draft area
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);
2407             } else {
2408                 $draftiddescription = 0;
2409             }
2411             // Structure the description field as the editor requires
2412             $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2413         }
2415         // Finally return the properties
2416         return $properties;
2417     }
2419     /**
2420      * Toggles the visibility of an event
2421      *
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
2424      *                   is made visible.
2425      * @return bool if event is successfully updated, toggle will be visible
2426      */
2427     public function toggle_visibility($force=null) {
2428         global $CFG, $DB;
2430         // Set visible to the default if it is not already set
2431         if (empty($this->properties->visible)) {
2432             $this->properties->visible = 1;
2433         }
2435         if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2436             // Make this event visible
2437             $this->properties->visible = 1;
2438             // Fire the hook
2439             self::calendar_event_hook('show_event', array($this->properties));
2440         } else {
2441             // Make this event hidden
2442             $this->properties->visible = 0;
2443             // Fire the hook
2444             self::calendar_event_hook('hide_event', array($this->properties));
2445         }
2447         // Update the database to reflect this change
2448         return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2449     }
2451     /**
2452      * Attempts to call the hook for the specified action should a calendar type
2453      * by set $CFG->calendar, and the appopriate function defined
2454      *
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
2458      */
2459     public static function calendar_event_hook($action, array $args) {
2460         global $CFG;
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;
2467                 } else {
2468                     debugging("Calendar lib file missing or not readable at /calendar/{$CFG->calendar}/lib.php.",
2469                         DEBUG_DEVELOPER);
2470                     $extcalendarinc = false;
2471                 }
2472             } else {
2473                 $extcalendarinc = false;
2474             }
2475         }
2476         if($extcalendarinc === false) {
2477             return false;
2478         }
2479         $hook = $CFG->calendar .'_'.$action;
2480         if (function_exists($hook)) {
2481             call_user_func_array($hook, $args);
2482             return true;
2483         }
2484         return false;
2485     }
2487     /**
2488      * Returns a calendar_event object when provided with an event id
2489      *
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
2492      *
2493      * @param int|object $param event object or event id
2494      * @return calendar_event|false status for loading calendar_event
2495      */
2496     public static function load($param) {
2497         global $DB;
2498         if (is_object($param)) {
2499             $event = new calendar_event($param);
2500         } else {
2501             $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2502             $event = new calendar_event($event);
2503         }
2504         return $event;
2505     }
2507     /**
2508      * Creates a new event and returns a calendar_event object
2509      *
2510      * @param object|array $properties An object containing event properties
2511      * @return calendar_event|false The event object or false if it failed
2512      */
2513     public static function create($properties) {
2514         if (is_array($properties)) {
2515             $properties = (object)$properties;
2516         }
2517         if (!is_object($properties)) {
2518             throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2519         }
2520         $event = new calendar_event($properties);
2521         if ($event->update($properties)) {
2522             return $event;
2523         } else {
2524             return false;
2525         }
2526     }
2529 /**
2530  * Calendar information class
2531  *
2532  * This class is used simply to organise the information pertaining to a calendar
2533  * and is used primarily to make information easily available.
2534  *
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
2539  */
2540 class calendar_information {
2541     /** @var int The day */
2542     public $day;
2544     /** @var int The month */
2545     public $month;
2547     /** @var int The year */
2548     public $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();
2562     /**
2563      * Creates a new instance
2564      *
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
2568      */
2569     public function __construct($day=0, $month=0, $year=0) {
2571         $date = usergetdate(time());
2573         if (empty($day)) {
2574             $day = $date['mday'];
2575         }
2577         if (empty($month)) {
2578             $month = $date['mon'];
2579         }
2581         if (empty($year)) {
2582             $year =  $date['year'];
2583         }
2585         $this->day = $day;
2586         $this->month = $month;
2587         $this->year = $year;
2588     }
2590     /**
2591      * Initialize calendar information
2592      *
2593      * @param stdClass $course object
2594      * @param array $coursestoload An array of courses [$course->id => $course]
2595      * @param bool $ignorefilters options to use filter
2596      */
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;
2604     }
2606     /**
2607      * Ensures the date for the calendar is correct and either sets it to now
2608      * or throws a moodle_exception if not
2609      *
2610      * @param bool $defaultonow use current time
2611      * @throws moodle_exception
2612      * @return bool validation of checkdate
2613      */
2614     public function checkdate($defaultonow = true) {
2615         if (!checkdate($this->month, $this->day, $this->year)) {
2616             if ($defaultonow) {
2617                 $now = usergetdate(time());
2618                 $this->day = intval($now['mday']);
2619                 $this->month = intval($now['mon']);
2620                 $this->year = intval($now['year']);
2621                 return true;
2622             } else {
2623                 throw new moodle_exception('invaliddate');
2624             }
2625         }
2626         return true;
2627     }
2628     /**
2629      * Gets todays timestamp for the calendar
2630      *
2631      * @return int today timestamp
2632      */
2633     public function timestamp_today() {
2634         return make_timestamp($this->year, $this->month, $this->day);
2635     }
2636     /**
2637      * Gets tomorrows timestamp for the calendar
2638      *
2639      * @return int tomorrow timestamp
2640      */
2641     public function timestamp_tomorrow() {
2642         return make_timestamp($this->year, $this->month, $this->day+1);
2643     }
2644     /**
2645      * Adds the pretend blocks for the calendar
2646      *
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)
2650      */
2651     public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
2652         if ($showfilters) {
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);
2658         }
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);
2664     }
2667 /**
2668  * Returns option list for the poll interval setting.
2669  *
2670  * @return array An array of poll interval options. Interval => description.
2671  */
2672 function calendar_get_pollinterval_choices() {
2673     return array(
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')
2680     );
2683 /**
2684  * Returns option list of available options for the calendar event type, given the current user and course.
2685  *
2686  * @param int $courseid The id of the course
2687  * @return array An array containing the event types the user can create.
2688  */
2689 function calendar_get_eventtype_choices($courseid) {
2690     $choices = array();
2691     $allowed = new stdClass;
2692     calendar_get_allowed_types($allowed, $courseid);
2694     if ($allowed->user) {
2695         $choices[0] = get_string('userevents', 'calendar');
2696     }
2697     if ($allowed->site) {
2698         $choices[SITEID] = get_string('siteevents', 'calendar');
2699     }
2700     if (!empty($allowed->courses)) {
2701         $choices[$courseid] = get_string('courseevents', 'calendar');
2702     }
2703     if (!empty($allowed->groups) and is_array($allowed->groups)) {
2704         $choices['group'] = get_string('group');
2705     }
2707     return array($choices, $allowed->groups);
2710 /**
2711  * Add an iCalendar subscription to the database.
2712  *
2713  * @param stdClass $sub The subscription object (e.g. from the form)
2714  * @return int The insert ID, if any.
2715  */
2716 function calendar_add_subscription($sub) {
2717     global $DB, $USER;
2719     $sub->courseid = $sub->eventtype;
2720     if ($sub->eventtype == 'group') {
2721         $sub->courseid = $sub->course;
2722     }
2723     $sub->userid = $USER->id;
2725     // File subscriptions never update.
2726     if (empty($sub->url)) {
2727         $sub->pollinterval = 0;
2728     }
2730     if (!empty($sub->name)) {
2731         if (empty($sub->id)) {
2732             $id = $DB->insert_record('event_subscriptions', $sub);
2733             return $id;
2734         } else {
2735             $DB->update_record('event_subscriptions', $sub);
2736             return $sub->id;
2737         }
2738     } else {
2739         print_error('errorbadsubscription', 'importcalendar');
2740     }
2743 /**
2744  * Add an iCalendar event to the Moodle calendar.
2745  *
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
2750  */
2751 function calendar_add_icalendar_event($event, $courseid, $subscriptionid = null) {
2752     global $DB, $USER;
2754     // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2755     if (empty($event->properties['SUMMARY'])) {
2756         return 0;
2757     }
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)) {
2768         $description = '';
2769     } else {
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);
2774     }
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)) {
2779         return 0;
2780     }
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
2785     } else {
2786         $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value) - $eventrecord->timestart;
2787     }
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;
2797     } else {
2798         $eventrecord->userid = $USER->id;
2799         $eventrecord->groupid = 0; // TODO: ???
2800         $eventrecord->courseid = $courseid;
2801     }
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;
2807         } else {
2808             return 0;
2809         }
2810     } else {
2811         if ($DB->insert_record('event', $eventrecord)) {
2812             return CALENDAR_IMPORT_EVENT_INSERTED;
2813         } else {
2814             return 0;
2815         }
2816     }
2819 /**
2820  * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2821  *
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
2826  */
2827 function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
2828     global $DB;
2830     if (empty($subscriptionid)) {
2831         return '';
2832     }
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.
2840     switch ($action) {
2841         case $strupdate:
2842             // Skip updating file subscriptions.
2843             if (empty($sub->url)) {
2844                 break;
2845             }
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);
2852         case $strremove:
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);
2856             break;
2858         default:
2859             break;
2860     }
2861     return '';
2864 /**
2865  * From a URL, fetch the calendar and return an iCalendar object.
2866  *
2867  * @param string $url The iCalendar URL
2868  * @return stdClass The iCalendar object
2869  */
2870 function calendar_get_icalendar($url) {
2871     global $CFG;
2873     require_once($CFG->libdir.'/filelib.php');
2875     $curl = new curl();
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');
2881     }
2883     $ical = new iCalendar();
2884     $ical->unserialize($calendar);
2885     return $ical;
2888 /**
2889  * Import events from an iCalendar object into a course calendar.
2890  *
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.
2895  */
2896 function calendar_import_icalendar_events($ical, $courseid, $subscriptionid = null) {
2897     global $DB;
2898     $return = '';
2899     $eventcount = 0;
2900     $updatecount = 0;
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));
2909     }
2910     foreach ($ical->components['VEVENT'] as $event) {
2911         $res = calendar_add_icalendar_event($event, $courseid, $subscriptionid);
2912         switch ($res) {
2913           case CALENDAR_IMPORT_EVENT_UPDATED:
2914             $updatecount++;
2915             break;
2916           case CALENDAR_IMPORT_EVENT_INSERTED:
2917             $eventcount++;
2918             break;
2919           case 0:
2920             $return .= '<p>'.get_string('erroraddingevent', 'calendar').': '.(empty($event->properties['SUMMARY'])?'('.get_string('notitle', 'calendar').')':$event->properties['SUMMARY'][0]->value)." </p>\n";
2921             break;
2922         }
2923     }
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";
2934         }
2935     }
2937     return $return;
2940 /**
2941  * Fetch a calendar subscription and update the events in the calendar.
2942  *
2943  * @param int $subscriptionid The course ID for the calendar.
2944  * @return string A log of the import progress, including errors.
2945  */
2946 function calendar_update_subscription_events($subscriptionid) {
2947     global $DB;
2949     $sub = $DB->get_record('event_subscriptions', array('id' => $subscriptionid));
2950     if (empty($sub)) {
2951         print_error('errorbadsubscription', 'calendar');
2952     }
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.';
2956     }
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);
2961     return $return;
2964 /**
2965  * Update calendar subscriptions.
2966  *
2967  * @return bool
2968  */
2969 function calendar_cron() {
2970     global $CFG, $DB;
2972     // In order to execute this we need bennu.
2973     require_once($CFG->libdir.'/bennu/bennu.inc.php');
2975     mtrace('Updating calendar subscriptions:');
2977     $time = time();
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}");
2981         try {
2982             $log = calendar_update_subscription_events($sub->id);
2983         } catch (moodle_exception $ex) {
2985         }
2986         mtrace(trim(strip_tags($log)));
2987     }
2989     mtrace('Finished updating calendar subscriptions.');
2991     return true;