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' => base64_encode($returnurl->out(false)), 'sesskey'=>sesskey()));
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 DISTINCT 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;
1450 $time = calendar_time_representation($event->timestart
);
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 = new stdClass();
1544 $allowed->user
= has_capability('moodle/calendar:manageownentries', get_system_context());
1545 $allowed->groups
= false; // This may change just below
1546 $allowed->courses
= false; // This may change just below
1547 $allowed->site
= has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE
, SITEID
));
1549 if (!empty($course)) {
1550 if (!is_object($course)) {
1551 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST
);
1553 if ($course->id
!= SITEID
) {
1554 $coursecontext = get_context_instance(CONTEXT_COURSE
, $course->id
);
1556 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1557 $allowed->courses
= array($course->id
=> 1);
1559 if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
1560 $allowed->groups
= groups_get_all_groups($course->id
);
1562 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1563 if($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
1564 $allowed->groups
= groups_get_all_groups($course->id
);
1572 * see if user can add calendar entries at all
1573 * used to print the "New Event" button
1576 function calendar_user_can_add_event($course) {
1577 if (!isloggedin() ||
isguestuser()) {
1580 calendar_get_allowed_types($allowed, $course);
1581 return (bool)($allowed->user ||
$allowed->groups ||
$allowed->courses ||
$allowed->site
);
1585 * Check wether the current user is permitted to add events
1587 * @param object $event
1590 function calendar_add_event_allowed($event) {
1593 // can not be using guest account
1594 if (!isloggedin() or isguestuser()) {
1598 $sitecontext = get_context_instance(CONTEXT_SYSTEM
);
1599 // if user has manageentries at site level, always return true
1600 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1604 switch ($event->eventtype
) {
1606 return has_capability('moodle/calendar:manageentries', $event->context
);
1609 // Allow users to add/edit group events if:
1610 // 1) They have manageentries (= entries for whole course)
1611 // 2) They have managegroupentries AND are in the group
1612 $group = $DB->get_record('groups', array('id'=>$event->groupid
));
1614 has_capability('moodle/calendar:manageentries', $event->context
) ||
1615 (has_capability('moodle/calendar:managegroupentries', $event->context
)
1616 && groups_is_member($event->groupid
)));
1619 if ($event->userid
== $USER->id
) {
1620 return (has_capability('moodle/calendar:manageownentries', $event->context
));
1622 //there is no 'break;' intentionally
1625 return has_capability('moodle/calendar:manageentries', $event->context
);
1628 return has_capability('moodle/calendar:manageentries', $event->context
);
1633 * A class to manage calendar events
1635 * This class provides the required functionality in order to manage calendar events.
1636 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1637 * better framework for dealing with calendar events in particular regard to file
1638 * handling through the new file API
1640 * @property int $id The id within the event table
1641 * @property string $name The name of the event
1642 * @property string $description The description of the event
1643 * @property int $format The format of the description FORMAT_?
1644 * @property int $courseid The course the event is associated with (0 if none)
1645 * @property int $groupid The group the event is associated with (0 if none)
1646 * @property int $userid The user the event is associated with (0 if none)
1647 * @property int $repeatid If this is a repeated event this will be set to the
1648 * id of the original
1649 * @property string $modulename If added by a module this will be the module name
1650 * @property int $instance If added by a module this will be the module instance
1651 * @property string $eventtype The event type
1652 * @property int $timestart The start time as a timestamp
1653 * @property int $timeduration The duration of the event in seconds
1654 * @property int $visible 1 if the event is visible
1655 * @property int $uuid ?
1656 * @property int $sequence ?
1657 * @property int $timemodified The time last modified as a timestamp
1659 class calendar_event
{
1662 * An object containing the event properties can be accessed via the
1663 * magic __get/set methods
1666 protected $properties = null;
1668 * The converted event discription with file paths resolved
1669 * This gets populated when someone requests description for the first time
1672 protected $_description = null;
1674 * The options to use with this description editor
1677 protected $editoroptions = array(
1679 'forcehttps'=>false,
1682 'trusttext'=>false);
1684 * The context to use with the description editor
1687 protected $editorcontext = null;
1690 * Instantiates a new event and optionally populates its properties with the
1693 * @param stdClass $data Optional. An object containing the properties to for
1696 public function __construct($data=null) {
1699 // First convert to object if it is not already (should either be object or assoc array)
1700 if (!is_object($data)) {
1701 $data = (object)$data;
1704 $this->editoroptions
['maxbytes'] = $CFG->maxbytes
;
1706 $data->eventrepeats
= 0;
1708 if (empty($data->id
)) {
1712 // Default to a user event
1713 if (empty($data->eventtype
)) {
1714 $data->eventtype
= 'user';
1717 // Default to the current user
1718 if (empty($data->userid
)) {
1719 $data->userid
= $USER->id
;
1722 if (!empty($data->timeduration
) && is_array($data->timeduration
)) {
1723 $data->timeduration
= make_timestamp($data->timeduration
['year'], $data->timeduration
['month'], $data->timeduration
['day'], $data->timeduration
['hour'], $data->timeduration
['minute']) - $data->timestart
;
1725 if (!empty($data->description
) && is_array($data->description
)) {
1726 $data->format
= $data->description
['format'];
1727 $data->description
= $data->description
['text'];
1728 } else if (empty($data->description
)) {
1729 $data->description
= '';
1730 $data->format
= editors_get_preferred_format();
1732 // Ensure form is defaulted correctly
1733 if (empty($data->format
)) {
1734 $data->format
= editors_get_preferred_format();
1737 if (empty($data->context
)) {
1738 $data->context
= $this->calculate_context($data);
1740 $this->properties
= $data;
1744 * Magic property method
1746 * Attempts to call a set_$key method if one exists otherwise falls back
1747 * to simply set the property
1749 * @param string $key
1750 * @param mixed $value
1752 public function __set($key, $value) {
1753 if (method_exists($this, 'set_'.$key)) {
1754 $this->{'set_'.$key}($value);
1756 $this->properties
->{$key} = $value;
1762 * Attempts to call a get_$key method to return the property and ralls over
1763 * to return the raw property
1768 public function __get($key) {
1769 if (method_exists($this, 'get_'.$key)) {
1770 return $this->{'get_'.$key}();
1772 if (!isset($this->properties
->{$key})) {
1773 throw new coding_exception('Undefined property requested');
1775 return $this->properties
->{$key};
1779 * Stupid PHP needs an isset magic method if you use the get magic method and
1780 * still want empty calls to work.... blah ~!
1782 * @param string $key
1785 public function __isset($key) {
1786 return !empty($this->properties
->{$key});
1790 * Calculate the context value needed for calendar_event.
1791 * Event's type can be determine by the available value store in $data
1792 * It is important to check for the existence of course/courseid to determine
1794 * Default value is set to CONTEXT_USER
1798 protected function calculate_context(stdClass
$data) {
1802 if (isset($data->courseid
) && $data->courseid
> 0) {
1803 $context = get_context_instance(CONTEXT_COURSE
, $data->courseid
);
1804 } else if (isset($data->course
) && $data->course
> 0) {
1805 $context = get_context_instance(CONTEXT_COURSE
, $data->course
);
1806 } else if (isset($data->groupid
) && $data->groupid
> 0) {
1807 $group = $DB->get_record('groups', array('id'=>$data->groupid
));
1808 $context = get_context_instance(CONTEXT_COURSE
, $group->courseid
);
1809 } else if (isset($data->userid
) && $data->userid
> 0 && $data->userid
== $USER->id
) {
1810 $context = get_context_instance(CONTEXT_USER
, $data->userid
);
1811 } else if (isset($data->userid
) && $data->userid
> 0 && $data->userid
!= $USER->id
&&
1812 isset($data->instance
) && $data->instance
> 0) {
1813 $cm = get_coursemodule_from_instance($data->modulename
, $data->instance
, 0, false, MUST_EXIST
);
1814 $context = get_context_instance(CONTEXT_COURSE
, $cm->course
);
1816 $context = get_context_instance(CONTEXT_USER
);
1823 * Returns an array of editoroptions for this event: Called by __get
1824 * Please use $blah = $event->editoroptions;
1827 protected function get_editoroptions() {
1828 return $this->editoroptions
;
1832 * Returns an event description: Called by __get
1833 * Please use $blah = $event->description;
1837 protected function get_description() {
1840 require_once($CFG->libdir
. '/filelib.php');
1842 if ($this->_description
=== null) {
1843 // Check if we have already resolved the context for this event
1844 if ($this->editorcontext
=== null) {
1845 // Switch on the event type to decide upon the appropriate context
1846 // to use for this event
1847 $this->editorcontext
= $this->properties
->context
;
1848 if ($this->properties
->eventtype
!= 'user' && $this->properties
->eventtype
!= 'course'
1849 && $this->properties
->eventtype
!= 'site' && $this->properties
->eventtype
!= 'group') {
1850 return clean_text($this->properties
->description
, $this->properties
->format
);
1854 // Work out the item id for the editor, if this is a repeated event then the files will
1855 // be associated with the original
1856 if (!empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
1857 $itemid = $this->properties
->repeatid
;
1859 $itemid = $this->properties
->id
;
1862 // Convert file paths in the description so that things display correctly
1863 $this->_description
= file_rewrite_pluginfile_urls($this->properties
->description
, 'pluginfile.php', $this->editorcontext
->id
, 'calendar', 'event_description', $itemid);
1864 // Clean the text so no nasties get through
1865 $this->_description
= clean_text($this->_description
, $this->properties
->format
);
1867 // Finally return the description
1868 return $this->_description
;
1872 * Return the number of repeat events there are in this events series
1876 public function count_repeats() {
1878 if (!empty($this->properties
->repeatid
)) {
1879 $this->properties
->eventrepeats
= $DB->count_records('event', array('repeatid'=>$this->properties
->repeatid
));
1880 // We don't want to count ourselves
1881 $this->properties
->eventrepeats
--;
1883 return $this->properties
->eventrepeats
;
1887 * Update or create an event within the database
1889 * Pass in a object containing the event properties and this function will
1890 * insert it into the database and deal with any associated files
1893 * @see update_event()
1895 * @param stdClass $data
1896 * @param boolean $checkcapability if moodle should check calendar managing capability or not
1898 public function update($data, $checkcapability=true) {
1899 global $CFG, $DB, $USER;
1901 foreach ($data as $key=>$value) {
1902 $this->properties
->$key = $value;
1905 $this->properties
->timemodified
= time();
1906 $usingeditor = (!empty($this->properties
->description
) && is_array($this->properties
->description
));
1908 if (empty($this->properties
->id
) ||
$this->properties
->id
< 1) {
1910 if ($checkcapability) {
1911 if (!calendar_add_event_allowed($this->properties
)) {
1912 print_error('nopermissiontoupdatecalendar');
1917 switch ($this->properties
->eventtype
) {
1919 $this->editorcontext
= $this->properties
->context
;
1920 $this->properties
->courseid
= 0;
1921 $this->properties
->groupid
= 0;
1922 $this->properties
->userid
= $USER->id
;
1925 $this->editorcontext
= $this->properties
->context
;
1926 $this->properties
->courseid
= SITEID
;
1927 $this->properties
->groupid
= 0;
1928 $this->properties
->userid
= $USER->id
;
1931 $this->editorcontext
= $this->properties
->context
;
1932 $this->properties
->groupid
= 0;
1933 $this->properties
->userid
= $USER->id
;
1936 $this->editorcontext
= $this->properties
->context
;
1937 $this->properties
->userid
= $USER->id
;
1940 // Ewww we should NEVER get here, but just incase we do lets
1942 $usingeditor = false;
1946 $editor = $this->properties
->description
;
1947 $this->properties
->format
= $this->properties
->description
['format'];
1948 $this->properties
->description
= $this->properties
->description
['text'];
1951 // Insert the event into the database
1952 $this->properties
->id
= $DB->insert_record('event', $this->properties
);
1955 $this->properties
->description
= file_save_draft_area_files(
1957 $this->editorcontext
->id
,
1959 'event_description',
1960 $this->properties
->id
,
1961 $this->editoroptions
,
1963 $this->editoroptions
['forcehttps']);
1965 $DB->set_field('event', 'description', $this->properties
->description
, array('id'=>$this->properties
->id
));
1968 // Log the event entry.
1969 add_to_log($this->properties
->courseid
, 'calendar', 'add', 'event.php?action=edit&id='.$this->properties
->id
, $this->properties
->name
);
1971 $repeatedids = array();
1973 if (!empty($this->properties
->repeat
)) {
1974 $this->properties
->repeatid
= $this->properties
->id
;
1975 $DB->set_field('event', 'repeatid', $this->properties
->repeatid
, array('id'=>$this->properties
->id
));
1977 $eventcopy = clone($this->properties
);
1978 unset($eventcopy->id
);
1980 for($i = 1; $i < $eventcopy->repeats
; $i++
) {
1982 $eventcopy->timestart
= ($eventcopy->timestart+WEEKSECS
) +
dst_offset_on($eventcopy->timestart
) - dst_offset_on($eventcopy->timestart+WEEKSECS
);
1984 // Get the event id for the log record.
1985 $eventcopyid = $DB->insert_record('event', $eventcopy);
1987 // If the context has been set delete all associated files
1989 $fs = get_file_storage();
1990 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description', $this->properties
->id
);
1991 foreach ($files as $file) {
1992 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
1996 $repeatedids[] = $eventcopyid;
1997 // Log the event entry.
1998 add_to_log($eventcopy->courseid
, 'calendar', 'add', 'event.php?action=edit&id='.$eventcopyid, $eventcopy->name
);
2002 // Hook for tracking added events
2003 self
::calendar_event_hook('add_event', array($this->properties
, $repeatedids));
2007 if ($checkcapability) {
2008 if(!calendar_edit_event_allowed($this->properties
)) {
2009 print_error('nopermissiontoupdatecalendar');
2014 if ($this->editorcontext
!== null) {
2015 $this->properties
->description
= file_save_draft_area_files(
2016 $this->properties
->description
['itemid'],
2017 $this->editorcontext
->id
,
2019 'event_description',
2020 $this->properties
->id
,
2021 $this->editoroptions
,
2022 $this->properties
->description
['text'],
2023 $this->editoroptions
['forcehttps']);
2025 $this->properties
->format
= $this->properties
->description
['format'];
2026 $this->properties
->description
= $this->properties
->description
['text'];
2030 $event = $DB->get_record('event', array('id'=>$this->properties
->id
));
2032 $updaterepeated = (!empty($this->properties
->repeatid
) && !empty($this->properties
->repeateditall
));
2034 if ($updaterepeated) {
2036 if ($this->properties
->timestart
!= $event->timestart
) {
2037 $timestartoffset = $this->properties
->timestart
- $event->timestart
;
2038 $sql = "UPDATE {event}
2041 timestart = timestart + ?,
2044 WHERE repeatid = ?";
2045 $params = array($this->properties
->name
, $this->properties
->description
, $timestartoffset, $this->properties
->timeduration
, time(), $event->repeatid
);
2047 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2048 $params = array($this->properties
->name
, $this->properties
->description
, $this->properties
->timeduration
, time(), $event->repeatid
);
2050 $DB->execute($sql, $params);
2052 // Log the event update.
2053 add_to_log($this->properties
->courseid
, 'calendar', 'edit all', 'event.php?action=edit&id='.$this->properties
->id
, $this->properties
->name
);
2055 $DB->update_record('event', $this->properties
);
2056 $event = calendar_event
::load($this->properties
->id
);
2057 $this->properties
= $event->properties();
2058 add_to_log($this->properties
->courseid
, 'calendar', 'edit', 'event.php?action=edit&id='.$this->properties
->id
, $this->properties
->name
);
2061 // Hook for tracking event updates
2062 self
::calendar_event_hook('update_event', array($this->properties
, $updaterepeated));
2068 * Deletes an event and if selected an repeated events in the same series
2070 * This function deletes an event, any associated events if $deleterepeated=true,
2071 * and cleans up any files associated with the events.
2073 * @see delete_event()
2075 * @param bool $deleterepeated
2078 public function delete($deleterepeated=false) {
2081 // If $this->properties->id is not set then something is wrong
2082 if (empty($this->properties
->id
)) {
2083 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER
);
2088 $DB->delete_records('event', array('id'=>$this->properties
->id
));
2090 // If the editor context hasn't already been set then set it now
2091 if ($this->editorcontext
=== null) {
2092 $this->editorcontext
= $this->properties
->context
;
2095 // If the context has been set delete all associated files
2096 if ($this->editorcontext
!== null) {
2097 $fs = get_file_storage();
2098 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description', $this->properties
->id
);
2099 foreach ($files as $file) {
2104 // Fire the event deleted hook
2105 self
::calendar_event_hook('delete_event', array($this->properties
->id
, $deleterepeated));
2107 // If we need to delete repeated events then we will fetch them all and delete one by one
2108 if ($deleterepeated && !empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
2109 // Get all records where the repeatid is the same as the event being removed
2110 $events = $DB->get_records('event', array('repeatid'=>$this->properties
->repeatid
));
2111 // For each of the returned events populate a calendar_event object and call delete
2112 // make sure the arg passed is false as we are already deleting all repeats
2113 foreach ($events as $event) {
2114 $event = new calendar_event($event);
2115 $event->delete(false);
2123 * Fetch all event properties
2125 * This function returns all of the events properties as an object and optionally
2126 * can prepare an editor for the description field at the same time. This is
2127 * designed to work when the properties are going to be used to set the default
2128 * values of a moodle forms form.
2130 * @param bool $prepareeditor If set to true a editor is prepared for use with
2131 * the mforms editor element. (for description)
2132 * @return stdClass Object containing event properties
2134 public function properties($prepareeditor=false) {
2135 global $USER, $CFG, $DB;
2137 // First take a copy of the properties. We don't want to actually change the
2138 // properties or we'd forever be converting back and forwards between an
2139 // editor formatted description and not
2140 $properties = clone($this->properties
);
2141 // Clean the description here
2142 $properties->description
= clean_text($properties->description
, $properties->format
);
2144 // If set to true we need to prepare the properties for use with an editor
2145 // and prepare the file area
2146 if ($prepareeditor) {
2148 // We may or may not have a property id. If we do then we need to work
2149 // out the context so we can copy the existing files to the draft area
2150 if (!empty($properties->id
)) {
2152 if ($properties->eventtype
=== 'site') {
2154 $this->editorcontext
= $this->properties
->context
;
2155 } else if ($properties->eventtype
=== 'user') {
2157 $this->editorcontext
= $this->properties
->context
;
2158 } else if ($properties->eventtype
=== 'group' ||
$properties->eventtype
=== 'course') {
2159 // First check the course is valid
2160 $course = $DB->get_record('course', array('id'=>$properties->courseid
));
2162 print_error('invalidcourse');
2165 $this->editorcontext
= $this->properties
->context
;
2166 // We have a course and are within the course context so we had
2167 // better use the courses max bytes value
2168 $this->editoroptions
['maxbytes'] = $course->maxbytes
;
2170 // If we get here we have a custom event type as used by some
2171 // modules. In this case the event will have been added by
2172 // code and we won't need the editor
2173 $this->editoroptions
['maxbytes'] = 0;
2174 $this->editoroptions
['maxfiles'] = 0;
2177 if (empty($this->editorcontext
) ||
empty($this->editorcontext
->id
)) {
2180 // Get the context id that is what we really want
2181 $contextid = $this->editorcontext
->id
;
2185 // If we get here then this is a new event in which case we don't need a
2186 // context as there is no existing files to copy to the draft area.
2190 // If the contextid === false we don't support files so no preparing
2192 if ($contextid !== false) {
2193 // Just encase it has already been submitted
2194 $draftiddescription = file_get_submitted_draft_itemid('description');
2195 // Prepare the draft area, this copies existing files to the draft area as well
2196 $properties->description
= file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id
, $this->editoroptions
, $properties->description
);
2198 $draftiddescription = 0;
2201 // Structure the description field as the editor requires
2202 $properties->description
= array('text'=>$properties->description
, 'format'=>$properties->format
, 'itemid'=>$draftiddescription);
2205 // Finally return the properties
2210 * Toggles the visibility of an event
2212 * @param null|bool $force If it is left null the events visibility is flipped,
2213 * If it is false the event is made hidden, if it is true it
2216 public function toggle_visibility($force=null) {
2219 // Set visible to the default if it is not already set
2220 if (empty($this->properties
->visible
)) {
2221 $this->properties
->visible
= 1;
2224 if ($force === true ||
($force !== false && $this->properties
->visible
== 0)) {
2225 // Make this event visible
2226 $this->properties
->visible
= 1;
2228 self
::calendar_event_hook('show_event', array($this->properties
));
2230 // Make this event hidden
2231 $this->properties
->visible
= 0;
2233 self
::calendar_event_hook('hide_event', array($this->properties
));
2236 // Update the database to reflect this change
2237 return $DB->set_field('event', 'visible', $this->properties
->visible
, array('id'=>$this->properties
->id
));
2241 * Attempts to call the hook for the specified action should a calendar type
2242 * by set $CFG->calendar, and the appopriate function defined
2245 * @staticvar bool $extcalendarinc Used to track the inclusion of the calendar lib
2246 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2247 * @param array $args The args to pass to the hook, usually the event is the first element
2250 public static function calendar_event_hook($action, array $args) {
2252 static $extcalendarinc;
2253 if ($extcalendarinc === null) {
2254 if (!empty($CFG->calendar
) && file_exists($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
2255 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
2256 $extcalendarinc = true;
2258 $extcalendarinc = false;
2261 if($extcalendarinc === false) {
2264 $hook = $CFG->calendar
.'_'.$action;
2265 if (function_exists($hook)) {
2266 call_user_func_array($hook, $args);
2273 * Returns a calendar_event object when provided with an event id
2275 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2276 * it will result in an exception being thrown
2278 * @param int|object $param
2279 * @return calendar_event|false
2281 public static function load($param) {
2283 if (is_object($param)) {
2284 $event = new calendar_event($param);
2286 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST
);
2287 $event = new calendar_event($event);
2293 * Creates a new event and returns a calendar_event object
2295 * @param object|array $properties An object containing event properties
2296 * @return calendar_event|false The event object or false if it failed
2298 public static function create($properties) {
2299 if (is_array($properties)) {
2300 $properties = (object)$properties;
2302 if (!is_object($properties)) {
2303 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2305 $event = new calendar_event($properties);
2306 if ($event->update($properties)) {
2315 * Calendar information class
2317 * This class is used simply to organise the information pertaining to a calendar
2318 * and is used primarily to make information easily available.
2320 class calendar_information
{
2341 public $courseid = null;
2343 * An array of courses
2346 public $courses = array();
2348 * An array of groups
2351 public $groups = array();
2356 public $users = array();
2359 * Creates a new instance
2365 public function __construct($day=0, $month=0, $year=0) {
2367 $date = usergetdate(time());
2370 $day = $date['mday'];
2373 if (empty($month)) {
2374 $month = $date['mon'];
2378 $year = $date['year'];
2382 $this->month
= $month;
2383 $this->year
= $year;
2388 * @param stdClass $course
2389 * @param array $coursestoload An array of courses [$course->id => $course]
2390 * @param type $ignorefilters
2392 public function prepare_for_view(stdClass
$course, array $coursestoload, $ignorefilters = false) {
2393 $this->courseid
= $course->id
;
2394 $this->course
= $course;
2395 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2396 $this->courses
= $courses;
2397 $this->groups
= $group;
2398 $this->users
= $user;
2402 * Ensures the date for the calendar is correct and either sets it to now
2403 * or throws a moodle_exception if not
2405 * @param bool $defaultonow
2408 public function checkdate($defaultonow = true) {
2409 if (!checkdate($this->month
, $this->day
, $this->year
)) {
2411 $now = usergetdate(time());
2412 $this->day
= intval($now['mday']);
2413 $this->month
= intval($now['mon']);
2414 $this->year
= intval($now['year']);
2417 throw new moodle_exception('invaliddate');
2423 * Gets todays timestamp for the calendar
2426 public function timestamp_today() {
2427 return make_timestamp($this->year
, $this->month
, $this->day
);
2430 * Gets tomorrows timestamp for the calendar
2433 public function timestamp_tomorrow() {
2434 return make_timestamp($this->year
, $this->month
, $this->day+
1);
2437 * Adds the pretend blocks for teh calendar
2439 * @param core_calendar_renderer $renderer
2440 * @param bool $showfilters
2441 * @param string|null $view
2443 public function add_sidecalendar_blocks(core_calendar_renderer
$renderer, $showfilters=false, $view=null) {
2445 $filters = new block_contents();
2446 $filters->content
= $renderer->fake_block_filters($this->courseid
, $this->day
, $this->month
, $this->year
, $view, $this->courses
);
2447 $filters->footer
= '';
2448 $filters->title
= get_string('eventskey', 'calendar');
2449 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT
);
2451 $block = new block_contents
;
2452 $block->content
= $renderer->fake_block_threemonths($this);
2453 $block->footer
= '';
2454 $block->title
= get_string('monthlyview', 'calendar');
2455 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT
);