3 /////////////////////////////////////////////////////////////////////////////
5 // NOTICE OF COPYRIGHT //
7 // Moodle - Calendar extension //
9 // Copyright (C) 2003-2004 Greek School Network www.sch.gr //
12 // Avgoustos Tsinakos (tsinakos@teikav.edu.gr) //
13 // Jon Papaioannou (pj@moodle.org) //
15 // Programming and development: //
16 // Jon Papaioannou (pj@moodle.org) //
18 // For bugs, suggestions, etc contact: //
19 // Jon Papaioannou (pj@moodle.org) //
21 // The current module was developed at the University of Macedonia //
22 // (www.uom.gr) under the funding of the Greek School Network (www.sch.gr) //
23 // The aim of this project is to provide additional and improved //
24 // functionality to the Asynchronous Distance Education service that the //
25 // Greek School Network deploys. //
27 // This program is free software; you can redistribute it and/or modify //
28 // it under the terms of the GNU General Public License as published by //
29 // the Free Software Foundation; either version 2 of the License, or //
30 // (at your option) any later version. //
32 // This program is distributed in the hope that it will be useful, //
33 // but WITHOUT ANY WARRANTY; without even the implied warranty of //
34 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the //
35 // GNU General Public License for more details: //
37 // http://www.gnu.org/copyleft/gpl.html //
39 /////////////////////////////////////////////////////////////////////////////
41 // These are read by the administration component to provide default values
42 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
43 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
44 define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
45 // This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
46 // Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
47 define('CALENDAR_DEFAULT_WEEKEND', 65);
48 define('CALENDAR_UPCOMING_DAYS', isset($CFG->calendar_lookahead) ? intval($CFG->calendar_lookahead) : CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD);
49 define('CALENDAR_UPCOMING_MAXEVENTS', isset($CFG->calendar_maxevents) ? intval($CFG->calendar_maxevents) : CALENDAR_DEFAULT_UPCOMING_MAXEVENTS);
50 define('CALENDAR_WEEKEND', isset($CFG->calendar_weekend) ? intval($CFG->calendar_weekend) : CALENDAR_DEFAULT_WEEKEND);
51 define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
52 define('CALENDAR_TF_24', '%H:%M');
53 define('CALENDAR_TF_12', '%I:%M %p');
56 * CALENDAR_STARTING_WEEKDAY has since been deprecated please call calendar_get_starting_weekday() instead
59 define('CALENDAR_STARTING_WEEKDAY', CALENDAR_DEFAULT_STARTING_WEEKDAY);
61 $CALENDARDAYS = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
64 * Gets the first day of the week
66 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
70 function calendar_get_starting_weekday() {
73 if (isset($CFG->calendar_startwday)) {
74 $firstday = $CFG->calendar_startwday;
76 $firstday = get_string('firstdayofweek', 'langconfig');
79 if(!is_numeric($firstday)) {
80 return CALENDAR_DEFAULT_STARTING_WEEKDAY;
82 return intval($firstday) % 7;
86 function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
87 global $CFG, $USER, $OUTPUT;
89 $display = new stdClass;
90 $display->minwday = get_user_preferences('calendar_startwday', calendar_get_starting_weekday());
91 $display->maxwday = $display->minwday + 6;
95 if(!empty($cal_month) && !empty($cal_year)) {
96 $thisdate = usergetdate(time()); // Date and time the user sees at his location
97 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
98 // Navigated to this month
100 $display->thismonth = true;
103 // Navigated to other month, let's do a nice trick and save us a lot of work...
104 if(!checkdate($cal_month, 1, $cal_year)) {
105 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
106 $display->thismonth = true;
109 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
110 $display->thismonth = false;
115 $date = usergetdate(time()); // Date and time the user sees at his location
116 $display->thismonth = true;
119 // Fill in the variables we 're going to use, nice and tidy
120 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
121 $display->maxdays = calendar_days_in_month($m, $y);
123 if (get_user_timezone_offset() < 99) {
124 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
125 $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
126 $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
128 // no timezone info specified
129 $display->tstart = mktime(0, 0, 0, $m, 1, $y);
130 $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y);
133 $startwday = dayofweek(1, $m, $y);
135 // Align the starting weekday to fall in our display range
136 // This is simple, not foolproof.
137 if($startwday < $display->minwday) {
141 // TODO: THIS IS TEMPORARY CODE!
142 // [pj] I was just reading through this and realized that I when writing this code I was probably
143 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
144 // make_timestamp would accomplish the same thing. So here goes a test:
145 //$test_start = make_timestamp($y, $m, 1);
146 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
147 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
148 //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);
150 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
151 //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);
155 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
156 $events = calendar_get_events(
157 usertime($display->tstart) - dst_offset_on($display->tstart),
158 usertime($display->tend) - dst_offset_on($display->tend),
159 $users, $groups, $courses);
161 // Set event course class for course events
162 if (!empty($events)) {
163 foreach ($events as $eventid => $event) {
164 if (!empty($event->modulename)) {
165 $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
166 if (!groups_course_module_visible($cm)) {
167 unset($events[$eventid]);
173 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
174 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
175 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
176 // arguments to this function.
179 if(!empty($courses)) {
180 $courses = array_diff($courses, array(SITEID));
181 if(count($courses) == 1) {
182 $morehref = '&course='.reset($courses);
186 // We want to have easy access by day, since the display is on a per-day basis.
187 // Arguments passed by reference.
188 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
189 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
191 //Accessibility: added summary and <abbr> elements.
192 ///global $CALENDARDAYS; appears to be broken.
193 $days_title = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
195 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
196 $summary = get_string('tabledata', 'access', $summary);
197 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table
198 $content .= '<tr class="weekdays">'; // Header row: day names
200 // Print out the names of the weekdays
201 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
202 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
203 // This uses the % operator to get the correct weekday no matter what shift we have
204 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
205 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
206 get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
209 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
211 // For the table display. $week is the row; $dayweek is the column.
212 $dayweek = $startwday;
214 // Paddding (the first week may have blank days in the beginning)
215 for($i = $display->minwday; $i < $startwday; ++$i) {
216 $content .= '<td class="dayblank"> </td>'."\n";
219 // Now display all the calendar
220 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
221 if($dayweek > $display->maxwday) {
222 // We need to change week (table row)
223 $content .= '</tr><tr>';
224 $dayweek = $display->minwday;
229 if(CALENDAR_WEEKEND & (1 << ($dayweek % 7))) {
230 // Weekend. This is true no matter what the exact range is.
231 $class = 'weekend day';
233 // Normal working day.
237 // Special visual fx if an event is defined
238 if(isset($eventsbyday[$day])) {
239 $class .= ' hasevent';
240 $dayhref = calendar_get_link_href(CALENDAR_URL.'view.php?view=day'.$morehref.'&', $day, $m, $y);
244 foreach($eventsbyday[$day] as $eventid) {
245 if (!isset($events[$eventid])) {
248 $event = $events[$eventid];
249 if(!empty($event->modulename)) {
250 $popupicon = $OUTPUT->pix_url('icon', $event->modulename) . '';
251 $popupalt = $event->modulename;
253 } else if ($event->courseid == SITEID) { // Site event
254 $popupicon = $OUTPUT->pix_url('c/site');
256 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
257 $popupicon = $OUTPUT->pix_url('c/course');
259 } else if ($event->groupid) { // Group event
260 $popupicon = $OUTPUT->pix_url('c/group');
262 } else if ($event->userid) { // User event
263 $popupicon = $OUTPUT->pix_url('c/user');
266 $popupcontent .= '<div><img class="icon" src="'.$popupicon.'" alt="'.$popupalt.'" /><a href="'.$dayhref.'#event_'.$event->id.'">'.format_string($event->name, true).'</a></div>';
269 //Accessibility: functionality moved to calendar_get_popup.
270 if($display->thismonth && $day == $d) {
271 $popup = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
273 $popup = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
276 // Class and cell content
277 if(isset($typesbyday[$day]['startglobal'])) {
278 $class .= ' calendar_event_global';
279 } else if(isset($typesbyday[$day]['startcourse'])) {
280 $class .= ' calendar_event_course';
281 } else if(isset($typesbyday[$day]['startgroup'])) {
282 $class .= ' calendar_event_group';
283 } else if(isset($typesbyday[$day]['startuser'])) {
284 $class .= ' calendar_event_user';
286 $cell = '<a href="'.$dayhref.'" '.$popup.'>'.$day.'</a>';
291 $durationclass = false;
292 if (isset($typesbyday[$day]['durationglobal'])) {
293 $durationclass = ' duration_global';
294 } else if(isset($typesbyday[$day]['durationcourse'])) {
295 $durationclass = ' duration_course';
296 } else if(isset($typesbyday[$day]['durationgroup'])) {
297 $durationclass = ' duration_group';
298 } else if(isset($typesbyday[$day]['durationuser'])) {
299 $durationclass = ' duration_user';
301 if ($durationclass) {
302 $class .= ' duration '.$durationclass;
305 // If event has a class set then add it to the table day <td> tag
306 // Note: only one colour for minicalendar
307 if(isset($eventsbyday[$day])) {
308 foreach($eventsbyday[$day] as $eventid) {
309 if (!isset($events[$eventid])) {
312 $event = $events[$eventid];
313 if (!empty($event->class)) {
314 $class .= ' '.$event->class;
320 // Special visual fx for today
321 //Accessibility: hidden text for today, and popup.
322 if($display->thismonth && $day == $d) {
324 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
326 if(! isset($eventsbyday[$day])) {
327 $class .= ' eventnone';
328 $popup = calendar_get_popup(true, false);
329 $cell = '<a href="#" '.$popup.'>'.$day.'</a>';
331 $cell = get_accesshide($today.' ').$cell;
336 $class = ' class="'.$class.'"';
338 $content .= '<td'.$class.'>'.$cell."</td>\n";
341 // Paddding (the last week may have blank days at the end)
342 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
343 $content .= '<td class="dayblank"> </td>';
345 $content .= '</tr>'; // Last row ends
347 $content .= '</table>'; // Tabular display of days ends
353 * calendar_get_popup, called at multiple points in from calendar_get_mini.
354 * Copied and modified from calendar_get_mini.
355 * @uses OverLib popup.
356 * @param $is_today bool, false except when called on the current day.
357 * @param $event_timestart mixed, $events[$eventid]->timestart, OR false if there are no events.
358 * @param $popupcontent string.
359 * @return $popup string, contains onmousover and onmouseout events.
361 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
364 if ($popupcount === null) {
369 $popupcaption = get_string('today', 'calendar').' ';
371 if (false === $event_timestart) {
372 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
373 $popupcontent = get_string('eventnone', 'calendar');
376 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
378 $id = 'calendar_tooltip_'.$popupcount;
379 $PAGE->requires->js_init_call("M.core_calendar.init", array(array('id'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
382 return 'id="'.$id.'"';
385 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
386 global $CFG, $COURSE, $DB;
388 $display = new stdClass;
389 $display->range = $daysinfuture; // How many days in the future we 'll look
390 $display->maxevents = $maxevents;
394 // Prepare "course caching", since it may save us a lot of queries
395 $coursecache = array();
398 $now = time(); // We 'll need this later
399 $usermidnighttoday = usergetmidnight($now);
402 $display->tstart = $fromtime;
404 $display->tstart = $usermidnighttoday;
407 // This works correctly with respect to the user's DST, but it is accurate
408 // only because $fromtime is always the exact midnight of some day!
409 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
411 // Get the events matching our criteria
412 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
414 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
415 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
416 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
417 // arguments to this function.
420 if(!empty($courses)) {
421 $courses = array_diff($courses, array(SITEID));
422 if(count($courses) == 1) {
423 $morehref = '&course='.reset($courses);
427 if ($events !== false) {
429 $modinfo =& get_fast_modinfo($COURSE);
431 foreach($events as $event) {
434 if (!empty($event->modulename)) {
435 if ($event->courseid == $COURSE->id) {
436 if (isset($modinfo->instances[$event->modulename][$event->instance])) {
437 $cm = $modinfo->instances[$event->modulename][$event->instance];
438 if (!$cm->uservisible) {
443 if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
446 if (!coursemodule_visible_for_user($cm)) {
450 if ($event->modulename == 'assignment'){
451 // TODO: rewrite this hack somehow
452 if (!calendar_edit_event_allowed($event)){ // cannot manage entries, eg. student
453 if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance))) {
454 // print_error("invalidid", 'assignment');
457 // assign assignment to assignment object to use hidden_is_hidden method
458 require_once($CFG->dirroot.'/mod/assignment/lib.php');
460 if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php')) {
463 require_once ($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
465 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
466 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm);
468 if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
469 $event->description = get_string('notavailableyet', 'assignment');
475 if ($processed >= $display->maxevents) {
479 $event->time = calendar_format_event_time($event, $now, $morehref);
487 function calendar_add_event_metadata($event) {
488 global $CFG, $OUTPUT;
490 //Support multilang in event->name
491 $event->name = format_string($event->name,true);
493 if(!empty($event->modulename)) { // Activity event
494 // The module name is set. I will assume that it has to be displayed, and
495 // also that it is an automatically-generated event. And of course that the
496 // fields for get_coursemodule_from_instance are set correctly.
497 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
499 if ($module === false) {
503 $modulename = get_string('modulename', $event->modulename);
504 $eventtype = get_string($event->eventtype, $event->modulename);
505 $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
507 $event->icon = '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
508 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
509 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$coursecache[$module->course]->fullname.'</a>';
510 $event->cmid = $module->id;
513 } else if($event->courseid == SITEID) { // Site event
514 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/site') . '" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
515 $event->cssclass = 'calendar_event_global';
516 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
517 calendar_get_course_cached($coursecache, $event->courseid);
518 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/course') . '" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
519 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$coursecache[$event->courseid]->fullname.'</a>';
520 $event->cssclass = 'calendar_event_course';
521 } else if ($event->groupid) { // Group event
522 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/group') . '" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
523 $event->cssclass = 'calendar_event_group';
524 } else if($event->userid) { // User event
525 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/user') . '" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
526 $event->cssclass = 'calendar_event_user';
531 function calendar_print_event($event, $showactions=true) {
532 global $CFG, $USER, $OUTPUT;
534 static $strftimetime;
536 $event = calendar_add_event_metadata($event);
537 if (!($event instanceof calendar_event)) {
538 $event = new calendar_event($event);
540 echo '<a name="event_'.$event->id.'"></a><table class="event" cellspacing="0">';
541 echo '<tr><td class="picture">';
542 if (!empty($event->icon)) {
545 echo $OUTPUT->spacer(array('height'=>16, 'width'=>16, 'br'=>true)); // should be done with CSS instead
548 echo '<td class="topic">';
550 if (!empty($event->referer)) {
551 echo '<div class="referer">'.$event->referer.'</div>';
553 echo '<div class="name">'.$event->name."</div>";
555 if (!empty($event->courselink)) {
556 echo '<div class="course">'.$event->courselink.' </div>';
558 if (!empty($event->time)) {
559 echo '<span class="date">'.$event->time.'</span>';
561 echo '<span class="date">'.calendar_time_representation($event->timestart).'</span>';
565 echo '<tr><td class="side"> </td>';
566 if (isset($event->cssclass)) {
567 echo '<td class="description '.$event->cssclass.'">';
569 echo '<td class="description">';
572 echo $event->description;
573 if (calendar_edit_event_allowed($event) && $showactions) {
574 echo '<div class="commands">';
575 $calendarcourseid = '';
576 if (!empty($event->calendarcourseid)) {
577 $calendarcourseid = '&course='.$event->calendarcourseid;
579 if (empty($event->cmid)) {
580 $editlink = CALENDAR_URL.'event.php?action=edit&id='.$event->id.$calendarcourseid;
581 $deletelink = CALENDAR_URL.'delete.php?id='.$event->id.$calendarcourseid;
583 $editlink = $CFG->wwwroot.'/course/mod.php?update='.$event->cmid.'&return=true&sesskey='.sesskey();
584 $deletelink = ''; // deleting activities directly from calendar is dangerous/confusing - see MDL-11843
586 echo ' <a href="'.$editlink.'"><img
587 src="'.$OUTPUT->pix_url('t/edit') . '" alt="'.get_string('tt_editevent', 'calendar').'"
588 title="'.get_string('tt_editevent', 'calendar').'" /></a>';
590 echo ' <a href="'.$deletelink.'"><img
591 src="'.$OUTPUT->pix_url('t/delete') . '" alt="'.get_string('tt_deleteevent', 'calendar').'"
592 title="'.get_string('tt_deleteevent', 'calendar').'" /></a>';
596 echo '</td></tr></table>';
601 * Get calendar events
602 * @param int $tstart Start time of time range for events
603 * @param int $tend End time of time range for events
604 * @param array/int/boolean $users array of users, user id or boolean for all/no user events
605 * @param array/int/boolean $groups array of groups, group id or boolean for all/no group events
606 * @param array/int/boolean $courses array of courses, course id or boolean for all/no course events
607 * @param boolean $withduration whether only events starting within time range selected
608 * or events in progress/already started selected as well
609 * @param boolean $ignorehidden whether to select only visible events or all events
610 * @return array of selected events or an empty array if there aren't any (or there was an error)
612 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
617 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
621 if(is_array($users) && !empty($users)) {
622 // Events from a number of users
623 if(!empty($whereclause)) $whereclause .= ' OR';
624 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
626 else if(is_numeric($users)) {
627 // Events from one user
628 if(!empty($whereclause)) $whereclause .= ' OR';
629 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
631 else if($users === true) {
632 // Events from ALL users
633 if(!empty($whereclause)) $whereclause .= ' OR';
634 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
636 else if($users === false) {
637 // No user at all, do nothing
640 if(is_array($groups) && !empty($groups)) {
641 // Events from a number of groups
642 if(!empty($whereclause)) $whereclause .= ' OR';
643 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
645 else if(is_numeric($groups)) {
646 // Events from one group
647 if(!empty($whereclause)) $whereclause .= ' OR ';
648 $whereclause .= ' groupid = '.$groups;
650 else if($groups === true) {
651 // Events from ALL groups
652 if(!empty($whereclause)) $whereclause .= ' OR ';
653 $whereclause .= ' groupid != 0';
655 // boolean false (no groups at all): we don't need to do anything
657 if(is_array($courses)) {
658 // A number of courses (maybe none at all!)
659 if(!empty($courses)) {
660 if(!empty($whereclause)) {
661 $whereclause .= ' OR';
663 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
666 // This means NO courses, not that we don't care!
667 // No need to do anything
670 else if(is_numeric($courses)) {
672 if(!empty($whereclause)) $whereclause .= ' OR';
673 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
675 else if($courses === true) {
676 // Events from ALL courses
677 if(!empty($whereclause)) $whereclause .= ' OR';
678 $whereclause .= ' (groupid = 0 AND courseid != 0)';
681 // Security check: if, by now, we have NOTHING in $whereclause, then it means
682 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
683 // events no matter what. Allowing the code to proceed might return a completely
684 // valid query with only time constraints, thus selecting ALL events in that time frame!
685 if(empty($whereclause)) {
690 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
693 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
695 if(!empty($whereclause)) {
696 // We have additional constraints
697 $whereclause = $timeclause.' AND ('.$whereclause.')';
700 // Just basic time filtering
701 $whereclause = $timeclause;
705 $whereclause .= ' AND visible = 1';
708 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
709 if ($events === false) {
715 function calendar_top_controls($type, $data) {
716 global $CFG, $CALENDARDAYS;
718 if(!isset($data['d'])) {
722 // Ensure course id passed if relevant
723 // Required due to changes in view/lib.php mainly (calendar_session_vars())
725 if (!empty($data['id'])) {
726 $courseid = '&course='.$data['id'];
729 if(!checkdate($data['m'], $data['d'], $data['y'])) {
733 $time = make_timestamp($data['y'], $data['m'], $data['d']);
735 $date = usergetdate($time);
737 $data['m'] = $date['mon'];
738 $data['y'] = $date['year'];
740 //Accessibility: calendar block controls, replaced <table> with <div>.
741 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
742 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
746 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
747 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
748 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
749 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
750 $content .= "\n".'<div class="calendar-controls">'. $prevlink;
751 $content .= '<span class="hide"> | </span><span class="current"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month'.$courseid.'&', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear')).'</a></span>';
752 $content .= '<span class="hide"> | </span>'. $nextlink ."\n";
753 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
756 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
757 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
758 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&', 0, $nextmonth, $nextyear, $accesshide=true);
759 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&', 0, $prevmonth, $prevyear, true);
760 $content .= "\n".'<div class="calendar-controls">'. $prevlink;
761 $content .= '<span class="hide"> | </span><span class="current"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month'.$courseid.'&', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear')).'</a></span>';
762 $content .= '<span class="hide"> | </span>'. $nextlink ."\n";
763 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
766 $content .= '<div style="text-align: center;"><a href="'.CALENDAR_URL.'view.php?view=upcoming"'.$courseid.'>'.userdate($time, get_string('strftimemonthyear'))."</a></div>\n";
769 $content .= '<h3><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month'.$courseid.'&', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear'))."</a></h3>\n";
772 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
773 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
774 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
775 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
776 $content .= "\n".'<div class="calendar-controls">';
777 $content .= calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&', 1, $prevmonth, $prevyear);
778 $content .= '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>\n";
779 $content .= '<span class="hide"> | </span>'.calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&', 1, $nextmonth, $nextyear);
780 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
783 $data['d'] = $date['mday']; // Just for convenience
784 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
785 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
786 $prevname = calendar_wday_name($CALENDARDAYS[$prevdate['wday']]);
787 $nextname = calendar_wday_name($CALENDARDAYS[$nextdate['wday']]);
788 $content .= "\n".'<div class="calendar-controls">';
789 $content .= calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
791 // Get the format string
792 $text = get_string('strftimedaydate');
794 // Regexp hackery to make a link out of the month/year part
795 $text = preg_replace('/(%B.+%Y|%Y.+%B|%Y.+%m[^ ]+)/', '<a href="'.calendar_get_link_href('view.php?view=month&', 1, $data['m'], $data['y']).'">\\1</a>', $text);
796 $text = preg_replace('/(F.+Y|Y.+F|Y.+m[^ ]+)/', '<a href="'.calendar_get_link_href('view.php?view=month&', 1, $data['m'], $data['y']).'">\\1</a>', $text);
798 // Replace with actual values and lose any day leading zero
799 $text = userdate($time, $text);
800 // Print the actual thing
801 $content .= '<span class="hide"> | </span><span class="current">'.$text.'</span>';
803 $content .= '<span class="hide"> | </span>'. calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
804 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
810 function calendar_filter_controls($type, $vars = NULL, $course = NULL, $courses = NULL) {
811 global $CFG, $SESSION, $USER, $OUTPUT;
816 $id = optional_param( 'id',0,PARAM_INT );
823 $getvars = '&from='.$type;
827 $getvars = '&from=course&id='.$id;
829 $getvars = '&from=course';
831 if (isset($course->groupmode) and $course->groupmode == NOGROUPS and $course->groupmodeforce) {
832 $groupevents = false;
838 $getvars .= '&'.$vars;
841 $content = '<table>';
844 if($SESSION->cal_show_global) {
845 $content .= '<td class="eventskey calendar_event_global" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showglobal'.$getvars."'".'" /></td>';
846 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
848 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showglobal'.$getvars."'".'" /></td>';
849 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
851 if($SESSION->cal_show_course) {
852 $content .= '<td class="eventskey calendar_event_course" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidecourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showcourses'.$getvars."'".'" /></td>';
853 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
855 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_showcourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showcourses'.$getvars."'".'" /></td>';
856 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
861 if (isloggedin() && !isguestuser()) {
862 $content .= "</tr>\n<tr>";
865 // This course MIGHT have group events defined, so show the filter
866 if($SESSION->cal_show_groups) {
867 $content .= '<td class="eventskey calendar_event_group" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidegroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showgroups'.$getvars."'".'" /></td>';
868 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
870 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showgroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showgroups'.$getvars."'".'" /></td>';
871 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
874 // This course CANNOT have group events, so lose the filter
875 $content .= '<td style="width: 11px;"></td><td> </td>'."\n";
877 if($SESSION->cal_show_user) {
878 $content .= '<td class="eventskey calendar_event_user" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showuser'.$getvars."'".'" /></td>';
879 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
881 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showuser'.$getvars."'".'" /></td>';
882 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
885 $content .= "</tr>\n</table>\n";
890 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
893 if(empty($shortformat)) {
894 $shortformat = get_string('strftimedayshort');
901 // To have it in one place, if a change is needed
902 $formal = userdate($tstamp, $shortformat);
904 $datestamp = usergetdate($tstamp);
905 $datenow = usergetdate($now);
907 if($usecommonwords == false) {
908 // We don't want words, just a date
911 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
913 return get_string('today', 'calendar');
916 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
917 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
920 return get_string('yesterday', 'calendar');
923 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
924 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
927 return get_string('tomorrow', 'calendar');
934 function calendar_time_representation($time) {
935 static $langtimeformat = NULL;
936 if($langtimeformat === NULL) {
937 $langtimeformat = get_string('strftimetime');
939 $timeformat = get_user_preferences('calendar_timeformat');
940 if(empty($timeformat)){
941 $timeformat = get_config(NULL,'calendar_site_timeformat');
943 // The ? is needed because the preference might be present, but empty
944 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
950 function calendar_get_link_href($linkbase, $d, $m, $y) {
951 if(empty($linkbase)) return '';
953 if(!empty($d)) $paramstr .= '&cal_d='.$d;
954 if(!empty($m)) $paramstr .= '&cal_m='.$m;
955 if(!empty($y)) $paramstr .= '&cal_y='.$y;
956 if(!empty($paramstr)) $paramstr = substr($paramstr, 5);
957 return $linkbase.$paramstr;
963 function calendar_get_link_tag($text, $linkbase, $d, $m, $y) {
964 $href = calendar_get_link_href($linkbase, $d, $m, $y);
965 if(empty($href)) return $text;
966 return '<a href="'.$href.'">'.$text.'</a>';
970 * Build and return a previous month HTML link, with an arrow.
971 * @param string $text The text label.
972 * @param string $linkbase The URL stub.
973 * @param int $d $m $y Day of month, month and year numbers.
974 * @param bool $accesshide Default visible, or hide from all except screenreaders.
975 * @return string HTML string.
977 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
978 $href = calendar_get_link_href($linkbase, $d, $m, $y);
979 if(empty($href)) return $text;
980 return link_arrow_left($text, $href, $accesshide, 'previous');
984 * Build and return a next month HTML link, with an arrow.
985 * @param string $text The text label.
986 * @param string $linkbase The URL stub.
987 * @param int $d $m $y Day of month, month and year numbers.
988 * @param bool $accesshide Default visible, or hide from all except screenreaders.
989 * @return string HTML string.
991 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
992 $href = calendar_get_link_href($linkbase, $d, $m, $y);
993 if(empty($href)) return $text;
994 return link_arrow_right($text, $href, $accesshide, 'next');
997 function calendar_wday_name($englishname) {
998 return get_string(strtolower($englishname), 'calendar');
1001 function calendar_days_in_month($month, $year) {
1002 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
1005 function calendar_get_sideblock_upcoming($events, $linkhref = NULL) {
1007 $lines = count($events);
1012 for ($i = 0; $i < $lines; ++$i) {
1013 if (!isset($events[$i]->time)) { // Just for robustness
1016 $events[$i] = calendar_add_event_metadata($events[$i]);
1017 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
1018 if (!empty($events[$i]->referer)) {
1019 // That's an activity event, so let's provide the hyperlink
1020 $content .= $events[$i]->referer;
1022 if(!empty($linkhref)) {
1023 $ed = usergetdate($events[$i]->timestart);
1024 $href = calendar_get_link_href(CALENDAR_URL.$linkhref, $ed['mday'], $ed['mon'], $ed['year']);
1025 $content .= '<a href="'.$href.'#event_'.$events[$i]->id.'">'.$events[$i]->name.'</a>';
1028 $content .= $events[$i]->name;
1031 $events[$i]->time = str_replace('»', '<br />»', $events[$i]->time);
1032 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
1033 if ($i < $lines - 1) $content .= '<hr />';
1039 function calendar_add_month($month, $year) {
1041 return array(1, $year + 1);
1044 return array($month + 1, $year);
1048 function calendar_sub_month($month, $year) {
1050 return array(12, $year - 1);
1053 return array($month - 1, $year);
1057 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1058 $eventsbyday = array();
1059 $typesbyday = array();
1060 $durationbyday = array();
1062 if($events === false) {
1066 foreach($events as $event) {
1068 $startdate = usergetdate($event->timestart);
1069 // Set end date = start date if no duration
1070 if ($event->timeduration) {
1071 $enddate = usergetdate($event->timestart + $event->timeduration - 1);
1073 $enddate = $startdate;
1076 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1077 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1082 $eventdaystart = intval($startdate['mday']);
1084 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1085 // Give the event to its day
1086 $eventsbyday[$eventdaystart][] = $event->id;
1088 // Mark the day as having such an event
1089 if($event->courseid == SITEID && $event->groupid == 0) {
1090 $typesbyday[$eventdaystart]['startglobal'] = true;
1091 // Set event class for global event
1092 $events[$event->id]->class = 'calendar_event_global';
1094 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1095 $typesbyday[$eventdaystart]['startcourse'] = true;
1096 // Set event class for course event
1097 $events[$event->id]->class = 'calendar_event_course';
1099 else if($event->groupid) {
1100 $typesbyday[$eventdaystart]['startgroup'] = true;
1101 // Set event class for group event
1102 $events[$event->id]->class = 'calendar_event_group';
1104 else if($event->userid) {
1105 $typesbyday[$eventdaystart]['startuser'] = true;
1106 // Set event class for user event
1107 $events[$event->id]->class = 'calendar_event_user';
1111 if($event->timeduration == 0) {
1112 // Proceed with the next
1116 // The event starts on $month $year or before. So...
1117 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
1119 // Also, it ends on $month $year or later...
1120 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1122 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1123 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1124 $durationbyday[$i][] = $event->id;
1125 if($event->courseid == SITEID && $event->groupid == 0) {
1126 $typesbyday[$i]['durationglobal'] = true;
1128 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1129 $typesbyday[$i]['durationcourse'] = true;
1131 else if($event->groupid) {
1132 $typesbyday[$i]['durationgroup'] = true;
1134 else if($event->userid) {
1135 $typesbyday[$i]['durationuser'] = true;
1143 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1144 $module = get_coursemodule_from_instance($modulename, $instance);
1146 if($module === false) return false;
1147 if(!calendar_get_course_cached($coursecache, $module->course)) {
1153 function calendar_get_course_cached(&$coursecache, $courseid) {
1154 global $COURSE, $DB;
1156 if (!isset($coursecache[$courseid])) {
1157 if ($courseid == $COURSE->id) {
1158 $coursecache[$courseid] = $COURSE;
1160 $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
1163 return $coursecache[$courseid];
1166 function calendar_session_vars($course=null) {
1167 global $SESSION, $USER;
1169 if(!isset($SESSION->cal_course_referer)) {
1170 $SESSION->cal_course_referer = 0;
1172 if(!isset($SESSION->cal_show_global)) {
1173 $SESSION->cal_show_global = true;
1175 if(!isset($SESSION->cal_show_groups)) {
1176 $SESSION->cal_show_groups = true;
1178 if(!isset($SESSION->cal_show_course)) {
1179 $SESSION->cal_show_course = true;
1181 if(!isset($SESSION->cal_show_user)) {
1182 $SESSION->cal_show_user = true;
1184 if ($course !== null) {
1185 // speedup hack for calendar related blocks
1186 $SESSION->cal_courses_shown = array($course->id => $course);
1188 $SESSION->cal_courses_shown = calendar_get_default_courses(true);
1190 if(empty($SESSION->cal_users_shown)) {
1191 // The empty() instead of !isset() here makes a whole world of difference,
1192 // as it will automatically change to the user's id when the user first logs
1193 // in. With !isset(), it would never do that.
1194 $SESSION->cal_users_shown = isloggedin() ? $USER->id : false;
1195 } else if(is_numeric($SESSION->cal_users_shown) && isloggedin() && $SESSION->cal_users_shown != $USER->id) {
1196 // Follow the white rabbit, for example if a teacher logs in as a student
1197 $SESSION->cal_users_shown = $USER->id;
1201 function calendar_set_referring_course($courseid) {
1203 $SESSION->cal_course_referer = intval($courseid);
1206 function calendar_set_filters(&$courses, &$group, &$user, $courseeventsfrom = NULL, $groupeventsfrom = NULL, $ignorefilters = false) {
1207 global $SESSION, $USER, $CFG, $DB;
1209 // Insidious bug-wannabe: setting $SESSION->cal_courses_shown to $course->id would cause
1210 // the code to function incorrectly UNLESS we convert it to an integer. One case where
1211 // PHP's loose type system works against us.
1212 if(is_string($SESSION->cal_courses_shown)) {
1213 $SESSION->cal_courses_shown = intval($SESSION->cal_courses_shown);
1215 if($courseeventsfrom === NULL) {
1216 $courseeventsfrom = $SESSION->cal_courses_shown;
1219 // MDL-9059, $courseeventsfrom can be an int, or an array of ints, or an array of course objects
1220 // convert all to array of objects
1221 // we probably should do some clean up and make sure that session is set to use the proper form
1222 if (is_int($courseeventsfrom)) { // case of an int, e.g. calendar view page
1224 $c[$courseeventsfrom] = $DB->get_record('course', array('id'=>$courseeventsfrom));
1225 $courseeventsfrom = $c;
1226 } else if (is_array($courseeventsfrom)) { // case of an array of ints, e.g. course home page
1227 foreach ($courseeventsfrom as $i=>$courseid) { // TODO: this seems wrong, the array is often constructed as [courseid] => 1 ???
1228 if (is_int($courseid)) {
1229 $courseeventsfrom[$i] = $DB->get_record('course', array('id'=>$courseid));
1234 if($groupeventsfrom === NULL) {
1235 $groupeventsfrom = $SESSION->cal_courses_shown;
1238 if(($SESSION->cal_show_course && $SESSION->cal_show_global) || $ignorefilters) {
1239 if(is_int($courseeventsfrom)) {
1240 $courses = array(SITEID, $courseeventsfrom);
1242 else if(is_array($courseeventsfrom)) {
1243 $courses = array_keys($courseeventsfrom);
1244 $courses[] = SITEID;
1247 else if($SESSION->cal_show_course) {
1248 if(is_int($courseeventsfrom)) {
1249 $courses = array($courseeventsfrom);
1251 else if(is_array($courseeventsfrom)) {
1252 $courses = array_keys($courseeventsfrom);
1254 $courses = array_diff($courses, array(SITEID));
1256 else if($SESSION->cal_show_global) {
1257 $courses = array(SITEID);
1262 //BUG 6130 clean $courses array as SESSION has bad entries.
1263 // [pj] TODO: See if this has to do with my new change in get_default_courses and can be taken out
1264 if (is_array($courses)) {
1265 foreach ($courses as $index => $value) {
1266 if (empty($value)) unset($courses[$index]);
1269 // Sort courses for consistent colour highlighting
1270 // Effectively ignoring SITEID as setting as last course id
1271 $key = array_search(SITEID, $courses);
1272 if ($key !== false) {
1273 unset($courses[$key]);
1275 $courses[] = SITEID;
1281 if($SESSION->cal_show_user || $ignorefilters) {
1282 // This doesn't work for arrays yet (maybe someday it will)
1283 $user = $SESSION->cal_users_shown;
1288 if($SESSION->cal_show_groups || $ignorefilters) {
1289 if(is_int($groupeventsfrom)) {
1290 $groupcourses = array($groupeventsfrom);
1292 else if(is_array($groupeventsfrom)) {
1293 $groupcourses = array_keys($groupeventsfrom);
1296 // XXX TODO: not sure how to replace $CFG->calendar_adminseesall
1297 if(has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM)) && !empty($CFG->calendar_adminseesall)) {
1301 $grouparray = array();
1303 // We already have the courses to examine in $courses
1304 // For each course...
1306 foreach($groupcourses as $courseid) {
1308 if (!isset($courseeventsfrom[$courseid]->context)) { // SHOULD be set MDL-11221
1309 if (is_object($courseeventsfrom[$courseid])) {
1310 $courseeventsfrom[$courseid]->context = get_context_instance(CONTEXT_COURSE, $courseid);
1314 // If the user is an editing teacher in there,
1315 if (isloggedin() && isset($courseeventsfrom[$courseid]->context) && has_capability('moodle/calendar:manageentries', $courseeventsfrom[$courseid]->context)) {
1316 // If this course has groups, show events from all of them
1317 if(is_int($groupeventsfrom)) {
1318 if (is_object($courseeventsfrom[$courseid])) { // SHOULD be set MDL-11221
1319 $courserecord = $courseeventsfrom[$courseid];
1321 $courserecord = $DB->get_record('course', array('id'=>$courseid));
1323 $courserecord = $DB->get_record('course', array('id'=>$courseid));
1324 if ($courserecord->groupmode != NOGROUPS || !$courserecord->groupmodeforce) {
1325 $groupids[] = $courseid;
1328 else if(isset($SESSION->cal_courses_shown[$courseid]) && ($SESSION->cal_courses_shown[$courseid]->groupmode != NOGROUPS || !$SESSION->cal_courses_shown[$courseid]->groupmodeforce)) {
1329 $groupids[] = $courseid;
1333 // Otherwise (not editing teacher) show events from the group he is a member of
1334 else if(isset($USER->groupmember[$courseid])) {
1335 //changed to 2D array
1336 foreach ($USER->groupmember[$courseid] as $groupid){
1337 $grouparray[] = $groupid;
1342 if (!empty($groupids)) {
1345 WHERE courseid IN (".implode(',', $groupids).')';
1347 if ($grouprecords = $DB->get_records_sql($sql, null)) {
1348 foreach ($grouprecords as $grouprecord) {
1349 $grouparray[] = $grouprecord->id;
1354 if(empty($grouparray)) {
1358 $group = $grouparray;
1368 function calendar_edit_event_allowed($event) {
1371 // Must be logged in
1372 if (!isloggedin()) {
1376 // can not be using guest account
1377 if ($USER->username == "guest") {
1381 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1382 // if user has manageentries at site level, return true
1383 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1387 // if groupid is set, it's definitely a group event
1388 if ($event->groupid) {
1389 // Allow users to add/edit group events if:
1390 // 1) They have manageentries (= entries for whole course)
1391 // 2) They have managegroupentries AND are in the group
1392 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1394 has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $group->courseid)) ||
1395 (has_capability('moodle/calendar:managegroupentries', get_context_instance(CONTEXT_COURSE, $group->courseid))
1396 && groups_is_member($event->groupid)));
1397 } else if ($event->courseid) {
1398 // if groupid is not set, but course is set,
1399 // it's definiely a course event
1400 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1401 } else if ($event->userid && $event->userid == $USER->id) {
1402 // if course is not set, but userid id set, it's a user event
1403 return (has_capability('moodle/calendar:manageownentries', $sitecontext));
1408 function calendar_get_default_courses($ignoreref = false) {
1409 global $USER, $CFG, $SESSION, $DB;
1411 if(!empty($SESSION->cal_course_referer) && !$ignoreref) {
1412 return array($SESSION->cal_course_referer => 1);
1415 if (!isloggedin()) {
1420 if (has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
1421 if (!empty($CFG->calendar_adminseesall)) {
1422 $courses = $DB->get_records_sql('SELECT id, 1 FROM {course}');
1427 if (isset($CFG->adminseesall)) {
1428 $courses = get_my_courses($USER->id, null, null, $CFG->adminseesall);
1431 $courses = get_my_courses($USER->id, null, null, false);
1437 function calendar_preferences_button() {
1440 // Guests have no preferences
1441 if (!isloggedin() || isguestuser()) {
1445 return "<form method=\"get\" ".
1446 " action=\"$CFG->wwwroot/calendar/preferences.php\">".
1447 "<div><input type=\"submit\" value=\"".get_string("preferences", "calendar")." ...\" /></div></form>";
1450 function calendar_format_event_time($event, $now, $morehref, $usecommonwords = true, $showtime=0) {
1451 $startdate = usergetdate($event->timestart);
1452 $enddate = usergetdate($event->timestart + $event->timeduration);
1453 $usermidnightstart = usergetmidnight($event->timestart);
1455 if($event->timeduration) {
1456 // To avoid doing the math if one IF is enough :)
1457 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1460 $usermidnightend = $usermidnightstart;
1463 // OK, now to get a meaningful display...
1464 // First of all we have to construct a human-readable date/time representation
1466 if($event->timeduration) {
1467 // It has a duration
1468 if($usermidnightstart == $usermidnightend ||
1469 ($event->timestart == $usermidnightstart) && ($event->timeduration == 86400 || $event->timeduration == 86399) ||
1470 ($event->timestart + $event->timeduration <= $usermidnightstart + 86400)) {
1471 // But it's all on the same day
1472 $timestart = calendar_time_representation($event->timestart);
1473 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1474 $time = $timestart.' <strong>»</strong> '.$timeend;
1476 if ($event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399)) {
1477 $time = get_string('allday', 'calendar');
1480 // Set printable representation
1482 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1483 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&', $enddate['mday'], $enddate['mon'], $enddate['year']).', '.$time;
1488 // It spans two or more days
1489 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords).', ';
1490 if ($showtime == $usermidnightstart) {
1493 $timestart = calendar_time_representation($event->timestart);
1494 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords).', ';
1495 if ($showtime == $usermidnightend) {
1498 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1500 // Set printable representation
1501 if ($now >= $usermidnightstart && $now < ($usermidnightstart + 86400)) {
1502 $eventtime = $timestart.' <strong>»</strong> '.calendar_get_link_tag($dayend, CALENDAR_URL.'view.php?view=day'.$morehref.'&', $enddate['mday'], $enddate['mon'], $enddate['year']).
1505 $eventtime = calendar_get_link_tag($daystart, CALENDAR_URL.'view.php?view=day'.$morehref.'&', $startdate['mday'], $startdate['mon'], $startdate['year']).
1506 $timestart.' <strong>»</strong> '.calendar_get_link_tag($dayend, CALENDAR_URL.'view.php?view=day'.$morehref.'&', $enddate['mday'], $enddate['mon'], $enddate['year']).
1513 // Set printable representation
1515 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1516 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&', $startdate['mday'], $startdate['mon'], $startdate['year']).trim($time);
1522 if($event->timestart + $event->timeduration < $now) {
1524 $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
1530 function calendar_print_month_selector($name, $selected) {
1533 for ($i=1; $i<=12; $i++) {
1534 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1537 echo html_writer::select($months, $name, $selected, false);
1540 function calendar_get_filters_status() {
1544 if($SESSION->cal_show_global) {
1547 if($SESSION->cal_show_course) {
1550 if($SESSION->cal_show_groups) {
1553 if($SESSION->cal_show_user) {
1559 function calendar_set_filters_status($packed_bitfield) {
1560 global $SESSION, $USER;
1562 if (!isloggedin()) {
1566 $SESSION->cal_show_global = ($packed_bitfield & 1);
1567 $SESSION->cal_show_course = ($packed_bitfield & 2);
1568 $SESSION->cal_show_groups = ($packed_bitfield & 4);
1569 $SESSION->cal_show_user = ($packed_bitfield & 8);
1574 function calendar_get_allowed_types(&$allowed) {
1575 global $USER, $CFG, $SESSION, $DB;
1576 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1577 $allowed->user = has_capability('moodle/calendar:manageownentries', $sitecontext);
1578 $allowed->groups = false; // This may change just below
1579 $allowed->courses = false; // This may change just below
1580 $allowed->site = has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
1582 if(!empty($SESSION->cal_course_referer) && $SESSION->cal_course_referer != SITEID) {
1583 $course = $DB->get_record('course', array('id'=>$SESSION->cal_course_referer));
1584 $coursecontext = get_context_instance(CONTEXT_COURSE, $SESSION->cal_course_referer);
1586 if(has_capability('moodle/calendar:manageentries', $coursecontext)) {
1587 $allowed->courses = array($course->id => 1);
1589 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1590 $allowed->groups = groups_get_all_groups($SESSION->cal_course_referer);
1592 } else if(has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1593 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1594 $allowed->groups = groups_get_all_groups($SESSION->cal_course_referer, $USER->id);
1601 * see if user can add calendar entries at all
1602 * used to print the "New Event" button
1605 function calendar_user_can_add_event() {
1606 calendar_get_allowed_types($allowed);
1607 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
1611 * Check wether the current user is permitted to add events
1613 * @param object $event
1616 function calendar_add_event_allowed($event) {
1619 // can not be using guest account
1620 if (!isloggedin() or isguestuser()) {
1624 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1625 // if user has manageentries at site level, always return true
1626 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1630 switch ($event->eventtype) {
1632 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1635 // Allow users to add/edit group events if:
1636 // 1) They have manageentries (= entries for whole course)
1637 // 2) They have managegroupentries AND are in the group
1638 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1640 has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $group->courseid)) ||
1641 (has_capability('moodle/calendar:managegroupentries', get_context_instance(CONTEXT_COURSE, $group->courseid))
1642 && groups_is_member($event->groupid)));
1645 if ($event->userid == $USER->id) {
1646 return (has_capability('moodle/calendar:manageownentries', $sitecontext));
1648 //there is no 'break;' intentionally
1651 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
1654 if (isset($event->courseid) && $event->courseid > 0) {
1655 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1662 * A class to manage calendar events
1664 * This class provides the required functionality in order to manage calendar events.
1665 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1666 * better framework for dealing with calendar events in particular regard to file
1667 * handling through the new file API
1669 * @property int $id The id within the event table
1670 * @property string $name The name of the event
1671 * @property string $description The description of the event
1672 * @property int $format The format of the description FORMAT_?
1673 * @property int $courseid The course the event is associated with (0 if none)
1674 * @property int $groupid The group the event is associated with (0 if none)
1675 * @property int $userid The user the event is associated with (0 if none)
1676 * @property int $repeatid If this is a repeated event this will be set to the
1677 * id of the original
1678 * @property string $modulename If added by a module this will be the module name
1679 * @property int $instance If added by a module this will be the module instance
1680 * @property string $eventtype The event type
1681 * @property int $timestart The start time as a timestamp
1682 * @property int $timeduration The duration of the event in seconds
1683 * @property int $visible 1 if the event is visible
1684 * @property int $uuid ?
1685 * @property int $sequence ?
1686 * @property int $timemodified The time last modified as a timestamp
1688 class calendar_event {
1691 * An object containing the event properties can be accessed via the
1692 * magic __get/set methods
1695 protected $properties = null;
1697 * The converted event discription with file paths resolved
1698 * This gets populated when someone requests description for the first time
1701 protected $_description = null;
1703 * The filearea to use with this event
1706 protected static $filearea = 'calendar_event_description';
1708 * The options to use with this description editor
1711 protected $editoroptions = array(
1713 'forcehttps'=>false,
1714 'maxfiles'=>EDITOR_UNLIMITED_FILES,
1716 'trusttext'=>false);
1718 * The context to use with the description editor
1721 protected $editorcontext = null;
1724 * Instantiates a new event and optionally populates its properties with the
1727 * @param stdClass $data Optional. An object containing the properties to for
1730 public function __construct($data=null) {
1733 // First convert to object if it is not already (should either be object or assoc array)
1734 if (!is_object($data)) {
1735 $data = (object)$data;
1738 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
1740 $data->eventrepeats = 0;
1742 if (empty($data->id)) {
1746 if (!empty($data->timeduration) && is_array($data->timeduration)) {
1747 $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
1749 if (!empty($data->description) && is_array($data->description)) {
1750 $data->format = $data->description['format'];
1751 $data->description = $data->description['text'];
1752 } else if (empty($data->description)) {
1753 $data->description = '';
1756 if (empty($data->format)) {
1757 if (can_use_html_editor()) {
1758 $data->format = FORMAT_HTML;
1760 $data->format = FORMAT_MOODLE;
1764 $this->properties = $data;
1768 * Magic property method
1770 * Attempts to call a set_$key method if one exists otherwise falls back
1771 * to simply set the property
1773 * @param string $key
1774 * @param mixed $value
1776 public function __set($key, $value) {
1777 if (method_exists($this, 'set_'.$key)) {
1778 $this->{'set_'.$key}($value);
1780 $this->properties->{$key} = $value;
1786 * Attempts to call a get_$key method to return the property and ralls over
1787 * to return the raw property
1792 public function __get($key) {
1793 if (method_exists($this, 'get_'.$key)) {
1794 return $this->{'get_'.$key}();
1796 return $this->properties->{$key};
1800 * Stupid PHP needs an isset magic method if you use the get magic method and
1801 * still want empty calls to work.... blah ~!
1803 * @param string $key
1806 public function __isset($key) {
1807 return !empty($this->properties->{$key});
1811 * Returns an array of editoroptions for this event: Called by __get
1812 * Please use $blah = $event->editoroptions;
1815 protected function get_editoroptions() {
1816 return $this->editoroptions;
1820 * Returns an event description: Called by __get
1821 * Please use $blah = $event->description;
1825 protected function get_description() {
1827 if ($this->_description === null) {
1828 // Check if we have already resolved the context for this event
1829 if ($this->editorcontext === null) {
1830 // Switch on the event type to decide upon the appropriate context
1831 // to use for this event
1832 switch ($this->properties->eventtype) {
1835 // Course and group event files are served from the course context
1836 // and there are checks in plugin.php to ensure permissions are
1838 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
1842 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
1846 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
1849 // Hmmmm some modules use custom eventtype strings, if that is the
1850 // case we are going to abandon using files. Anything that uses a
1851 // custom type is being added manually through code
1852 return clean_text($this->properties->description, $this->properties->format);
1857 // Work out the item id for the editor, if this is a repeated event then the files will
1858 // be associated with the original
1859 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
1860 $itemid = $this->properties->repeatid;
1862 $itemid = $this->properties->id;
1865 // Convert file paths in the description so that things display correctly
1866 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, self::$filearea, $itemid);
1867 // Clean the text so no nasties get through
1868 $this->_description = clean_text($this->_description, $this->properties->format);
1870 // Finally return the description
1871 return $this->_description;
1875 * Return the number of repeat events there are in this events series
1879 public function count_repeats() {
1881 if (!empty($this->properties->repeatid)) {
1882 $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
1883 // We don't want to count ourselves
1884 $this->properties->eventrepeats--;
1886 return $this->properties->eventrepeats;
1890 * Update or create an event within the database
1892 * Pass in a object containing the event properties and this function will
1893 * insert it into the database and deal with any associated files
1896 * @see update_event()
1898 * @param stdClass $data
1900 public function update($data) {
1901 global $CFG, $DB, $USER;
1903 $this->properties = (object)$data;
1904 $this->properties->timemodified = time();
1905 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
1907 if (empty($this->properties->id) || $this->properties->id < 1) {
1909 if (!calendar_add_event_allowed($this->properties)) {
1910 print_error('nopermissions');
1914 switch ($this->properties->eventtype) {
1916 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
1917 $this->properties->courseid = 0;
1918 $this->properties->groupid = 0;
1919 $this->properties->userid = $USER->id;
1922 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
1923 $this->properties->courseid = SITEID;
1924 $this->properties->groupid = 0;
1925 $this->properties->userid = $USER->id;
1928 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
1929 $this->properties->groupid = 0;
1930 $this->properties->userid = $USER->id;
1933 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
1934 $this->properties->groupid = 0;
1935 $this->properties->userid = $USER->id;
1938 // Ewww we should NEVER get here, but just incase we do lets
1940 $usingeditor = false;
1944 $editor = $this->properties->description;
1945 $this->properties->format = $this->properties->description['format'];
1946 $this->properties->description = $this->properties->description['text'];
1949 // Insert the event into the database
1950 $this->properties->id = $DB->insert_record('event', $this->properties);
1953 $this->properties->description = file_save_draft_area_files(
1955 $this->editorcontext->id,
1957 $this->properties->id,
1958 $this->editoroptions,
1960 $this->editoroptions['forcehttps']);
1962 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
1965 // Log the event entry.
1966 add_to_log($this->properties->courseid, 'calendar', 'add', 'event.php?action=edit&id='.$this->properties->id, $this->properties->name);
1968 $repeatedids = array();
1970 if (!empty($this->properties->repeat)) {
1971 $this->properties->repeatid = $this->properties->id;
1972 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));
1974 $eventcopy = clone($this->properties);
1975 unset($eventcopy->id);
1977 for($i = 1; $i < $eventcopy->repeats; $i++) {
1979 $eventcopy->timestart = ($eventcopy->timestart+WEEKSECS) + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart+WEEKSECS);
1981 // Get the event id for the log record.
1982 $eventcopyid = $DB->insert_record('event', $eventcopy);
1984 // If the context has been set delete all associated files
1986 $fs = get_file_storage();
1987 $files = $fs->get_area_files($this->editorcontext->id, self::$filearea, $this->properties->id);
1988 foreach ($files as $file) {
1989 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
1993 $repeatedids[] = $eventcopyid;
1994 // Log the event entry.
1995 add_to_log($eventcopy->courseid, 'calendar', 'add', 'event.php?action=edit&id='.$eventcopyid, $eventcopy->name);
1999 // Hook for tracking added events
2000 self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
2004 if(!calendar_edit_event_allowed($this->properties)) {
2005 print_error('nopermissions');
2009 if ($this->editorcontext !== null) {
2010 $this->properties->description = file_save_draft_area_files(
2011 $this->properties->description['itemid'],
2012 $this->editorcontext->id,
2014 $this->properties->id,
2015 $this->editoroptions,
2016 $this->properties->description['text'],
2017 $this->editoroptions['forcehttps']);
2019 $this->properties->format = $this->properties->description['format'];
2020 $this->properties->description = $this->properties->description['text'];
2024 $event = $DB->get_record('event', array('id'=>$this->properties->id));
2026 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
2028 if ($updaterepeated) {
2030 if ($this->properties->timestart != $event->timestart) {
2031 $timestartoffset = $this->properties->timestart - $event->timestart;
2032 $sql = "UPDATE {event}
2035 timestart = timestart + ?,
2038 WHERE repeatid = ?";
2039 $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
2041 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2042 $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
2044 $DB->execute($sql, $params);
2046 // Log the event update.
2047 add_to_log($this->properties->courseid, 'calendar', 'edit all', 'event.php?action=edit&id='.$this->properties->id, $this->properties->name);
2049 $DB->update_record('event', $this->properties);
2050 $event = calendar_event::load($this->properties->id);
2051 $this->properties = $event->properties();
2052 add_to_log($this->properties->courseid, 'calendar', 'edit', 'event.php?action=edit&id='.$this->properties->id, $this->properties->name);
2055 // Hook for tracking event updates
2056 self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
2062 * Deletes an event and if selected an repeated events in the same series
2064 * This function deletes an event, any associated events if $deleterepeated=true,
2065 * and cleans up any files associated with the events.
2067 * @see delete_event()
2069 * @param bool $deleterepeated
2072 public function delete($deleterepeated=false) {
2073 global $DB, $USER, $CFG;
2075 // If $this->properties->id is not set then something is wrong
2076 if (empty($this->properties->id)) {
2077 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
2082 $DB->delete_records('event', array('id'=>$this->properties->id));
2084 // If the editor context hasn't already been set then set it now
2085 if ($this->editorcontext === null) {
2086 switch ($this->properties->eventtype) {
2089 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
2092 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
2095 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
2098 // There is a chance we can get here as some modules use there own
2099 // eventtype strings. In this case the event has been added by code
2100 // and we don't need to worry about it anyway
2105 // If the context has been set delete all associated files
2106 if ($this->editorcontext !== null) {
2107 $fs = get_file_storage();
2108 $files = $fs->get_area_files($this->editorcontext->id, self::$filearea, $this->properties->id);
2109 foreach ($files as $file) {
2114 // Fire the event deleted hook
2115 self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));
2117 // If we need to delete repeated events then we will fetch them all and delete one by one
2118 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2119 // Get all records where the repeatid is the same as the event being removed
2120 $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
2121 // For each of the returned events populate a calendar_event object and call delete
2122 // make sure the arg passed is false as we are already deleting all repeats
2123 foreach ($events as $event) {
2124 $event = new calendar_event($event);
2125 $event->delete(false);
2133 * Fetch all event properties
2135 * This function returns all of the events properties as an object and optionally
2136 * can prepare an editor for the description field at the same time. This is
2137 * designed to work when the properties are going to be used to set the default
2138 * values of a moodle forms form.
2140 * @param bool $prepareeditor If set to true a editor is prepared for use with
2141 * the mforms editor element. (for description)
2142 * @return stdClass Object containing event properties
2144 public function properties($prepareeditor=false) {
2145 global $USER, $CFG, $DB;
2147 // First take a copy of the properties. We don't want to actually change the
2148 // properties or we'd forever be converting back and forwards between an
2149 // editor formatted description and not
2150 $properties = clone($this->properties);
2151 // Clean the description here
2152 $properties->description = clean_text($properties->description, $properties->format);
2154 // If set to true we need to prepare the properties for use with an editor
2155 // and prepare the file area
2156 if ($prepareeditor) {
2158 // We may or may not have a property id. If we do then we need to work
2159 // out the context so we can copy the existing files to the draft area
2160 if (!empty($properties->id)) {
2162 if ($properties->eventtype === 'site') {
2164 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
2165 } else if ($properties->eventtype === 'user') {
2167 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
2168 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
2169 // First check the course is valid
2170 $course = $DB->get_record('course', array('id'=>$properties->courseid));
2172 print_error('invalidcourse');
2175 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $course->id);
2176 // We have a course and are within the course context so we had
2177 // better use the courses max bytes value
2178 $this->editoroptions['maxbytes'] = $course->maxbytes;
2180 // If we get here we have a custom event type as used by some
2181 // modules. In this case the event will have been added by
2182 // code and we won't need the editor
2183 $this->editoroptions['maxbytes'] = 0;
2184 $this->editoroptions['maxfiles'] = 0;
2187 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2190 // Get the context id that is what we really want
2191 $contextid = $this->editorcontext->id;
2195 // If we get here then this is a new event in which case we don't need a
2196 // context as there is no existing files to copy to the draft area.
2200 // If the contextid === false we don't support files so no preparing
2202 if ($contextid !== false) {
2203 // Just encase it has already been submitted
2204 $draftiddescription = file_get_submitted_draft_itemid('description');
2205 // Prepare the draft area, this copies existing files to the draft area as well
2206 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, self::$filearea, $properties->id, $this->editoroptions, $properties->description);
2208 $draftiddescription = 0;
2211 // Structure the description field as the editor requires
2212 $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2215 // Finally return the properties
2220 * Toggles the visibility of an event
2222 * @param null|bool $force If it is left null the events visibility is flipped,
2223 * If it is false the event is made hidden, if it is true it
2226 public function toggle_visibility($force=null) {
2229 // Set visible to the default if it is not already set
2230 if (empty($this->properties->visible)) {
2231 $this->properties->visible = 1;
2234 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2235 // Make this event visible
2236 $this->properties->visible = 1;
2238 self::calendar_event_hook('show_event', array($this->properties));
2240 // Make this event hidden
2241 $this->properties->visible = 0;
2243 self::calendar_event_hook('hide_event', array($this->properties));
2246 // Update the database to reflect this change
2247 return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2251 * Attempts to call the hook for the specified action should a calendar type
2252 * by set $CFG->calendar, and the appopriate function defined
2255 * @staticvar bool $extcalendarinc Used to track the inclusion of the calendar lib
2256 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2257 * @param array $args The args to pass to the hook, usually the event is the first element
2260 public static function calendar_event_hook($action, array $args) {
2262 static $extcalendarinc;
2263 if ($extcalendarinc === null) {
2264 if (!empty($CFG->calendar) && file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
2265 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
2266 $extcalendarinc = true;
2268 $extcalendarinc = false;
2271 if($extcalendarinc === false) {
2274 $hook = $CFG->dirroot .'_'.$action;
2275 if (function_exists($hook)) {
2276 call_user_func_array($hook, $args);
2283 * Returns a calendar_event object when provided with an event id
2285 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2286 * it will result in an exception being thrown
2288 * @param int|object $param
2289 * @return calendar_event|false
2291 public static function load($param) {
2293 if (is_object($param)) {
2294 $event = new calendar_event($param);
2296 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2297 $event = new calendar_event($event);
2303 * Creates a new event and returns a calendar_event object
2305 * @param object|array $properties An object containing event properties
2306 * @return calendar_event|false The event object or false if it failed
2308 public static function create($properties) {
2309 if (is_array($properties)) {
2310 $properties = (object)$properties;
2312 if (!is_object($properties)) {
2313 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2315 $event = new calendar_event();
2316 if ($event->update($properties)) {