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_URL', $CFG->wwwroot
.'/calendar/');
49 define('CALENDAR_TF_24', '%H:%M');
50 define('CALENDAR_TF_12', '%I:%M %p');
52 define('CALENDAR_EVENT_GLOBAL', 1);
53 define('CALENDAR_EVENT_COURSE', 2);
54 define('CALENDAR_EVENT_GROUP', 4);
55 define('CALENDAR_EVENT_USER', 8);
58 * CALENDAR_STARTING_WEEKDAY has since been deprecated please call calendar_get_starting_weekday() instead
61 define('CALENDAR_STARTING_WEEKDAY', CALENDAR_DEFAULT_STARTING_WEEKDAY
);
64 * Return the days of the week
68 function calendar_get_days() {
69 return array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
73 * Gets the first day of the week
75 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
79 function calendar_get_starting_weekday() {
82 if (isset($CFG->calendar_startwday
)) {
83 $firstday = $CFG->calendar_startwday
;
85 $firstday = get_string('firstdayofweek', 'langconfig');
88 if(!is_numeric($firstday)) {
89 return CALENDAR_DEFAULT_STARTING_WEEKDAY
;
91 return intval($firstday) %
7;
96 * Generates the HTML for a miniature calendar
98 * @global core_renderer $OUTPUT
99 * @param array $courses
100 * @param array $groups
101 * @param array $users
102 * @param int $cal_month
103 * @param int $cal_year
106 function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
107 global $CFG, $USER, $OUTPUT;
109 $display = new stdClass
;
110 $display->minwday
= get_user_preferences('calendar_startwday', calendar_get_starting_weekday());
111 $display->maxwday
= $display->minwday +
6;
115 if(!empty($cal_month) && !empty($cal_year)) {
116 $thisdate = usergetdate(time()); // Date and time the user sees at his location
117 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
118 // Navigated to this month
120 $display->thismonth
= true;
122 // Navigated to other month, let's do a nice trick and save us a lot of work...
123 if(!checkdate($cal_month, 1, $cal_year)) {
124 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
125 $display->thismonth
= true;
127 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
128 $display->thismonth
= false;
132 $date = usergetdate(time()); // Date and time the user sees at his location
133 $display->thismonth
= true;
136 // Fill in the variables we 're going to use, nice and tidy
137 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
138 $display->maxdays
= calendar_days_in_month($m, $y);
140 if (get_user_timezone_offset() < 99) {
141 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
142 $display->tstart
= gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
143 $display->tend
= gmmktime(23, 59, 59, $m, $display->maxdays
, $y); // GMT
145 // no timezone info specified
146 $display->tstart
= mktime(0, 0, 0, $m, 1, $y);
147 $display->tend
= mktime(23, 59, 59, $m, $display->maxdays
, $y);
150 $startwday = dayofweek(1, $m, $y);
152 // Align the starting weekday to fall in our display range
153 // This is simple, not foolproof.
154 if($startwday < $display->minwday
) {
158 // TODO: THIS IS TEMPORARY CODE!
159 // [pj] I was just reading through this and realized that I when writing this code I was probably
160 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
161 // make_timestamp would accomplish the same thing. So here goes a test:
162 //$test_start = make_timestamp($y, $m, 1);
163 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
164 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
165 //notify('Failed assertion in calendar/lib.php line 126; display->tstart = '.$display->tstart.', dst_offset = '.dst_offset_on($display->tstart).', usertime = '.usertime($display->tstart).', make_t = '.$test_start);
167 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
168 //notify('Failed assertion in calendar/lib.php line 130; display->tend = '.$display->tend.', dst_offset = '.dst_offset_on($display->tend).', usertime = '.usertime($display->tend).', make_t = '.$test_end);
172 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
173 $events = calendar_get_events(
174 usertime($display->tstart
) - dst_offset_on($display->tstart
),
175 usertime($display->tend
) - dst_offset_on($display->tend
),
176 $users, $groups, $courses);
178 // Set event course class for course events
179 if (!empty($events)) {
180 foreach ($events as $eventid => $event) {
181 if (!empty($event->modulename
)) {
182 $cm = get_coursemodule_from_instance($event->modulename
, $event->instance
);
183 if (!groups_course_module_visible($cm)) {
184 unset($events[$eventid]);
190 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
191 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
192 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
193 // arguments to this function.
195 $hrefparams = array();
196 if(!empty($courses)) {
197 $courses = array_diff($courses, array(SITEID
));
198 if(count($courses) == 1) {
199 $hrefparams['course'] = reset($courses);
203 // We want to have easy access by day, since the display is on a per-day basis.
204 // Arguments passed by reference.
205 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
206 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
208 //Accessibility: added summary and <abbr> elements.
209 $days_title = calendar_get_days();
211 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
212 $summary = get_string('tabledata', 'access', $summary);
213 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table
214 $content .= '<tr class="weekdays">'; // Header row: day names
216 // Print out the names of the weekdays
217 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
218 for($i = $display->minwday
; $i <= $display->maxwday
; ++
$i) {
219 // This uses the % operator to get the correct weekday no matter what shift we have
220 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
221 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i %
7], 'calendar') .'">'.
222 get_string($days[$i %
7], 'calendar') ."</abbr></th>\n";
225 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
227 // For the table display. $week is the row; $dayweek is the column.
228 $dayweek = $startwday;
230 // Paddding (the first week may have blank days in the beginning)
231 for($i = $display->minwday
; $i < $startwday; ++
$i) {
232 $content .= '<td class="dayblank"> </td>'."\n";
235 $weekend = CALENDAR_DEFAULT_WEEKEND
;
236 if (isset($CFG->calendar_weekend
)) {
237 $weekend = intval($CFG->calendar_weekend
);
240 // Now display all the calendar
241 for($day = 1; $day <= $display->maxdays
; ++
$day, ++
$dayweek) {
242 if($dayweek > $display->maxwday
) {
243 // We need to change week (table row)
244 $content .= '</tr><tr>';
245 $dayweek = $display->minwday
;
250 if ($weekend & (1 << ($dayweek %
7))) {
251 // Weekend. This is true no matter what the exact range is.
252 $class = 'weekend day';
254 // Normal working day.
258 // Special visual fx if an event is defined
259 if(isset($eventsbyday[$day])) {
260 $class .= ' hasevent';
261 $hrefparams['view'] = 'day';
262 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $hrefparams), $day, $m, $y);
265 foreach($eventsbyday[$day] as $eventid) {
266 if (!isset($events[$eventid])) {
269 $event = $events[$eventid];
271 $component = 'moodle';
272 if(!empty($event->modulename
)) {
274 $popupalt = $event->modulename
;
275 $component = $event->modulename
;
276 } else if ($event->courseid
== SITEID
) { // Site event
277 $popupicon = 'c/site';
278 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) { // Course event
279 $popupicon = 'c/course';
280 } else if ($event->groupid
) { // Group event
281 $popupicon = 'c/group';
282 } else if ($event->userid
) { // User event
283 $popupicon = 'c/user';
286 $dayhref->set_anchor('event_'.$event->id
);
288 $popupcontent .= html_writer
::start_tag('div');
289 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
290 $popupcontent .= html_writer
::link($dayhref, format_string($event->name
, true));
291 $popupcontent .= html_writer
::end_tag('div');
294 //Accessibility: functionality moved to calendar_get_popup.
295 if($display->thismonth
&& $day == $d) {
296 $popup = calendar_get_popup(true, $events[$eventid]->timestart
, $popupcontent);
298 $popup = calendar_get_popup(false, $events[$eventid]->timestart
, $popupcontent);
301 // Class and cell content
302 if(isset($typesbyday[$day]['startglobal'])) {
303 $class .= ' calendar_event_global';
304 } else if(isset($typesbyday[$day]['startcourse'])) {
305 $class .= ' calendar_event_course';
306 } else if(isset($typesbyday[$day]['startgroup'])) {
307 $class .= ' calendar_event_group';
308 } else if(isset($typesbyday[$day]['startuser'])) {
309 $class .= ' calendar_event_user';
311 $cell = '<a href="'.(string)$dayhref.'" '.$popup.'>'.$day.'</a>';
316 $durationclass = false;
317 if (isset($typesbyday[$day]['durationglobal'])) {
318 $durationclass = ' duration_global';
319 } else if(isset($typesbyday[$day]['durationcourse'])) {
320 $durationclass = ' duration_course';
321 } else if(isset($typesbyday[$day]['durationgroup'])) {
322 $durationclass = ' duration_group';
323 } else if(isset($typesbyday[$day]['durationuser'])) {
324 $durationclass = ' duration_user';
326 if ($durationclass) {
327 $class .= ' duration '.$durationclass;
330 // If event has a class set then add it to the table day <td> tag
331 // Note: only one colour for minicalendar
332 if(isset($eventsbyday[$day])) {
333 foreach($eventsbyday[$day] as $eventid) {
334 if (!isset($events[$eventid])) {
337 $event = $events[$eventid];
338 if (!empty($event->class)) {
339 $class .= ' '.$event->class;
345 // Special visual fx for today
346 //Accessibility: hidden text for today, and popup.
347 if($display->thismonth
&& $day == $d) {
349 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
351 if(! isset($eventsbyday[$day])) {
352 $class .= ' eventnone';
353 $popup = calendar_get_popup(true, false);
354 $cell = '<a href="#" '.$popup.'>'.$day.'</a>';
356 $cell = get_accesshide($today.' ').$cell;
361 $class = ' class="'.$class.'"';
363 $content .= '<td'.$class.'>'.$cell."</td>\n";
366 // Paddding (the last week may have blank days at the end)
367 for($i = $dayweek; $i <= $display->maxwday
; ++
$i) {
368 $content .= '<td class="dayblank"> </td>';
370 $content .= '</tr>'; // Last row ends
372 $content .= '</table>'; // Tabular display of days ends
378 * calendar_get_popup, called at multiple points in from calendar_get_mini.
379 * Copied and modified from calendar_get_mini.
380 * @global moodle_page $PAGE
381 * @param $is_today bool, false except when called on the current day.
382 * @param $event_timestart mixed, $events[$eventid]->timestart, OR false if there are no events.
383 * @param $popupcontent string.
384 * @return $popup string, contains onmousover and onmouseout events.
386 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
389 if ($popupcount === null) {
394 $popupcaption = get_string('today', 'calendar').' ';
396 if (false === $event_timestart) {
397 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
398 $popupcontent = get_string('eventnone', 'calendar');
401 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
403 $id = 'calendar_tooltip_'.$popupcount;
404 $PAGE->requires
->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
407 return 'id="'.$id.'"';
410 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
411 global $CFG, $COURSE, $DB;
413 $display = new stdClass
;
414 $display->range
= $daysinfuture; // How many days in the future we 'll look
415 $display->maxevents
= $maxevents;
419 // Prepare "course caching", since it may save us a lot of queries
420 $coursecache = array();
423 $now = time(); // We 'll need this later
424 $usermidnighttoday = usergetmidnight($now);
427 $display->tstart
= $fromtime;
429 $display->tstart
= $usermidnighttoday;
432 // This works correctly with respect to the user's DST, but it is accurate
433 // only because $fromtime is always the exact midnight of some day!
434 $display->tend
= usergetmidnight($display->tstart + DAYSECS
* $display->range +
3 * HOURSECS
) - 1;
436 // Get the events matching our criteria
437 $events = calendar_get_events($display->tstart
, $display->tend
, $users, $groups, $courses);
439 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
440 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
441 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
442 // arguments to this function.
444 $hrefparams = array();
445 if(!empty($courses)) {
446 $courses = array_diff($courses, array(SITEID
));
447 if(count($courses) == 1) {
448 $hrefparams['course'] = reset($courses);
452 if ($events !== false) {
454 $modinfo =& get_fast_modinfo($COURSE);
456 foreach($events as $event) {
459 if (!empty($event->modulename
)) {
460 if ($event->courseid
== $COURSE->id
) {
461 if (isset($modinfo->instances
[$event->modulename
][$event->instance
])) {
462 $cm = $modinfo->instances
[$event->modulename
][$event->instance
];
463 if (!$cm->uservisible
) {
468 if (!$cm = get_coursemodule_from_instance($event->modulename
, $event->instance
)) {
471 if (!coursemodule_visible_for_user($cm)) {
475 if ($event->modulename
== 'assignment'){
476 // create calendar_event to test edit_event capability
477 // this new event will also prevent double creation of calendar_event object
478 $checkevent = new calendar_event($event);
479 // TODO: rewrite this hack somehow
480 if (!calendar_edit_event_allowed($checkevent)){ // cannot manage entries, eg. student
481 if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance
))) {
482 // print_error("invalidid", 'assignment');
485 // assign assignment to assignment object to use hidden_is_hidden method
486 require_once($CFG->dirroot
.'/mod/assignment/lib.php');
488 if (!file_exists($CFG->dirroot
.'/mod/assignment/type/'.$assignment->assignmenttype
.'/assignment.class.php')) {
491 require_once ($CFG->dirroot
.'/mod/assignment/type/'.$assignment->assignmenttype
.'/assignment.class.php');
493 $assignmentclass = 'assignment_'.$assignment->assignmenttype
;
494 $assignmentinstance = new $assignmentclass($cm->id
, $assignment, $cm);
496 if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
497 $event->description
= get_string('notavailableyet', 'assignment');
503 if ($processed >= $display->maxevents
) {
507 $event->time
= calendar_format_event_time($event, $now, $hrefparams);
515 function calendar_add_event_metadata($event) {
516 global $CFG, $OUTPUT;
518 //Support multilang in event->name
519 $event->name
= format_string($event->name
,true);
521 if(!empty($event->modulename
)) { // Activity event
522 // The module name is set. I will assume that it has to be displayed, and
523 // also that it is an automatically-generated event. And of course that the
524 // fields for get_coursemodule_from_instance are set correctly.
525 $module = calendar_get_module_cached($coursecache, $event->modulename
, $event->instance
);
527 if ($module === false) {
531 $modulename = get_string('modulename', $event->modulename
);
532 if (get_string_manager()->string_exists($event->eventtype
, $event->modulename
)) {
533 // will be used as alt text if the event icon
534 $eventtype = get_string($event->eventtype
, $event->modulename
);
538 $icon = $OUTPUT->pix_url('icon', $event->modulename
) . '';
540 $context = get_context_instance(CONTEXT_COURSE
, $module->course
);
541 $fullname = format_string($coursecache[$module->course
]->fullname
, true, array('context' => $context));
543 $event->icon
= '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
544 $event->referer
= '<a href="'.$CFG->wwwroot
.'/mod/'.$event->modulename
.'/view.php?id='.$module->id
.'">'.$event->name
.'</a>';
545 $event->courselink
= '<a href="'.$CFG->wwwroot
.'/course/view.php?id='.$module->course
.'">'.$fullname.'</a>';
546 $event->cmid
= $module->id
;
549 } else if($event->courseid
== SITEID
) { // Site event
550 $event->icon
= '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/site') . '" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
551 $event->cssclass
= 'calendar_event_global';
552 } else if($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) { // Course event
553 calendar_get_course_cached($coursecache, $event->courseid
);
555 $context = get_context_instance(CONTEXT_COURSE
, $event->courseid
);
556 $fullname = format_string($coursecache[$event->courseid
]->fullname
, true, array('context' => $context));
558 $event->icon
= '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/course') . '" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
559 $event->courselink
= '<a href="'.$CFG->wwwroot
.'/course/view.php?id='.$event->courseid
.'">'.$fullname.'</a>';
560 $event->cssclass
= 'calendar_event_course';
561 } else if ($event->groupid
) { // Group event
562 $event->icon
= '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/group') . '" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
563 $event->cssclass
= 'calendar_event_group';
564 } else if($event->userid
) { // User event
565 $event->icon
= '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/user') . '" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
566 $event->cssclass
= 'calendar_event_user';
572 * Prints a calendar event
576 function calendar_print_event($event, $showactions=true) {
577 global $CFG, $USER, $OUTPUT, $PAGE;
578 debugging('calendar_print_event is deprecated please update your code', DEBUG_DEVELOPER
);
579 $renderer = $PAGE->get_renderer('core_calendar');
580 if (!($event instanceof calendar_event
)) {
581 $event = new calendar_event($event);
583 echo $renderer->event($event);
587 * Get calendar events
588 * @param int $tstart Start time of time range for events
589 * @param int $tend End time of time range for events
590 * @param array/int/boolean $users array of users, user id or boolean for all/no user events
591 * @param array/int/boolean $groups array of groups, group id or boolean for all/no group events
592 * @param array/int/boolean $courses array of courses, course id or boolean for all/no course events
593 * @param boolean $withduration whether only events starting within time range selected
594 * or events in progress/already started selected as well
595 * @param boolean $ignorehidden whether to select only visible events or all events
596 * @return array of selected events or an empty array if there aren't any (or there was an error)
598 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
603 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
607 if(is_array($users) && !empty($users)) {
608 // Events from a number of users
609 if(!empty($whereclause)) $whereclause .= ' OR';
610 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
611 } else if(is_numeric($users)) {
612 // Events from one user
613 if(!empty($whereclause)) $whereclause .= ' OR';
614 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
615 } else if($users === true) {
616 // Events from ALL users
617 if(!empty($whereclause)) $whereclause .= ' OR';
618 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
619 } else if($users === false) {
620 // No user at all, do nothing
623 if(is_array($groups) && !empty($groups)) {
624 // Events from a number of groups
625 if(!empty($whereclause)) $whereclause .= ' OR';
626 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
627 } else if(is_numeric($groups)) {
628 // Events from one group
629 if(!empty($whereclause)) $whereclause .= ' OR ';
630 $whereclause .= ' groupid = '.$groups;
631 } else if($groups === true) {
632 // Events from ALL groups
633 if(!empty($whereclause)) $whereclause .= ' OR ';
634 $whereclause .= ' groupid != 0';
636 // boolean false (no groups at all): we don't need to do anything
638 if(is_array($courses) && !empty($courses)) {
639 if(!empty($whereclause)) {
640 $whereclause .= ' OR';
642 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
643 } else if(is_numeric($courses)) {
645 if(!empty($whereclause)) $whereclause .= ' OR';
646 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
647 } else if ($courses === true) {
648 // Events from ALL courses
649 if(!empty($whereclause)) $whereclause .= ' OR';
650 $whereclause .= ' (groupid = 0 AND courseid != 0)';
653 // Security check: if, by now, we have NOTHING in $whereclause, then it means
654 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
655 // events no matter what. Allowing the code to proceed might return a completely
656 // valid query with only time constraints, thus selecting ALL events in that time frame!
657 if(empty($whereclause)) {
662 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
665 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
667 if(!empty($whereclause)) {
668 // We have additional constraints
669 $whereclause = $timeclause.' AND ('.$whereclause.')';
672 // Just basic time filtering
673 $whereclause = $timeclause;
677 $whereclause .= ' AND visible = 1';
680 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
681 if ($events === false) {
687 function calendar_top_controls($type, $data) {
690 if(!isset($data['d'])) {
694 // Ensure course id passed if relevant
695 // Required due to changes in view/lib.php mainly (calendar_session_vars())
697 if (!empty($data['id'])) {
698 $courseid = '&course='.$data['id'];
701 if(!checkdate($data['m'], $data['d'], $data['y'])) {
705 $time = make_timestamp($data['y'], $data['m'], $data['d']);
707 $date = usergetdate($time);
709 $data['m'] = $date['mon'];
710 $data['y'] = $date['year'];
712 //Accessibility: calendar block controls, replaced <table> with <div>.
713 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
714 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
718 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
719 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
720 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
721 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
723 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
724 if (!empty($data['id'])) {
725 $calendarlink->param('course', $data['id']);
728 if (right_to_left()) {
736 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
737 $content .= $left.'<span class="hide"> | </span>';
738 $content .= html_writer
::tag('span', html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
739 $content .= '<span class="hide"> | </span>'. $right;
740 $content .= "<span class=\"clearer\"><!-- --></span>\n";
741 $content .= html_writer
::end_tag('div');
745 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
746 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
747 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&', 0, $nextmonth, $nextyear, $accesshide=true);
748 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&', 0, $prevmonth, $prevyear, true);
750 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
751 if (!empty($data['id'])) {
752 $calendarlink->param('course', $data['id']);
755 if (right_to_left()) {
763 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
764 $content .= $left.'<span class="hide"> | </span>';
765 $content .= html_writer
::tag('span', html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
766 $content .= '<span class="hide"> | </span>'. $right;
767 $content .= "<span class=\"clearer\"><!-- --></span>";
768 $content .= html_writer
::end_tag('div');
771 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view'=>'upcoming')), 1, $data['m'], $data['y']);
772 if (!empty($data['id'])) {
773 $calendarlink->param('course', $data['id']);
775 $calendarlink = html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
776 $content .= html_writer
::tag('div', $calendarlink, array('class'=>'centered'));
779 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
780 if (!empty($data['id'])) {
781 $calendarlink->param('course', $data['id']);
783 $calendarlink = html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
784 $content .= html_writer
::tag('h3', $calendarlink);
787 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
788 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
789 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
790 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
791 $prevlink = calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&', 1, $prevmonth, $prevyear);
792 $nextlink = calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&', 1, $nextmonth, $nextyear);
794 if (right_to_left()) {
802 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
803 $content .= $left . '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>";
804 $content .= '<span class="hide"> | </span>' . $right;
805 $content .= '<span class="clearer"><!-- --></span>';
806 $content .= html_writer
::end_tag('div')."\n";
809 $days = calendar_get_days();
810 $data['d'] = $date['mday']; // Just for convenience
811 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
812 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] +
1));
813 $prevname = calendar_wday_name($days[$prevdate['wday']]);
814 $nextname = calendar_wday_name($days[$nextdate['wday']]);
815 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
816 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
818 if (right_to_left()) {
826 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
828 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
829 $content .= '<span class="hide"> | </span>'. $right;
830 $content .= "<span class=\"clearer\"><!-- --></span>";
831 $content .= html_writer
::end_tag('div')."\n";
838 function calendar_filter_controls(moodle_url
$returnurl) {
839 global $CFG, $USER, $OUTPUT;
843 $id = optional_param( 'id',0,PARAM_INT
);
845 $seturl = new moodle_url('/calendar/set.php', array('return' => $returnurl));
847 $content = '<table>';
850 $seturl->param('var', 'showglobal');
851 if (calendar_show_event_type(CALENDAR_EVENT_GLOBAL
)) {
852 $content .= '<td class="eventskey calendar_event_global" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
853 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
855 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
856 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
859 $seturl->param('var', 'showcourses');
860 if (calendar_show_event_type(CALENDAR_EVENT_COURSE
)) {
861 $content .= '<td class="eventskey calendar_event_course" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidecourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
862 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
864 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_showcourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
865 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
868 if (isloggedin() && !isguestuser()) {
869 $content .= "</tr>\n<tr>";
872 // This course MIGHT have group events defined, so show the filter
873 $seturl->param('var', 'showgroups');
874 if (calendar_show_event_type(CALENDAR_EVENT_GROUP
)) {
875 $content .= '<td class="eventskey calendar_event_group" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidegroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
876 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
878 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showgroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
879 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
882 // This course CANNOT have group events, so lose the filter
883 $content .= '<td style="width: 11px;"></td><td> </td>'."\n";
886 $seturl->param('var', 'showuser');
887 if (calendar_show_event_type(CALENDAR_EVENT_USER
)) {
888 $content .= '<td class="eventskey calendar_event_user" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
889 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
891 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".$seturl."'".'" /></td>';
892 $content .= '<td><a href="'.$seturl.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
895 $content .= "</tr>\n</table>\n";
900 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
903 if(empty($shortformat)) {
904 $shortformat = get_string('strftimedayshort');
911 // To have it in one place, if a change is needed
912 $formal = userdate($tstamp, $shortformat);
914 $datestamp = usergetdate($tstamp);
915 $datenow = usergetdate($now);
917 if($usecommonwords == false) {
918 // We don't want words, just a date
921 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
923 return get_string('today', 'calendar');
926 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
927 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
930 return get_string('yesterday', 'calendar');
933 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] +
1 ) ||
934 ($datestamp['year'] == $datenow['year'] +
1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
937 return get_string('tomorrow', 'calendar');
944 function calendar_time_representation($time) {
945 static $langtimeformat = NULL;
946 if($langtimeformat === NULL) {
947 $langtimeformat = get_string('strftimetime');
949 $timeformat = get_user_preferences('calendar_timeformat');
950 if(empty($timeformat)){
951 $timeformat = get_config(NULL,'calendar_site_timeformat');
953 // The ? is needed because the preference might be present, but empty
954 return userdate($time, empty($timeformat) ?
$langtimeformat : $timeformat);
958 * Adds day, month, year arguments to a URL and returns a moodle_url object.
960 * @param string|moodle_url $linkbase
966 function calendar_get_link_href($linkbase, $d, $m, $y) {
967 if (empty($linkbase)) {
970 if (!($linkbase instanceof moodle_url
)) {
971 $linkbase = new moodle_url();
974 $linkbase->param('cal_d', $d);
977 $linkbase->param('cal_m', $m);
980 $linkbase->param('cal_y', $y);
986 * This function has been deprecated as of Moodle 2.0... DO NOT USE!!!!!
991 * @param string $text
992 * @param string|moodle_url $linkbase
996 * @return string HTML link
998 function calendar_get_link_tag($text, $linkbase, $d, $m, $y) {
999 $url = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1003 return html_writer
::link($url, $text);
1007 * Build and return a previous month HTML link, with an arrow.
1009 * @param string $text The text label.
1010 * @param string|moodle_url $linkbase The URL stub.
1011 * @param int $d $m $y Day of month, month and year numbers.
1012 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1013 * @return string HTML string.
1015 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
1016 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1020 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
1024 * Build and return a next month HTML link, with an arrow.
1026 * @param string $text The text label.
1027 * @param string|moodle_url $linkbase The URL stub.
1028 * @param int $d $m $y Day of month, month and year numbers.
1029 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1030 * @return string HTML string.
1032 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
1033 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1037 return link_arrow_right($text, (string)$href, $accesshide, 'next');
1040 function calendar_wday_name($englishname) {
1041 return get_string(strtolower($englishname), 'calendar');
1044 function calendar_days_in_month($month, $year) {
1045 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
1048 function calendar_get_block_upcoming($events, $linkhref = NULL) {
1050 $lines = count($events);
1055 for ($i = 0; $i < $lines; ++
$i) {
1056 if (!isset($events[$i]->time
)) { // Just for robustness
1059 $events[$i] = calendar_add_event_metadata($events[$i]);
1060 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon
.'</span> ';
1061 if (!empty($events[$i]->referer
)) {
1062 // That's an activity event, so let's provide the hyperlink
1063 $content .= $events[$i]->referer
;
1065 if(!empty($linkhref)) {
1066 $ed = usergetdate($events[$i]->timestart
);
1067 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL
.$linkhref), $ed['mday'], $ed['mon'], $ed['year']);
1068 $href->set_anchor('event_'.$events[$i]->id
);
1069 $content .= html_writer
::link($href, $events[$i]->name
);
1072 $content .= $events[$i]->name
;
1075 $events[$i]->time
= str_replace('»', '<br />»', $events[$i]->time
);
1076 $content .= '<div class="date">'.$events[$i]->time
.'</div></div>';
1077 if ($i < $lines - 1) $content .= '<hr />';
1083 function calendar_add_month($month, $year) {
1085 return array(1, $year +
1);
1088 return array($month +
1, $year);
1092 function calendar_sub_month($month, $year) {
1094 return array(12, $year - 1);
1097 return array($month - 1, $year);
1101 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1102 $eventsbyday = array();
1103 $typesbyday = array();
1104 $durationbyday = array();
1106 if($events === false) {
1110 foreach($events as $event) {
1112 $startdate = usergetdate($event->timestart
);
1113 // Set end date = start date if no duration
1114 if ($event->timeduration
) {
1115 $enddate = usergetdate($event->timestart +
$event->timeduration
- 1);
1117 $enddate = $startdate;
1120 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1121 if(!($startdate['year'] * 13 +
$startdate['mon'] <= $year * 13 +
$month) && ($enddate['year'] * 13 +
$enddate['mon'] >= $year * 13 +
$month)) {
1126 $eventdaystart = intval($startdate['mday']);
1128 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1129 // Give the event to its day
1130 $eventsbyday[$eventdaystart][] = $event->id
;
1132 // Mark the day as having such an event
1133 if($event->courseid
== SITEID
&& $event->groupid
== 0) {
1134 $typesbyday[$eventdaystart]['startglobal'] = true;
1135 // Set event class for global event
1136 $events[$event->id
]->class = 'calendar_event_global';
1138 else if($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
1139 $typesbyday[$eventdaystart]['startcourse'] = true;
1140 // Set event class for course event
1141 $events[$event->id
]->class = 'calendar_event_course';
1143 else if($event->groupid
) {
1144 $typesbyday[$eventdaystart]['startgroup'] = true;
1145 // Set event class for group event
1146 $events[$event->id
]->class = 'calendar_event_group';
1148 else if($event->userid
) {
1149 $typesbyday[$eventdaystart]['startuser'] = true;
1150 // Set event class for user event
1151 $events[$event->id
]->class = 'calendar_event_user';
1155 if($event->timeduration
== 0) {
1156 // Proceed with the next
1160 // The event starts on $month $year or before. So...
1161 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ?
intval($startdate['mday']) : 0;
1163 // Also, it ends on $month $year or later...
1164 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ?
intval($enddate['mday']) : calendar_days_in_month($month, $year);
1166 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1167 for($i = $lowerbound +
1; $i <= $upperbound; ++
$i) {
1168 $durationbyday[$i][] = $event->id
;
1169 if($event->courseid
== SITEID
&& $event->groupid
== 0) {
1170 $typesbyday[$i]['durationglobal'] = true;
1172 else if($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
1173 $typesbyday[$i]['durationcourse'] = true;
1175 else if($event->groupid
) {
1176 $typesbyday[$i]['durationgroup'] = true;
1178 else if($event->userid
) {
1179 $typesbyday[$i]['durationuser'] = true;
1187 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1188 $module = get_coursemodule_from_instance($modulename, $instance);
1190 if($module === false) return false;
1191 if(!calendar_get_course_cached($coursecache, $module->course
)) {
1197 function calendar_get_course_cached(&$coursecache, $courseid) {
1198 global $COURSE, $DB;
1200 if (!isset($coursecache[$courseid])) {
1201 if ($courseid == $COURSE->id
) {
1202 $coursecache[$courseid] = $COURSE;
1204 $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
1207 return $coursecache[$courseid];
1211 * Returns the courses to load events for, the
1213 * @global moodle_database $DB
1214 * @param array $courseeventsfrom An array of courses to load calendar events for
1215 * @param bool $ignorefilters
1216 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1218 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1219 global $USER, $CFG, $DB;
1221 // For backwards compatability we have to check whether the courses array contains
1222 // just id's in which case we need to load course objects.
1223 $coursestoload = array();
1224 foreach ($courseeventsfrom as $id => $something) {
1225 if (!is_object($something)) {
1226 $coursestoload[] = $id;
1227 unset($courseeventsfrom[$id]);
1230 if (!empty($coursestoload)) {
1231 // TODO remove this in 2.2
1232 debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER
);
1233 $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
1240 $isloggedin = isloggedin();
1242 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_COURSE
)) {
1243 $courses = array_keys($courseeventsfrom);
1245 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_GLOBAL
)) {
1246 $courses[] = SITEID
;
1248 $courses = array_unique($courses);
1251 if (!empty($courses) && in_array(SITEID
, $courses)) {
1252 // Sort courses for consistent colour highlighting
1253 // Effectively ignoring SITEID as setting as last course id
1254 $key = array_search(SITEID
, $courses);
1255 unset($courses[$key]);
1256 $courses[] = SITEID
;
1259 if ($ignorefilters ||
($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER
))) {
1263 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP
) ||
$ignorefilters)) {
1265 if (!empty($CFG->calendar_adminseesall
) && has_capability('moodle/calendar:manageentries', get_system_context())) {
1267 } else if ($isloggedin) {
1268 $groupids = array();
1270 // We already have the courses to examine in $courses
1271 // For each course...
1272 foreach ($courseeventsfrom as $courseid => $course) {
1273 // If the user is an editing teacher in there,
1274 if (!empty($USER->groupmember
[$course->id
])) {
1275 // We've already cached the users groups for this course so we can just use that
1276 $groupids = array_merge($groupids, $USER->groupmember
[$course->id
]);
1277 } else if (($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE
, $course->id
))) {
1278 // If this course has groups, show events from all of them
1279 $coursegroups = groups_get_user_groups($course->id
, $USER->id
);
1280 $groupids = array_merge($groupids, $coursegroups['0']);
1283 if (!empty($groupids)) {
1288 if (empty($courses)) {
1292 return array($courses, $group, $user);
1295 function calendar_edit_event_allowed($event) {
1298 // Must be logged in
1299 if (!isloggedin()) {
1303 // can not be using guest account
1304 if (isguestuser()) {
1308 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
1309 // if user has manageentries at site level, return true
1310 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1314 // if groupid is set, it's definitely a group event
1315 if (!empty($event->groupid
)) {
1316 // Allow users to add/edit group events if:
1317 // 1) They have manageentries (= entries for whole course)
1318 // 2) They have managegroupentries AND are in the group
1319 $group = $DB->get_record('groups', array('id'=>$event->groupid
));
1321 has_capability('moodle/calendar:manageentries', $event->context
) ||
1322 (has_capability('moodle/calendar:managegroupentries', $event->context
)
1323 && groups_is_member($event->groupid
)));
1324 } else if (!empty($event->courseid
)) {
1325 // if groupid is not set, but course is set,
1326 // it's definiely a course event
1327 return has_capability('moodle/calendar:manageentries', $event->context
);
1328 } else if (!empty($event->userid
) && $event->userid
== $USER->id
) {
1329 // if course is not set, but userid id set, it's a user event
1330 return (has_capability('moodle/calendar:manageownentries', $event->context
));
1331 } else if (!empty($event->userid
)) {
1332 return (has_capability('moodle/calendar:manageentries', $event->context
));
1338 * Returns the default courses to display on the calendar when there isn't a specific
1339 * course to display.
1341 * @global moodle_database $DB
1342 * @return array Array of courses to display
1344 function calendar_get_default_courses() {
1347 if (!isloggedin()) {
1352 if (!empty($CFG->calendar_adminseesall
) && has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM
))) {
1353 list ($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
1354 $sql = "SELECT c.* $select
1356 JOIN {event} e ON e.courseid = c.id
1358 $courses = $DB->get_records_sql($sql, null, 0, 20);
1359 foreach ($courses as $course) {
1360 context_instance_preload($course);
1365 $courses = enrol_get_my_courses();
1370 function calendar_preferences_button(stdClass
$course) {
1373 // Guests have no preferences
1374 if (!isloggedin() ||
isguestuser()) {
1378 return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id
)), get_string("preferences", "calendar"));
1381 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime=0) {
1382 $startdate = usergetdate($event->timestart
);
1383 $enddate = usergetdate($event->timestart +
$event->timeduration
);
1384 $usermidnightstart = usergetmidnight($event->timestart
);
1386 if($event->timeduration
) {
1387 // To avoid doing the math if one IF is enough :)
1388 $usermidnightend = usergetmidnight($event->timestart +
$event->timeduration
);
1391 $usermidnightend = $usermidnightstart;
1394 if (empty($linkparams) ||
!is_array($linkparams)) {
1395 $linkparams = array();
1397 $linkparams['view'] = 'day';
1399 // OK, now to get a meaningful display...
1400 // First of all we have to construct a human-readable date/time representation
1402 if($event->timeduration
) {
1403 // It has a duration
1404 if($usermidnightstart == $usermidnightend ||
1405 ($event->timestart
== $usermidnightstart) && ($event->timeduration
== 86400 ||
$event->timeduration
== 86399) ||
1406 ($event->timestart +
$event->timeduration
<= $usermidnightstart +
86400)) {
1407 // But it's all on the same day
1408 $timestart = calendar_time_representation($event->timestart
);
1409 $timeend = calendar_time_representation($event->timestart +
$event->timeduration
);
1410 $time = $timestart.' <strong>»</strong> '.$timeend;
1412 if ($event->timestart
== $usermidnightstart && ($event->timeduration
== 86400 ||
$event->timeduration
== 86399)) {
1413 $time = get_string('allday', 'calendar');
1416 // Set printable representation
1418 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
1419 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1420 $eventtime = html_writer
::link($url, $day).', '.$time;
1425 // It spans two or more days
1426 $daystart = calendar_day_representation($event->timestart
, $now, $usecommonwords).', ';
1427 if ($showtime == $usermidnightstart) {
1430 $timestart = calendar_time_representation($event->timestart
);
1431 $dayend = calendar_day_representation($event->timestart +
$event->timeduration
, $now, $usecommonwords).', ';
1432 if ($showtime == $usermidnightend) {
1435 $timeend = calendar_time_representation($event->timestart +
$event->timeduration
);
1437 // Set printable representation
1438 if ($now >= $usermidnightstart && $now < ($usermidnightstart +
86400)) {
1439 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1440 $eventtime = $timestart.' <strong>»</strong> '.html_writer
::link($url, $dayend).$timeend;
1442 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1443 $eventtime = html_writer
::link($url, $daystart).$timestart.' <strong>»</strong> ';
1445 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1446 $eventtime .= html_writer
::link($url, $dayend).$timeend;
1452 // Set printable representation
1454 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
1455 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1456 $eventtime = html_writer
::link($url, $day).trim($time);
1462 if($event->timestart +
$event->timeduration
< $now) {
1464 $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
1470 function calendar_print_month_selector($name, $selected) {
1472 for ($i=1; $i<=12; $i++
) {
1473 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1475 echo html_writer
::select($months, $name, $selected, false);
1479 * Checks to see if the requested type of event should be shown for the given user.
1481 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1482 * The type to check the display for (default is to display all)
1483 * @param stdClass|int|null $user The user to check for - by default the current user
1484 * @return bool True if the tyep should be displayed false otherwise
1486 function calendar_show_event_type($type, $user = null) {
1487 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER
;
1488 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
1490 if (!isset($SESSION->calendarshoweventtype
)) {
1491 $SESSION->calendarshoweventtype
= $default;
1493 return $SESSION->calendarshoweventtype
& $type;
1495 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
1500 * Sets the display of the event type given $display.
1501 * If $display = true the event type will be shown.
1502 * If $display = false the event type will NOT be shown.
1503 * If $display = null the current value will be toggled and saved.
1505 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1506 * @param true|false|null $display
1507 * @param stdClass|int|null $user
1509 function calendar_set_event_type_display($type, $display = null, $user = null) {
1510 $persist = get_user_preferences('calendar_persistflt', 0, $user);
1511 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER
;
1512 if ($persist === 0) {
1514 if (!isset($SESSION->calendarshoweventtype
)) {
1515 $SESSION->calendarshoweventtype
= $default;
1517 $preference = $SESSION->calendarshoweventtype
;
1519 $preference = get_user_preferences('calendar_savedflt', $default, $user);
1521 $current = $preference & $type;
1522 if ($display === null) {
1523 $display = !$current;
1525 if ($display && !$current) {
1526 $preference +
= $type;
1527 } else if (!$display && $current) {
1528 $preference -= $type;
1530 if ($persist === 0) {
1531 $SESSION->calendarshoweventtype
= $preference;
1533 if ($preference == $default) {
1534 unset_user_preference('calendar_savedflt', $user);
1536 set_user_preference('calendar_savedflt', $preference, $user);
1541 function calendar_get_allowed_types(&$allowed, $course = null) {
1542 global $USER, $CFG, $DB;
1543 $allowed->user
= has_capability('moodle/calendar:manageownentries', get_system_context());
1544 $allowed->groups
= false; // This may change just below
1545 $allowed->courses
= false; // This may change just below
1546 $allowed->site
= has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE
, SITEID
));
1548 if (!empty($course)) {
1549 if (!is_object($course)) {
1550 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST
);
1552 if ($course->id
!= SITEID
) {
1553 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
1555 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1556 $allowed->courses
= array($course->id
=> 1);
1558 if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
1559 $allowed->groups
= groups_get_all_groups($course->id
);
1561 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1562 if($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
1563 $allowed->groups
= groups_get_all_groups($course->id
);
1571 * see if user can add calendar entries at all
1572 * used to print the "New Event" button
1575 function calendar_user_can_add_event($course) {
1576 if (!isloggedin() ||
isguestuser()) {
1579 calendar_get_allowed_types($allowed, $course);
1580 return (bool)($allowed->user ||
$allowed->groups ||
$allowed->courses ||
$allowed->site
);
1584 * Check wether the current user is permitted to add events
1586 * @param object $event
1589 function calendar_add_event_allowed($event) {
1592 // can not be using guest account
1593 if (!isloggedin() or isguestuser()) {
1597 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
1598 // if user has manageentries at site level, always return true
1599 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1603 switch ($event->eventtype
) {
1605 return has_capability('moodle/calendar:manageentries', $event->context
);
1608 // Allow users to add/edit group events if:
1609 // 1) They have manageentries (= entries for whole course)
1610 // 2) They have managegroupentries AND are in the group
1611 $group = $DB->get_record('groups', array('id'=>$event->groupid
));
1613 has_capability('moodle/calendar:manageentries', $event->context
) ||
1614 (has_capability('moodle/calendar:managegroupentries', $event->context
)
1615 && groups_is_member($event->groupid
)));
1618 if ($event->userid
== $USER->id
) {
1619 return (has_capability('moodle/calendar:manageownentries', $event->context
));
1621 //there is no 'break;' intentionally
1624 return has_capability('moodle/calendar:manageentries', $event->context
);
1627 return has_capability('moodle/calendar:manageentries', $event->context
);
1632 * A class to manage calendar events
1634 * This class provides the required functionality in order to manage calendar events.
1635 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1636 * better framework for dealing with calendar events in particular regard to file
1637 * handling through the new file API
1639 * @property int $id The id within the event table
1640 * @property string $name The name of the event
1641 * @property string $description The description of the event
1642 * @property int $format The format of the description FORMAT_?
1643 * @property int $courseid The course the event is associated with (0 if none)
1644 * @property int $groupid The group the event is associated with (0 if none)
1645 * @property int $userid The user the event is associated with (0 if none)
1646 * @property int $repeatid If this is a repeated event this will be set to the
1647 * id of the original
1648 * @property string $modulename If added by a module this will be the module name
1649 * @property int $instance If added by a module this will be the module instance
1650 * @property string $eventtype The event type
1651 * @property int $timestart The start time as a timestamp
1652 * @property int $timeduration The duration of the event in seconds
1653 * @property int $visible 1 if the event is visible
1654 * @property int $uuid ?
1655 * @property int $sequence ?
1656 * @property int $timemodified The time last modified as a timestamp
1658 class calendar_event
{
1661 * An object containing the event properties can be accessed via the
1662 * magic __get/set methods
1665 protected $properties = null;
1667 * The converted event discription with file paths resolved
1668 * This gets populated when someone requests description for the first time
1671 protected $_description = null;
1673 * The options to use with this description editor
1676 protected $editoroptions = array(
1678 'forcehttps'=>false,
1681 'trusttext'=>false);
1683 * The context to use with the description editor
1686 protected $editorcontext = null;
1689 * Instantiates a new event and optionally populates its properties with the
1692 * @param stdClass $data Optional. An object containing the properties to for
1695 public function __construct($data=null) {
1698 // First convert to object if it is not already (should either be object or assoc array)
1699 if (!is_object($data)) {
1700 $data = (object)$data;
1703 $this->editoroptions
['maxbytes'] = $CFG->maxbytes
;
1705 $data->eventrepeats
= 0;
1707 if (empty($data->id
)) {
1711 // Default to a user event
1712 if (empty($data->eventtype
)) {
1713 $data->eventtype
= 'user';
1716 // Default to the current user
1717 if (empty($data->userid
)) {
1718 $data->userid
= $USER->id
;
1721 if (!empty($data->timeduration
) && is_array($data->timeduration
)) {
1722 $data->timeduration
= make_timestamp($data->timeduration
['year'], $data->timeduration
['month'], $data->timeduration
['day'], $data->timeduration
['hour'], $data->timeduration
['minute']) - $data->timestart
;
1724 if (!empty($data->description
) && is_array($data->description
)) {
1725 $data->format
= $data->description
['format'];
1726 $data->description
= $data->description
['text'];
1727 } else if (empty($data->description
)) {
1728 $data->description
= '';
1729 $data->format
= editors_get_preferred_format();
1731 // Ensure form is defaulted correctly
1732 if (empty($data->format
)) {
1733 $data->format
= editors_get_preferred_format();
1736 if (empty($data->context
)) {
1737 $data->context
= $this->calculate_context($data);
1739 $this->properties
= $data;
1743 * Magic property method
1745 * Attempts to call a set_$key method if one exists otherwise falls back
1746 * to simply set the property
1748 * @param string $key
1749 * @param mixed $value
1751 public function __set($key, $value) {
1752 if (method_exists($this, 'set_'.$key)) {
1753 $this->{'set_'.$key}($value);
1755 $this->properties
->{$key} = $value;
1761 * Attempts to call a get_$key method to return the property and ralls over
1762 * to return the raw property
1767 public function __get($key) {
1768 if (method_exists($this, 'get_'.$key)) {
1769 return $this->{'get_'.$key}();
1771 if (!isset($this->properties
->{$key})) {
1772 throw new coding_exception('Undefined property requested');
1774 return $this->properties
->{$key};
1778 * Stupid PHP needs an isset magic method if you use the get magic method and
1779 * still want empty calls to work.... blah ~!
1781 * @param string $key
1784 public function __isset($key) {
1785 return !empty($this->properties
->{$key});
1789 * Calculate the context value needed for calendar_event.
1790 * Event's type can be determine by the available value store in $data
1791 * It is important to check for the existence of course/courseid to determine
1793 * Default value is set to CONTEXT_USER
1797 protected function calculate_context(stdClass
$data) {
1801 if (isset($data->courseid
) && $data->courseid
> 0) {
1802 $context = get_context_instance(CONTEXT_COURSE
, $data->courseid
);
1803 } else if (isset($data->course
) && $data->course
> 0) {
1804 $context = get_context_instance(CONTEXT_COURSE
, $data->course
);
1805 } else if (isset($data->groupid
) && $data->groupid
> 0) {
1806 $group = $DB->get_record('groups', array('id'=>$data->groupid
));
1807 $context = get_context_instance(CONTEXT_COURSE
, $group->courseid
);
1808 } else if (isset($data->userid
) && $data->userid
> 0 && $data->userid
== $USER->id
) {
1809 $context = get_context_instance(CONTEXT_USER
);
1810 } else if (isset($data->userid
) && $data->userid
> 0 && $data->userid
!= $USER->id
&&
1811 isset($data->instance
) && $data->instance
> 0) {
1812 $cm = get_coursemodule_from_instance($data->modulename
, $data->instance
, 0, false, MUST_EXIST
);
1813 $context = get_context_instance(CONTEXT_COURSE
, $cm->course
);
1815 $context = get_context_instance(CONTEXT_USER
);
1822 * Returns an array of editoroptions for this event: Called by __get
1823 * Please use $blah = $event->editoroptions;
1826 protected function get_editoroptions() {
1827 return $this->editoroptions
;
1831 * Returns an event description: Called by __get
1832 * Please use $blah = $event->description;
1836 protected function get_description() {
1839 require_once($CFG->libdir
. '/filelib.php');
1841 if ($this->_description
=== null) {
1842 // Check if we have already resolved the context for this event
1843 if ($this->editorcontext
=== null) {
1844 // Switch on the event type to decide upon the appropriate context
1845 // to use for this event
1846 $this->editorcontext
= $this->properties
->context
;
1847 if ($this->properties
->eventtype
!= 'user' && $this->properties
->eventtype
!= 'course'
1848 && $this->properties
->eventtype
!= 'site' && $this->properties
->eventtype
!= 'group') {
1849 return clean_text($this->properties
->description
, $this->properties
->format
);
1853 // Work out the item id for the editor, if this is a repeated event then the files will
1854 // be associated with the original
1855 if (!empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
1856 $itemid = $this->properties
->repeatid
;
1858 $itemid = $this->properties
->id
;
1861 // Convert file paths in the description so that things display correctly
1862 $this->_description
= file_rewrite_pluginfile_urls($this->properties
->description
, 'pluginfile.php', $this->editorcontext
->id
, 'calendar', 'event_description', $itemid);
1863 // Clean the text so no nasties get through
1864 $this->_description
= clean_text($this->_description
, $this->properties
->format
);
1866 // Finally return the description
1867 return $this->_description
;
1871 * Return the number of repeat events there are in this events series
1875 public function count_repeats() {
1877 if (!empty($this->properties
->repeatid
)) {
1878 $this->properties
->eventrepeats
= $DB->count_records('event', array('repeatid'=>$this->properties
->repeatid
));
1879 // We don't want to count ourselves
1880 $this->properties
->eventrepeats
--;
1882 return $this->properties
->eventrepeats
;
1886 * Update or create an event within the database
1888 * Pass in a object containing the event properties and this function will
1889 * insert it into the database and deal with any associated files
1892 * @see update_event()
1894 * @param stdClass $data
1895 * @param boolean $checkcapability if moodle should check calendar managing capability or not
1897 public function update($data, $checkcapability=true) {
1898 global $CFG, $DB, $USER;
1900 foreach ($data as $key=>$value) {
1901 $this->properties
->$key = $value;
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 ($checkcapability) {
1910 if (!calendar_add_event_allowed($this->properties
)) {
1911 print_error('nopermissiontoupdatecalendar');
1916 switch ($this->properties
->eventtype
) {
1918 $this->editorcontext
= $this->properties
->context
;
1919 $this->properties
->courseid
= 0;
1920 $this->properties
->groupid
= 0;
1921 $this->properties
->userid
= $USER->id
;
1924 $this->editorcontext
= $this->properties
->context
;
1925 $this->properties
->courseid
= SITEID
;
1926 $this->properties
->groupid
= 0;
1927 $this->properties
->userid
= $USER->id
;
1930 $this->editorcontext
= $this->properties
->context
;
1931 $this->properties
->groupid
= 0;
1932 $this->properties
->userid
= $USER->id
;
1935 $this->editorcontext
= $this->properties
->context
;
1936 $this->properties
->userid
= $USER->id
;
1939 // Ewww we should NEVER get here, but just incase we do lets
1941 $usingeditor = false;
1945 $editor = $this->properties
->description
;
1946 $this->properties
->format
= $this->properties
->description
['format'];
1947 $this->properties
->description
= $this->properties
->description
['text'];
1950 // Insert the event into the database
1951 $this->properties
->id
= $DB->insert_record('event', $this->properties
);
1954 $this->properties
->description
= file_save_draft_area_files(
1956 $this->editorcontext
->id
,
1958 'event_description',
1959 $this->properties
->id
,
1960 $this->editoroptions
,
1962 $this->editoroptions
['forcehttps']);
1964 $DB->set_field('event', 'description', $this->properties
->description
, array('id'=>$this->properties
->id
));
1967 // Log the event entry.
1968 add_to_log($this->properties
->courseid
, 'calendar', 'add', 'event.php?action=edit&id='.$this->properties
->id
, $this->properties
->name
);
1970 $repeatedids = array();
1972 if (!empty($this->properties
->repeat
)) {
1973 $this->properties
->repeatid
= $this->properties
->id
;
1974 $DB->set_field('event', 'repeatid', $this->properties
->repeatid
, array('id'=>$this->properties
->id
));
1976 $eventcopy = clone($this->properties
);
1977 unset($eventcopy->id
);
1979 for($i = 1; $i < $eventcopy->repeats
; $i++
) {
1981 $eventcopy->timestart
= ($eventcopy->timestart+WEEKSECS
) +
dst_offset_on($eventcopy->timestart
) - dst_offset_on($eventcopy->timestart+WEEKSECS
);
1983 // Get the event id for the log record.
1984 $eventcopyid = $DB->insert_record('event', $eventcopy);
1986 // If the context has been set delete all associated files
1988 $fs = get_file_storage();
1989 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description', $this->properties
->id
);
1990 foreach ($files as $file) {
1991 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
1995 $repeatedids[] = $eventcopyid;
1996 // Log the event entry.
1997 add_to_log($eventcopy->courseid
, 'calendar', 'add', 'event.php?action=edit&id='.$eventcopyid, $eventcopy->name
);
2001 // Hook for tracking added events
2002 self
::calendar_event_hook('add_event', array($this->properties
, $repeatedids));
2006 if ($checkcapability) {
2007 if(!calendar_edit_event_allowed($this->properties
)) {
2008 print_error('nopermissiontoupdatecalendar');
2013 if ($this->editorcontext
!== null) {
2014 $this->properties
->description
= file_save_draft_area_files(
2015 $this->properties
->description
['itemid'],
2016 $this->editorcontext
->id
,
2018 'event_description',
2019 $this->properties
->id
,
2020 $this->editoroptions
,
2021 $this->properties
->description
['text'],
2022 $this->editoroptions
['forcehttps']);
2024 $this->properties
->format
= $this->properties
->description
['format'];
2025 $this->properties
->description
= $this->properties
->description
['text'];
2029 $event = $DB->get_record('event', array('id'=>$this->properties
->id
));
2031 $updaterepeated = (!empty($this->properties
->repeatid
) && !empty($this->properties
->repeateditall
));
2033 if ($updaterepeated) {
2035 if ($this->properties
->timestart
!= $event->timestart
) {
2036 $timestartoffset = $this->properties
->timestart
- $event->timestart
;
2037 $sql = "UPDATE {event}
2040 timestart = timestart + ?,
2043 WHERE repeatid = ?";
2044 $params = array($this->properties
->name
, $this->properties
->description
, $timestartoffset, $this->properties
->timeduration
, time(), $event->repeatid
);
2046 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2047 $params = array($this->properties
->name
, $this->properties
->description
, $this->properties
->timeduration
, time(), $event->repeatid
);
2049 $DB->execute($sql, $params);
2051 // Log the event update.
2052 add_to_log($this->properties
->courseid
, 'calendar', 'edit all', 'event.php?action=edit&id='.$this->properties
->id
, $this->properties
->name
);
2054 $DB->update_record('event', $this->properties
);
2055 $event = calendar_event
::load($this->properties
->id
);
2056 $this->properties
= $event->properties();
2057 add_to_log($this->properties
->courseid
, 'calendar', 'edit', 'event.php?action=edit&id='.$this->properties
->id
, $this->properties
->name
);
2060 // Hook for tracking event updates
2061 self
::calendar_event_hook('update_event', array($this->properties
, $updaterepeated));
2067 * Deletes an event and if selected an repeated events in the same series
2069 * This function deletes an event, any associated events if $deleterepeated=true,
2070 * and cleans up any files associated with the events.
2072 * @see delete_event()
2074 * @param bool $deleterepeated
2077 public function delete($deleterepeated=false) {
2080 // If $this->properties->id is not set then something is wrong
2081 if (empty($this->properties
->id
)) {
2082 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER
);
2087 $DB->delete_records('event', array('id'=>$this->properties
->id
));
2089 // If the editor context hasn't already been set then set it now
2090 if ($this->editorcontext
=== null) {
2091 $this->editorcontext
= $this->properties
->context
;
2094 // If the context has been set delete all associated files
2095 if ($this->editorcontext
!== null) {
2096 $fs = get_file_storage();
2097 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description', $this->properties
->id
);
2098 foreach ($files as $file) {
2103 // Fire the event deleted hook
2104 self
::calendar_event_hook('delete_event', array($this->properties
->id
, $deleterepeated));
2106 // If we need to delete repeated events then we will fetch them all and delete one by one
2107 if ($deleterepeated && !empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
2108 // Get all records where the repeatid is the same as the event being removed
2109 $events = $DB->get_records('event', array('repeatid'=>$this->properties
->repeatid
));
2110 // For each of the returned events populate a calendar_event object and call delete
2111 // make sure the arg passed is false as we are already deleting all repeats
2112 foreach ($events as $event) {
2113 $event = new calendar_event($event);
2114 $event->delete(false);
2122 * Fetch all event properties
2124 * This function returns all of the events properties as an object and optionally
2125 * can prepare an editor for the description field at the same time. This is
2126 * designed to work when the properties are going to be used to set the default
2127 * values of a moodle forms form.
2129 * @param bool $prepareeditor If set to true a editor is prepared for use with
2130 * the mforms editor element. (for description)
2131 * @return stdClass Object containing event properties
2133 public function properties($prepareeditor=false) {
2134 global $USER, $CFG, $DB;
2136 // First take a copy of the properties. We don't want to actually change the
2137 // properties or we'd forever be converting back and forwards between an
2138 // editor formatted description and not
2139 $properties = clone($this->properties
);
2140 // Clean the description here
2141 $properties->description
= clean_text($properties->description
, $properties->format
);
2143 // If set to true we need to prepare the properties for use with an editor
2144 // and prepare the file area
2145 if ($prepareeditor) {
2147 // We may or may not have a property id. If we do then we need to work
2148 // out the context so we can copy the existing files to the draft area
2149 if (!empty($properties->id
)) {
2151 if ($properties->eventtype
=== 'site') {
2153 $this->editorcontext
= $this->properties
->context
;
2154 } else if ($properties->eventtype
=== 'user') {
2156 $this->editorcontext
= $this->properties
->context
;
2157 } else if ($properties->eventtype
=== 'group' ||
$properties->eventtype
=== 'course') {
2158 // First check the course is valid
2159 $course = $DB->get_record('course', array('id'=>$properties->courseid
));
2161 print_error('invalidcourse');
2164 $this->editorcontext
= $this->properties
->context
;
2165 // We have a course and are within the course context so we had
2166 // better use the courses max bytes value
2167 $this->editoroptions
['maxbytes'] = $course->maxbytes
;
2169 // If we get here we have a custom event type as used by some
2170 // modules. In this case the event will have been added by
2171 // code and we won't need the editor
2172 $this->editoroptions
['maxbytes'] = 0;
2173 $this->editoroptions
['maxfiles'] = 0;
2176 if (empty($this->editorcontext
) ||
empty($this->editorcontext
->id
)) {
2179 // Get the context id that is what we really want
2180 $contextid = $this->editorcontext
->id
;
2184 // If we get here then this is a new event in which case we don't need a
2185 // context as there is no existing files to copy to the draft area.
2189 // If the contextid === false we don't support files so no preparing
2191 if ($contextid !== false) {
2192 // Just encase it has already been submitted
2193 $draftiddescription = file_get_submitted_draft_itemid('description');
2194 // Prepare the draft area, this copies existing files to the draft area as well
2195 $properties->description
= file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id
, $this->editoroptions
, $properties->description
);
2197 $draftiddescription = 0;
2200 // Structure the description field as the editor requires
2201 $properties->description
= array('text'=>$properties->description
, 'format'=>$properties->format
, 'itemid'=>$draftiddescription);
2204 // Finally return the properties
2209 * Toggles the visibility of an event
2211 * @param null|bool $force If it is left null the events visibility is flipped,
2212 * If it is false the event is made hidden, if it is true it
2215 public function toggle_visibility($force=null) {
2218 // Set visible to the default if it is not already set
2219 if (empty($this->properties
->visible
)) {
2220 $this->properties
->visible
= 1;
2223 if ($force === true ||
($force !== false && $this->properties
->visible
== 0)) {
2224 // Make this event visible
2225 $this->properties
->visible
= 1;
2227 self
::calendar_event_hook('show_event', array($this->properties
));
2229 // Make this event hidden
2230 $this->properties
->visible
= 0;
2232 self
::calendar_event_hook('hide_event', array($this->properties
));
2235 // Update the database to reflect this change
2236 return $DB->set_field('event', 'visible', $this->properties
->visible
, array('id'=>$this->properties
->id
));
2240 * Attempts to call the hook for the specified action should a calendar type
2241 * by set $CFG->calendar, and the appopriate function defined
2244 * @staticvar bool $extcalendarinc Used to track the inclusion of the calendar lib
2245 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2246 * @param array $args The args to pass to the hook, usually the event is the first element
2249 public static function calendar_event_hook($action, array $args) {
2251 static $extcalendarinc;
2252 if ($extcalendarinc === null) {
2253 if (!empty($CFG->calendar
) && file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
2254 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
2255 $extcalendarinc = true;
2257 $extcalendarinc = false;
2260 if($extcalendarinc === false) {
2263 $hook = $CFG->calendar
.'_'.$action;
2264 if (function_exists($hook)) {
2265 call_user_func_array($hook, $args);
2272 * Returns a calendar_event object when provided with an event id
2274 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2275 * it will result in an exception being thrown
2277 * @param int|object $param
2278 * @return calendar_event|false
2280 public static function load($param) {
2282 if (is_object($param)) {
2283 $event = new calendar_event($param);
2285 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST
);
2286 $event = new calendar_event($event);
2292 * Creates a new event and returns a calendar_event object
2294 * @param object|array $properties An object containing event properties
2295 * @return calendar_event|false The event object or false if it failed
2297 public static function create($properties) {
2298 if (is_array($properties)) {
2299 $properties = (object)$properties;
2301 if (!is_object($properties)) {
2302 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2304 $event = new calendar_event($properties);
2305 if ($event->update($properties)) {
2314 * Calendar information class
2316 * This class is used simply to organise the information pertaining to a calendar
2317 * and is used primarily to make information easily available.
2319 class calendar_information
{
2340 public $courseid = null;
2342 * An array of courses
2345 public $courses = array();
2347 * An array of groups
2350 public $groups = array();
2355 public $users = array();
2358 * Creates a new instance
2364 public function __construct($day=0, $month=0, $year=0) {
2366 $date = usergetdate(time());
2369 $day = $date['mday'];
2372 if (empty($month)) {
2373 $month = $date['mon'];
2377 $year = $date['year'];
2381 $this->month
= $month;
2382 $this->year
= $year;
2387 * @param stdClass $course
2388 * @param array $coursestoload An array of courses [$course->id => $course]
2389 * @param type $ignorefilters
2391 public function prepare_for_view(stdClass
$course, array $coursestoload, $ignorefilters = false) {
2392 $this->courseid
= $course->id
;
2393 $this->course
= $course;
2394 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2395 $this->courses
= $courses;
2396 $this->groups
= $group;
2397 $this->users
= $user;
2401 * Ensures the date for the calendar is correct and either sets it to now
2402 * or throws a moodle_exception if not
2404 * @param bool $defaultonow
2407 public function checkdate($defaultonow = true) {
2408 if (!checkdate($this->month
, $this->day
, $this->year
)) {
2410 $now = usergetdate(time());
2411 $this->day
= intval($now['mday']);
2412 $this->month
= intval($now['mon']);
2413 $this->year
= intval($now['year']);
2416 throw new moodle_exception('invaliddate');
2422 * Gets todays timestamp for the calendar
2425 public function timestamp_today() {
2426 return make_timestamp($this->year
, $this->month
, $this->day
);
2429 * Gets tomorrows timestamp for the calendar
2432 public function timestamp_tomorrow() {
2433 return make_timestamp($this->year
, $this->month
, $this->day+
1);
2436 * Adds the pretend blocks for teh calendar
2438 * @param core_calendar_renderer $renderer
2439 * @param bool $showfilters
2440 * @param string|null $view
2442 public function add_sidecalendar_blocks(core_calendar_renderer
$renderer, $showfilters=false, $view=null) {
2444 $filters = new block_contents();
2445 $filters->content
= $renderer->fake_block_filters($this->courseid
, $this->day
, $this->month
, $this->year
, $view, $this->courses
);
2446 $filters->footer
= '';
2447 $filters->title
= get_string('eventskey', 'calendar');
2448 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT
);
2450 $block = new block_contents
;
2451 $block->content
= $renderer->fake_block_threemonths($this);
2452 $block->footer
= '';
2453 $block->title
= get_string('monthlyview', 'calendar');
2454 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT
);