2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
20 * @package core_calendar
21 * @copyright 2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 * These are read by the administration component to provide default values
31 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
33 define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
36 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
38 define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
41 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
43 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
49 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
51 define('CALENDAR_DEFAULT_WEEKEND', 65);
54 * CALENDAR_URL - path to calendar's folder
56 define('CALENDAR_URL', $CFG->wwwroot
.'/calendar/');
59 * CALENDAR_TF_24 - Calendar time in 24 hours format
61 define('CALENDAR_TF_24', '%H:%M');
64 * CALENDAR_TF_12 - Calendar time in 12 hours format
66 define('CALENDAR_TF_12', '%I:%M %p');
69 * CALENDAR_EVENT_GLOBAL - Global calendar event types
71 define('CALENDAR_EVENT_GLOBAL', 1);
74 * CALENDAR_EVENT_COURSE - Course calendar event types
76 define('CALENDAR_EVENT_COURSE', 2);
79 * CALENDAR_EVENT_GROUP - group calendar event types
81 define('CALENDAR_EVENT_GROUP', 4);
84 * CALENDAR_EVENT_USER - user calendar event types
86 define('CALENDAR_EVENT_USER', 8);
90 * Return the days of the week
92 * @return array array of days
94 function calendar_get_days() {
95 return array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday');
99 * Gets the first day of the week
101 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
105 function calendar_get_starting_weekday() {
108 if (isset($CFG->calendar_startwday
)) {
109 $firstday = $CFG->calendar_startwday
;
111 $firstday = get_string('firstdayofweek', 'langconfig');
114 if(!is_numeric($firstday)) {
115 return CALENDAR_DEFAULT_STARTING_WEEKDAY
;
117 return intval($firstday) %
7;
122 * Generates the HTML for a miniature calendar
124 * @param array $courses list of course
125 * @param array $groups list of group
126 * @param array $users user's info
127 * @param int $cal_month calendar month in numeric, default is set to false
128 * @param int $cal_year calendar month in numeric, default is set to false
129 * @return string $content return html table for mini calendar
131 function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
132 global $CFG, $USER, $OUTPUT;
134 $display = new stdClass
;
135 $display->minwday
= get_user_preferences('calendar_startwday', calendar_get_starting_weekday());
136 $display->maxwday
= $display->minwday +
6;
140 if(!empty($cal_month) && !empty($cal_year)) {
141 $thisdate = usergetdate(time()); // Date and time the user sees at his location
142 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
143 // Navigated to this month
145 $display->thismonth
= true;
147 // Navigated to other month, let's do a nice trick and save us a lot of work...
148 if(!checkdate($cal_month, 1, $cal_year)) {
149 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
150 $display->thismonth
= true;
152 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
153 $display->thismonth
= false;
157 $date = usergetdate(time()); // Date and time the user sees at his location
158 $display->thismonth
= true;
161 // Fill in the variables we 're going to use, nice and tidy
162 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
163 $display->maxdays
= calendar_days_in_month($m, $y);
165 if (get_user_timezone_offset() < 99) {
166 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
167 $display->tstart
= gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
168 $display->tend
= gmmktime(23, 59, 59, $m, $display->maxdays
, $y); // GMT
170 // no timezone info specified
171 $display->tstart
= mktime(0, 0, 0, $m, 1, $y);
172 $display->tend
= mktime(23, 59, 59, $m, $display->maxdays
, $y);
175 $startwday = dayofweek(1, $m, $y);
177 // Align the starting weekday to fall in our display range
178 // This is simple, not foolproof.
179 if($startwday < $display->minwday
) {
183 // TODO: THIS IS TEMPORARY CODE!
184 // [pj] I was just reading through this and realized that I when writing this code I was probably
185 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
186 // make_timestamp would accomplish the same thing. So here goes a test:
187 //$test_start = make_timestamp($y, $m, 1);
188 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
189 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
190 //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);
192 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
193 //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);
197 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
198 $events = calendar_get_events(
199 usertime($display->tstart
) - dst_offset_on($display->tstart
),
200 usertime($display->tend
) - dst_offset_on($display->tend
),
201 $users, $groups, $courses);
203 // Set event course class for course events
204 if (!empty($events)) {
205 foreach ($events as $eventid => $event) {
206 if (!empty($event->modulename
)) {
207 $cm = get_coursemodule_from_instance($event->modulename
, $event->instance
);
208 if (!groups_course_module_visible($cm)) {
209 unset($events[$eventid]);
215 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
216 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
217 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
218 // arguments to this function.
220 $hrefparams = array();
221 if(!empty($courses)) {
222 $courses = array_diff($courses, array(SITEID
));
223 if(count($courses) == 1) {
224 $hrefparams['course'] = reset($courses);
228 // We want to have easy access by day, since the display is on a per-day basis.
229 // Arguments passed by reference.
230 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
231 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
233 //Accessibility: added summary and <abbr> elements.
234 $days_title = calendar_get_days();
236 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
237 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table
238 $content .= '<tr class="weekdays">'; // Header row: day names
240 // Print out the names of the weekdays
241 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
242 for($i = $display->minwday
; $i <= $display->maxwday
; ++
$i) {
243 // This uses the % operator to get the correct weekday no matter what shift we have
244 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
245 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i %
7], 'calendar') .'">'.
246 get_string($days[$i %
7], 'calendar') ."</abbr></th>\n";
249 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
251 // For the table display. $week is the row; $dayweek is the column.
252 $dayweek = $startwday;
254 // Paddding (the first week may have blank days in the beginning)
255 for($i = $display->minwday
; $i < $startwday; ++
$i) {
256 $content .= '<td class="dayblank"> </td>'."\n";
259 $weekend = CALENDAR_DEFAULT_WEEKEND
;
260 if (isset($CFG->calendar_weekend
)) {
261 $weekend = intval($CFG->calendar_weekend
);
264 // Now display all the calendar
265 for($day = 1; $day <= $display->maxdays
; ++
$day, ++
$dayweek) {
266 if($dayweek > $display->maxwday
) {
267 // We need to change week (table row)
268 $content .= '</tr><tr>';
269 $dayweek = $display->minwday
;
274 if ($weekend & (1 << ($dayweek %
7))) {
275 // Weekend. This is true no matter what the exact range is.
276 $class = 'weekend day';
278 // Normal working day.
282 // Special visual fx if an event is defined
283 if(isset($eventsbyday[$day])) {
284 $class .= ' hasevent';
285 $hrefparams['view'] = 'day';
286 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $hrefparams), $day, $m, $y);
289 foreach($eventsbyday[$day] as $eventid) {
290 if (!isset($events[$eventid])) {
293 $event = $events[$eventid];
295 $component = 'moodle';
296 if(!empty($event->modulename
)) {
298 $popupalt = $event->modulename
;
299 $component = $event->modulename
;
300 } else if ($event->courseid
== SITEID
) { // Site event
301 $popupicon = 'c/site';
302 } else if ($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) { // Course event
303 $popupicon = 'c/course';
304 } else if ($event->groupid
) { // Group event
305 $popupicon = 'c/group';
306 } else if ($event->userid
) { // User event
307 $popupicon = 'c/user';
310 $dayhref->set_anchor('event_'.$event->id
);
312 $popupcontent .= html_writer
::start_tag('div');
313 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
314 $popupcontent .= html_writer
::link($dayhref, format_string($event->name
, true));
315 $popupcontent .= html_writer
::end_tag('div');
318 //Accessibility: functionality moved to calendar_get_popup.
319 if($display->thismonth
&& $day == $d) {
320 $popupid = calendar_get_popup(true, $events[$eventid]->timestart
, $popupcontent);
322 $popupid = calendar_get_popup(false, $events[$eventid]->timestart
, $popupcontent);
325 // Class and cell content
326 if(isset($typesbyday[$day]['startglobal'])) {
327 $class .= ' calendar_event_global';
328 } else if(isset($typesbyday[$day]['startcourse'])) {
329 $class .= ' calendar_event_course';
330 } else if(isset($typesbyday[$day]['startgroup'])) {
331 $class .= ' calendar_event_group';
332 } else if(isset($typesbyday[$day]['startuser'])) {
333 $class .= ' calendar_event_user';
335 $cell = html_writer
::link((string)$dayhref, $day, array('aria-controls' => $popupid.'_panel', 'id' => $popupid));
340 $durationclass = false;
341 if (isset($typesbyday[$day]['durationglobal'])) {
342 $durationclass = ' duration_global';
343 } else if(isset($typesbyday[$day]['durationcourse'])) {
344 $durationclass = ' duration_course';
345 } else if(isset($typesbyday[$day]['durationgroup'])) {
346 $durationclass = ' duration_group';
347 } else if(isset($typesbyday[$day]['durationuser'])) {
348 $durationclass = ' duration_user';
350 if ($durationclass) {
351 $class .= ' duration '.$durationclass;
354 // If event has a class set then add it to the table day <td> tag
355 // Note: only one colour for minicalendar
356 if(isset($eventsbyday[$day])) {
357 foreach($eventsbyday[$day] as $eventid) {
358 if (!isset($events[$eventid])) {
361 $event = $events[$eventid];
362 if (!empty($event->class)) {
363 $class .= ' '.$event->class;
369 // Special visual fx for today
370 //Accessibility: hidden text for today, and popup.
371 if($display->thismonth
&& $day == $d) {
373 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
375 if(! isset($eventsbyday[$day])) {
376 $class .= ' eventnone';
377 $popupid = calendar_get_popup(true, false);
378 $cell = html_writer
::link('#', $day, array('aria-controls' => $popupid.'_panel', 'id' => $popupid));;
380 $cell = get_accesshide($today.' ').$cell;
385 $class = ' class="'.$class.'"';
387 $content .= '<td'.$class.'>'.$cell."</td>\n";
390 // Paddding (the last week may have blank days at the end)
391 for($i = $dayweek; $i <= $display->maxwday
; ++
$i) {
392 $content .= '<td class="dayblank"> </td>';
394 $content .= '</tr>'; // Last row ends
396 $content .= '</table>'; // Tabular display of days ends
402 * Gets the calendar popup
404 * It called at multiple points in from calendar_get_mini.
405 * Copied and modified from calendar_get_mini.
407 * @param bool $is_today false except when called on the current day.
408 * @param mixed $event_timestart $events[$eventid]->timestart, OR false if there are no events.
409 * @param string $popupcontent content for the popup window/layout.
410 * @return string eventid for the calendar_tooltip popup window/layout.
412 function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
415 if ($popupcount === null) {
420 $popupcaption = get_string('today', 'calendar').' ';
422 if (false === $event_timestart) {
423 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
424 $popupcontent = get_string('eventnone', 'calendar');
427 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
429 $id = 'calendar_tooltip_'.$popupcount;
430 $PAGE->requires
->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
437 * Gets the calendar upcoming event
439 * @param array $courses array of courses
440 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
441 * @param array|int|bool $users array of users, user id or boolean for all/no user events
442 * @param int $daysinfuture number of days in the future we 'll look
443 * @param int $maxevents maximum number of events
444 * @param int $fromtime start time
445 * @return array $output array of upcoming events
447 function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
448 global $CFG, $COURSE, $DB;
450 $display = new stdClass
;
451 $display->range
= $daysinfuture; // How many days in the future we 'll look
452 $display->maxevents
= $maxevents;
456 // Prepare "course caching", since it may save us a lot of queries
457 $coursecache = array();
460 $now = time(); // We 'll need this later
461 $usermidnighttoday = usergetmidnight($now);
464 $display->tstart
= $fromtime;
466 $display->tstart
= $usermidnighttoday;
469 // This works correctly with respect to the user's DST, but it is accurate
470 // only because $fromtime is always the exact midnight of some day!
471 $display->tend
= usergetmidnight($display->tstart + DAYSECS
* $display->range +
3 * HOURSECS
) - 1;
473 // Get the events matching our criteria
474 $events = calendar_get_events($display->tstart
, $display->tend
, $users, $groups, $courses);
476 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
477 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
478 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
479 // arguments to this function.
481 $hrefparams = array();
482 if(!empty($courses)) {
483 $courses = array_diff($courses, array(SITEID
));
484 if(count($courses) == 1) {
485 $hrefparams['course'] = reset($courses);
489 if ($events !== false) {
491 $modinfo = get_fast_modinfo($COURSE);
493 foreach($events as $event) {
496 if (!empty($event->modulename
)) {
497 if ($event->courseid
== $COURSE->id
) {
498 if (isset($modinfo->instances
[$event->modulename
][$event->instance
])) {
499 $cm = $modinfo->instances
[$event->modulename
][$event->instance
];
500 if (!$cm->uservisible
) {
505 if (!$cm = get_coursemodule_from_instance($event->modulename
, $event->instance
)) {
508 if (!coursemodule_visible_for_user($cm)) {
512 if ($event->modulename
== 'assignment'){
513 // create calendar_event to test edit_event capability
514 // this new event will also prevent double creation of calendar_event object
515 $checkevent = new calendar_event($event);
516 // TODO: rewrite this hack somehow
517 if (!calendar_edit_event_allowed($checkevent)){ // cannot manage entries, eg. student
518 if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance
))) {
519 // print_error("invalidid", 'assignment');
522 // assign assignment to assignment object to use hidden_is_hidden method
523 require_once($CFG->dirroot
.'/mod/assignment/lib.php');
525 if (!file_exists($CFG->dirroot
.'/mod/assignment/type/'.$assignment->assignmenttype
.'/assignment.class.php')) {
528 require_once ($CFG->dirroot
.'/mod/assignment/type/'.$assignment->assignmenttype
.'/assignment.class.php');
530 $assignmentclass = 'assignment_'.$assignment->assignmenttype
;
531 $assignmentinstance = new $assignmentclass($cm->id
, $assignment, $cm);
533 if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
534 $event->description
= get_string('notavailableyet', 'assignment');
540 if ($processed >= $display->maxevents
) {
544 $event->time
= calendar_format_event_time($event, $now, $hrefparams);
553 * Add calendar event metadata
555 * @param stdClass $event event info
556 * @return stdClass $event metadata
558 function calendar_add_event_metadata($event) {
559 global $CFG, $OUTPUT;
561 //Support multilang in event->name
562 $event->name
= format_string($event->name
,true);
564 if(!empty($event->modulename
)) { // Activity event
565 // The module name is set. I will assume that it has to be displayed, and
566 // also that it is an automatically-generated event. And of course that the
567 // fields for get_coursemodule_from_instance are set correctly.
568 $module = calendar_get_module_cached($coursecache, $event->modulename
, $event->instance
);
570 if ($module === false) {
574 $modulename = get_string('modulename', $event->modulename
);
575 if (get_string_manager()->string_exists($event->eventtype
, $event->modulename
)) {
576 // will be used as alt text if the event icon
577 $eventtype = get_string($event->eventtype
, $event->modulename
);
581 $icon = $OUTPUT->pix_url('icon', $event->modulename
) . '';
583 $context = context_course
::instance($module->course
);
584 $fullname = format_string($coursecache[$module->course
]->fullname
, true, array('context' => $context));
586 $event->icon
= '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
587 $event->referer
= '<a href="'.$CFG->wwwroot
.'/mod/'.$event->modulename
.'/view.php?id='.$module->id
.'">'.$event->name
.'</a>';
588 $event->courselink
= '<a href="'.$CFG->wwwroot
.'/course/view.php?id='.$module->course
.'">'.$fullname.'</a>';
589 $event->cmid
= $module->id
;
592 } else if($event->courseid
== SITEID
) { // Site event
593 $event->icon
= '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/site') . '" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
594 $event->cssclass
= 'calendar_event_global';
595 } else if($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) { // Course event
596 calendar_get_course_cached($coursecache, $event->courseid
);
598 $context = context_course
::instance($event->courseid
);
599 $fullname = format_string($coursecache[$event->courseid
]->fullname
, true, array('context' => $context));
601 $event->icon
= '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/course') . '" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
602 $event->courselink
= '<a href="'.$CFG->wwwroot
.'/course/view.php?id='.$event->courseid
.'">'.$fullname.'</a>';
603 $event->cssclass
= 'calendar_event_course';
604 } else if ($event->groupid
) { // Group event
605 $event->icon
= '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/group') . '" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
606 $event->cssclass
= 'calendar_event_group';
607 } else if($event->userid
) { // User event
608 $event->icon
= '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/user') . '" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
609 $event->cssclass
= 'calendar_event_user';
615 * Get calendar events
617 * @param int $tstart Start time of time range for events
618 * @param int $tend End time of time range for events
619 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
620 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
621 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
622 * @param boolean $withduration whether only events starting within time range selected
623 * or events in progress/already started selected as well
624 * @param boolean $ignorehidden whether to select only visible events or all events
625 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
627 function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
632 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
636 if(is_array($users) && !empty($users)) {
637 // Events from a number of users
638 if(!empty($whereclause)) $whereclause .= ' OR';
639 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
640 } else if(is_numeric($users)) {
641 // Events from one user
642 if(!empty($whereclause)) $whereclause .= ' OR';
643 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
644 } else if($users === true) {
645 // Events from ALL users
646 if(!empty($whereclause)) $whereclause .= ' OR';
647 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
648 } else if($users === false) {
649 // No user at all, do nothing
652 if(is_array($groups) && !empty($groups)) {
653 // Events from a number of groups
654 if(!empty($whereclause)) $whereclause .= ' OR';
655 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
656 } else if(is_numeric($groups)) {
657 // Events from one group
658 if(!empty($whereclause)) $whereclause .= ' OR ';
659 $whereclause .= ' groupid = '.$groups;
660 } else if($groups === true) {
661 // Events from ALL groups
662 if(!empty($whereclause)) $whereclause .= ' OR ';
663 $whereclause .= ' groupid != 0';
665 // boolean false (no groups at all): we don't need to do anything
667 if(is_array($courses) && !empty($courses)) {
668 if(!empty($whereclause)) {
669 $whereclause .= ' OR';
671 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
672 } else if(is_numeric($courses)) {
674 if(!empty($whereclause)) $whereclause .= ' OR';
675 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
676 } else if ($courses === true) {
677 // Events from ALL courses
678 if(!empty($whereclause)) $whereclause .= ' OR';
679 $whereclause .= ' (groupid = 0 AND courseid != 0)';
682 // Security check: if, by now, we have NOTHING in $whereclause, then it means
683 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
684 // events no matter what. Allowing the code to proceed might return a completely
685 // valid query with only time constraints, thus selecting ALL events in that time frame!
686 if(empty($whereclause)) {
691 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
694 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
696 if(!empty($whereclause)) {
697 // We have additional constraints
698 $whereclause = $timeclause.' AND ('.$whereclause.')';
701 // Just basic time filtering
702 $whereclause = $timeclause;
706 $whereclause .= ' AND visible = 1';
709 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
710 if ($events === false) {
717 * Get control options for Calendar
719 * @param string $type of calendar
720 * @param array $data calendar information
721 * @return string $content return available control for the calender in html
723 function calendar_top_controls($type, $data) {
726 if(!isset($data['d'])) {
730 // Ensure course id passed if relevant
731 // Required due to changes in view/lib.php mainly (calendar_session_vars())
733 if (!empty($data['id'])) {
734 $courseid = '&course='.$data['id'];
737 if(!checkdate($data['m'], $data['d'], $data['y'])) {
741 $time = make_timestamp($data['y'], $data['m'], $data['d']);
743 $date = usergetdate($time);
745 $data['m'] = $date['mon'];
746 $data['y'] = $date['year'];
748 //Accessibility: calendar block controls, replaced <table> with <div>.
749 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
750 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
754 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
755 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
756 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
757 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
759 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
760 if (!empty($data['id'])) {
761 $calendarlink->param('course', $data['id']);
764 if (right_to_left()) {
772 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
773 $content .= $left.'<span class="hide"> | </span>';
774 $content .= html_writer
::tag('span', html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
775 $content .= '<span class="hide"> | </span>'. $right;
776 $content .= "<span class=\"clearer\"><!-- --></span>\n";
777 $content .= html_writer
::end_tag('div');
781 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
782 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
783 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&', 0, $nextmonth, $nextyear, $accesshide=true);
784 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&', 0, $prevmonth, $prevyear, true);
786 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
787 if (!empty($data['id'])) {
788 $calendarlink->param('course', $data['id']);
791 if (right_to_left()) {
799 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
800 $content .= $left.'<span class="hide"> | </span>';
801 $content .= html_writer
::tag('span', html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
802 $content .= '<span class="hide"> | </span>'. $right;
803 $content .= "<span class=\"clearer\"><!-- --></span>";
804 $content .= html_writer
::end_tag('div');
807 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view'=>'upcoming')), 1, $data['m'], $data['y']);
808 if (!empty($data['id'])) {
809 $calendarlink->param('course', $data['id']);
811 $calendarlink = html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
812 $content .= html_writer
::tag('div', $calendarlink, array('class'=>'centered'));
815 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', array('view'=>'month')), 1, $data['m'], $data['y']);
816 if (!empty($data['id'])) {
817 $calendarlink->param('course', $data['id']);
819 $calendarlink = html_writer
::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
820 $content .= html_writer
::tag('h3', $calendarlink);
823 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
824 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
825 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
826 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
827 $prevlink = calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&', 1, $prevmonth, $prevyear);
828 $nextlink = calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&', 1, $nextmonth, $nextyear);
830 if (right_to_left()) {
838 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
839 $content .= $left . '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>";
840 $content .= '<span class="hide"> | </span>' . $right;
841 $content .= '<span class="clearer"><!-- --></span>';
842 $content .= html_writer
::end_tag('div')."\n";
845 $days = calendar_get_days();
846 $data['d'] = $date['mday']; // Just for convenience
847 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
848 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] +
1));
849 $prevname = calendar_wday_name($days[$prevdate['wday']]);
850 $nextname = calendar_wday_name($days[$nextdate['wday']]);
851 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
852 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
854 if (right_to_left()) {
862 $content .= html_writer
::start_tag('div', array('class'=>'calendar-controls'));
864 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
865 $content .= '<span class="hide"> | </span>'. $right;
866 $content .= "<span class=\"clearer\"><!-- --></span>";
867 $content .= html_writer
::end_tag('div')."\n";
875 * Formats a filter control element.
877 * @param moodle_url $url of the filter
878 * @param int $type constant defining the type filter
879 * @return string html content of the element
881 function calendar_filter_controls_element(moodle_url
$url, $type) {
884 case CALENDAR_EVENT_GLOBAL
:
885 $typeforhumans = 'global';
886 $class = 'calendar_event_global';
888 case CALENDAR_EVENT_COURSE
:
889 $typeforhumans = 'course';
890 $class = 'calendar_event_course';
892 case CALENDAR_EVENT_GROUP
:
893 $typeforhumans = 'groups';
894 $class = 'calendar_event_group';
896 case CALENDAR_EVENT_USER
:
897 $typeforhumans = 'user';
898 $class = 'calendar_event_user';
901 if (calendar_show_event_type($type)) {
902 $icon = $OUTPUT->pix_icon('t/hide', get_string('hide'));
903 $str = get_string('hide'.$typeforhumans.'events', 'calendar');
905 $icon = $OUTPUT->pix_icon('t/show', get_string('show'));
906 $str = get_string('show'.$typeforhumans.'events', 'calendar');
908 $content = html_writer
::start_tag('li', array('class' => 'calendar_event'));
909 $content .= html_writer
::start_tag('a', array('href' => $url));
910 $content .= html_writer
::tag('span', $icon, array('class' => $class));
911 $content .= html_writer
::tag('span', $str, array('class' => 'eventname'));
912 $content .= html_writer
::end_tag('a');
913 $content .= html_writer
::end_tag('li');
918 * Get the controls filter for calendar.
920 * Filter is used to hide calendar info from the display page
922 * @param moodle_url $returnurl return-url for filter controls
923 * @return string $content return filter controls in html
925 function calendar_filter_controls(moodle_url
$returnurl) {
926 global $CFG, $USER, $OUTPUT;
929 $id = optional_param( 'id',0,PARAM_INT
);
930 $seturl = new moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out(false)), 'sesskey'=>sesskey()));
931 $content = html_writer
::start_tag('ul');
933 $seturl->param('var', 'showglobal');
934 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GLOBAL
);
936 $seturl->param('var', 'showcourses');
937 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_COURSE
);
939 if (isloggedin() && !isguestuser()) {
941 // This course MIGHT have group events defined, so show the filter
942 $seturl->param('var', 'showgroups');
943 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GROUP
);
945 // This course CANNOT have group events, so lose the filter
947 $seturl->param('var', 'showuser');
948 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_USER
);
950 $content .= html_writer
::end_tag('ul');
956 * Return the representation day
958 * @param int $tstamp Timestamp in GMT
959 * @param int $now current Unix timestamp
960 * @param bool $usecommonwords
961 * @return string the formatted date/time
963 function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
966 if(empty($shortformat)) {
967 $shortformat = get_string('strftimedayshort');
974 // To have it in one place, if a change is needed
975 $formal = userdate($tstamp, $shortformat);
977 $datestamp = usergetdate($tstamp);
978 $datenow = usergetdate($now);
980 if($usecommonwords == false) {
981 // We don't want words, just a date
984 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
986 return get_string('today', 'calendar');
989 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
990 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
993 return get_string('yesterday', 'calendar');
996 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] +
1 ) ||
997 ($datestamp['year'] == $datenow['year'] +
1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
1000 return get_string('tomorrow', 'calendar');
1008 * return the formatted representation time
1010 * @param int $time the timestamp in UTC, as obtained from the database
1011 * @return string the formatted date/time
1013 function calendar_time_representation($time) {
1014 static $langtimeformat = NULL;
1015 if($langtimeformat === NULL) {
1016 $langtimeformat = get_string('strftimetime');
1018 $timeformat = get_user_preferences('calendar_timeformat');
1019 if(empty($timeformat)){
1020 $timeformat = get_config(NULL,'calendar_site_timeformat');
1022 // The ? is needed because the preference might be present, but empty
1023 return userdate($time, empty($timeformat) ?
$langtimeformat : $timeformat);
1027 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1029 * @param string|moodle_url $linkbase
1030 * @param int $d The number of the day.
1031 * @param int $m The number of the month.
1032 * @param int $y The number of the year.
1033 * @return moodle_url|null $linkbase
1035 function calendar_get_link_href($linkbase, $d, $m, $y) {
1036 if (empty($linkbase)) {
1039 if (!($linkbase instanceof moodle_url
)) {
1040 $linkbase = new moodle_url();
1043 $linkbase->param('cal_d', $d);
1046 $linkbase->param('cal_m', $m);
1049 $linkbase->param('cal_y', $y);
1055 * Build and return a previous month HTML link, with an arrow.
1057 * @param string $text The text label.
1058 * @param string|moodle_url $linkbase The URL stub.
1059 * @param int $d The number of the date.
1060 * @param int $m The number of the month.
1061 * @param int $y year The number of the year.
1062 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1063 * @return string HTML string.
1065 function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
1066 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1070 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
1074 * Build and return a next month HTML link, with an arrow.
1076 * @param string $text The text label.
1077 * @param string|moodle_url $linkbase The URL stub.
1078 * @param int $d the number of the Day
1079 * @param int $m The number of the month.
1080 * @param int $y The number of the year.
1081 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1082 * @return string HTML string.
1084 function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
1085 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y);
1089 return link_arrow_right($text, (string)$href, $accesshide, 'next');
1093 * Return the name of the weekday
1095 * @param string $englishname
1096 * @return string of the weekeday
1098 function calendar_wday_name($englishname) {
1099 return get_string(strtolower($englishname), 'calendar');
1103 * Return the number of days in month
1105 * @param int $month the number of the month.
1106 * @param int $year the number of the year
1109 function calendar_days_in_month($month, $year) {
1110 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
1114 * Get the upcoming event block
1116 * @param array $events list of events
1117 * @param moodle_url|string $linkhref link to event referer
1118 * @return string|null $content html block content
1120 function calendar_get_block_upcoming($events, $linkhref = NULL) {
1122 $lines = count($events);
1127 for ($i = 0; $i < $lines; ++
$i) {
1128 if (!isset($events[$i]->time
)) { // Just for robustness
1131 $events[$i] = calendar_add_event_metadata($events[$i]);
1132 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon
.'</span> ';
1133 if (!empty($events[$i]->referer
)) {
1134 // That's an activity event, so let's provide the hyperlink
1135 $content .= $events[$i]->referer
;
1137 if(!empty($linkhref)) {
1138 $ed = usergetdate($events[$i]->timestart
);
1139 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL
.$linkhref), $ed['mday'], $ed['mon'], $ed['year']);
1140 $href->set_anchor('event_'.$events[$i]->id
);
1141 $content .= html_writer
::link($href, $events[$i]->name
);
1144 $content .= $events[$i]->name
;
1147 $events[$i]->time
= str_replace('»', '<br />»', $events[$i]->time
);
1148 $content .= '<div class="date">'.$events[$i]->time
.'</div></div>';
1149 if ($i < $lines - 1) $content .= '<hr />';
1156 * Get the next following month
1158 * If the current month is December, it will get the first month of the following year.
1161 * @param int $month the number of the month.
1162 * @param int $year the number of the year.
1163 * @return array the following month
1165 function calendar_add_month($month, $year) {
1167 return array(1, $year +
1);
1170 return array($month +
1, $year);
1175 * Get the previous month
1177 * If the current month is January, it will get the last month of the previous year.
1179 * @param int $month the number of the month.
1180 * @param int $year the number of the year.
1181 * @return array previous month
1183 function calendar_sub_month($month, $year) {
1185 return array(12, $year - 1);
1188 return array($month - 1, $year);
1193 * Get per-day basis events
1195 * @param array $events list of events
1196 * @param int $month the number of the month
1197 * @param int $year the number of the year
1198 * @param array $eventsbyday event on specific day
1199 * @param array $durationbyday duration of the event in days
1200 * @param array $typesbyday event type (eg: global, course, user, or group)
1201 * @param array $courses list of courses
1204 function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
1205 $eventsbyday = array();
1206 $typesbyday = array();
1207 $durationbyday = array();
1209 if($events === false) {
1213 foreach($events as $event) {
1215 $startdate = usergetdate($event->timestart
);
1216 // Set end date = start date if no duration
1217 if ($event->timeduration
) {
1218 $enddate = usergetdate($event->timestart +
$event->timeduration
- 1);
1220 $enddate = $startdate;
1223 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
1224 if(!($startdate['year'] * 13 +
$startdate['mon'] <= $year * 13 +
$month) && ($enddate['year'] * 13 +
$enddate['mon'] >= $year * 13 +
$month)) {
1229 $eventdaystart = intval($startdate['mday']);
1231 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1232 // Give the event to its day
1233 $eventsbyday[$eventdaystart][] = $event->id
;
1235 // Mark the day as having such an event
1236 if($event->courseid
== SITEID
&& $event->groupid
== 0) {
1237 $typesbyday[$eventdaystart]['startglobal'] = true;
1238 // Set event class for global event
1239 $events[$event->id
]->class = 'calendar_event_global';
1241 else if($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
1242 $typesbyday[$eventdaystart]['startcourse'] = true;
1243 // Set event class for course event
1244 $events[$event->id
]->class = 'calendar_event_course';
1246 else if($event->groupid
) {
1247 $typesbyday[$eventdaystart]['startgroup'] = true;
1248 // Set event class for group event
1249 $events[$event->id
]->class = 'calendar_event_group';
1251 else if($event->userid
) {
1252 $typesbyday[$eventdaystart]['startuser'] = true;
1253 // Set event class for user event
1254 $events[$event->id
]->class = 'calendar_event_user';
1258 if($event->timeduration
== 0) {
1259 // Proceed with the next
1263 // The event starts on $month $year or before. So...
1264 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ?
intval($startdate['mday']) : 0;
1266 // Also, it ends on $month $year or later...
1267 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ?
intval($enddate['mday']) : calendar_days_in_month($month, $year);
1269 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1270 for($i = $lowerbound +
1; $i <= $upperbound; ++
$i) {
1271 $durationbyday[$i][] = $event->id
;
1272 if($event->courseid
== SITEID
&& $event->groupid
== 0) {
1273 $typesbyday[$i]['durationglobal'] = true;
1275 else if($event->courseid
!= 0 && $event->courseid
!= SITEID
&& $event->groupid
== 0) {
1276 $typesbyday[$i]['durationcourse'] = true;
1278 else if($event->groupid
) {
1279 $typesbyday[$i]['durationgroup'] = true;
1281 else if($event->userid
) {
1282 $typesbyday[$i]['durationuser'] = true;
1291 * Get current module cache
1293 * @param array $coursecache list of course cache
1294 * @param string $modulename name of the module
1295 * @param int $instance module instance number
1296 * @return stdClass|bool $module information
1298 function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1299 $module = get_coursemodule_from_instance($modulename, $instance);
1301 if($module === false) return false;
1302 if(!calendar_get_course_cached($coursecache, $module->course
)) {
1309 * Get current course cache
1311 * @param array $coursecache list of course cache
1312 * @param int $courseid id of the course
1313 * @return stdClass $coursecache[$courseid] return the specific course cache
1315 function calendar_get_course_cached(&$coursecache, $courseid) {
1316 global $COURSE, $DB;
1318 if (!isset($coursecache[$courseid])) {
1319 if ($courseid == $COURSE->id
) {
1320 $coursecache[$courseid] = $COURSE;
1322 $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
1325 return $coursecache[$courseid];
1329 * Returns the courses to load events for, the
1331 * @param array $courseeventsfrom An array of courses to load calendar events for
1332 * @param bool $ignorefilters specify the use of filters, false is set as default
1333 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1335 function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1336 global $USER, $CFG, $DB;
1338 // For backwards compatability we have to check whether the courses array contains
1339 // just id's in which case we need to load course objects.
1340 $coursestoload = array();
1341 foreach ($courseeventsfrom as $id => $something) {
1342 if (!is_object($something)) {
1343 $coursestoload[] = $id;
1344 unset($courseeventsfrom[$id]);
1347 if (!empty($coursestoload)) {
1348 // TODO remove this in 2.2
1349 debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER
);
1350 $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
1357 // capabilities that allow seeing group events from all groups
1358 // TODO: rewrite so that moodle/calendar:manageentries is not necessary here
1359 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
1361 $isloggedin = isloggedin();
1363 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_COURSE
)) {
1364 $courses = array_keys($courseeventsfrom);
1366 if ($ignorefilters ||
calendar_show_event_type(CALENDAR_EVENT_GLOBAL
)) {
1367 $courses[] = SITEID
;
1369 $courses = array_unique($courses);
1372 if (!empty($courses) && in_array(SITEID
, $courses)) {
1373 // Sort courses for consistent colour highlighting
1374 // Effectively ignoring SITEID as setting as last course id
1375 $key = array_search(SITEID
, $courses);
1376 unset($courses[$key]);
1377 $courses[] = SITEID
;
1380 if ($ignorefilters ||
($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER
))) {
1384 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP
) ||
$ignorefilters)) {
1386 if (count($courseeventsfrom)==1) {
1387 $course = reset($courseeventsfrom);
1388 if (has_any_capability($allgroupscaps, context_course
::instance($course->id
))) {
1389 $coursegroups = groups_get_all_groups($course->id
, 0, 0, 'g.id');
1390 $group = array_keys($coursegroups);
1393 if ($group === false) {
1394 if (!empty($CFG->calendar_adminseesall
) && has_any_capability($allgroupscaps, get_system_context())) {
1396 } else if ($isloggedin) {
1397 $groupids = array();
1399 // We already have the courses to examine in $courses
1400 // For each course...
1401 foreach ($courseeventsfrom as $courseid => $course) {
1402 // If the user is an editing teacher in there,
1403 if (!empty($USER->groupmember
[$course->id
])) {
1404 // We've already cached the users groups for this course so we can just use that
1405 $groupids = array_merge($groupids, $USER->groupmember
[$course->id
]);
1406 } else if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
1407 // If this course has groups, show events from all of those related to the current user
1408 $coursegroups = groups_get_user_groups($course->id
, $USER->id
);
1409 $groupids = array_merge($groupids, $coursegroups['0']);
1412 if (!empty($groupids)) {
1418 if (empty($courses)) {
1422 return array($courses, $group, $user);
1426 * Return the capability for editing calendar event
1428 * @param calendar_event $event event object
1429 * @return bool capability to edit event
1431 function calendar_edit_event_allowed($event) {
1434 // Must be logged in
1435 if (!isloggedin()) {
1439 // can not be using guest account
1440 if (isguestuser()) {
1444 $sitecontext = context_system
::instance();
1445 // if user has manageentries at site level, return true
1446 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1450 // if groupid is set, it's definitely a group event
1451 if (!empty($event->groupid
)) {
1452 // Allow users to add/edit group events if:
1453 // 1) They have manageentries (= entries for whole course)
1454 // 2) They have managegroupentries AND are in the group
1455 $group = $DB->get_record('groups', array('id'=>$event->groupid
));
1457 has_capability('moodle/calendar:manageentries', $event->context
) ||
1458 (has_capability('moodle/calendar:managegroupentries', $event->context
)
1459 && groups_is_member($event->groupid
)));
1460 } else if (!empty($event->courseid
)) {
1461 // if groupid is not set, but course is set,
1462 // it's definiely a course event
1463 return has_capability('moodle/calendar:manageentries', $event->context
);
1464 } else if (!empty($event->userid
) && $event->userid
== $USER->id
) {
1465 // if course is not set, but userid id set, it's a user event
1466 return (has_capability('moodle/calendar:manageownentries', $event->context
));
1467 } else if (!empty($event->userid
)) {
1468 return (has_capability('moodle/calendar:manageentries', $event->context
));
1474 * Returns the default courses to display on the calendar when there isn't a specific
1475 * course to display.
1477 * @return array $courses Array of courses to display
1479 function calendar_get_default_courses() {
1482 if (!isloggedin()) {
1487 if (!empty($CFG->calendar_adminseesall
) && has_capability('moodle/calendar:manageentries', context_system
::instance())) {
1488 list ($select, $join) = context_instance_preload_sql('c.id', CONTEXT_COURSE
, 'ctx');
1489 $sql = "SELECT c.* $select
1492 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
1494 $courses = $DB->get_records_sql($sql, null, 0, 20);
1495 foreach ($courses as $course) {
1496 context_helper
::preload_from_record($course);
1501 $courses = enrol_get_my_courses();
1507 * Display calendar preference button
1509 * @param stdClass $course course object
1510 * @return string return preference button in html
1512 function calendar_preferences_button(stdClass
$course) {
1515 // Guests have no preferences
1516 if (!isloggedin() ||
isguestuser()) {
1520 return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id
)), get_string("preferences", "calendar"));
1524 * Get event format time
1526 * @param calendar_event $event event object
1527 * @param int $now current time in gmt
1528 * @param array $linkparams list of params for event link
1529 * @param bool $usecommonwords the words as formatted date/time.
1530 * @param int $showtime determine the show time GMT timestamp
1531 * @return string $eventtime link/string for event time
1533 function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime=0) {
1534 $startdate = usergetdate($event->timestart
);
1535 $enddate = usergetdate($event->timestart +
$event->timeduration
);
1536 $usermidnightstart = usergetmidnight($event->timestart
);
1538 if($event->timeduration
) {
1539 // To avoid doing the math if one IF is enough :)
1540 $usermidnightend = usergetmidnight($event->timestart +
$event->timeduration
);
1543 $usermidnightend = $usermidnightstart;
1546 if (empty($linkparams) ||
!is_array($linkparams)) {
1547 $linkparams = array();
1549 $linkparams['view'] = 'day';
1551 // OK, now to get a meaningful display...
1552 // First of all we have to construct a human-readable date/time representation
1554 if($event->timeduration
) {
1555 // It has a duration
1556 if($usermidnightstart == $usermidnightend ||
1557 ($event->timestart
== $usermidnightstart) && ($event->timeduration
== 86400 ||
$event->timeduration
== 86399) ||
1558 ($event->timestart +
$event->timeduration
<= $usermidnightstart +
86400)) {
1559 // But it's all on the same day
1560 $timestart = calendar_time_representation($event->timestart
);
1561 $timeend = calendar_time_representation($event->timestart +
$event->timeduration
);
1562 $time = $timestart.' <strong>»</strong> '.$timeend;
1564 if ($event->timestart
== $usermidnightstart && ($event->timeduration
== 86400 ||
$event->timeduration
== 86399)) {
1565 $time = get_string('allday', 'calendar');
1568 // Set printable representation
1570 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
1571 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1572 $eventtime = html_writer
::link($url, $day).', '.$time;
1577 // It spans two or more days
1578 $daystart = calendar_day_representation($event->timestart
, $now, $usecommonwords).', ';
1579 if ($showtime == $usermidnightstart) {
1582 $timestart = calendar_time_representation($event->timestart
);
1583 $dayend = calendar_day_representation($event->timestart +
$event->timeduration
, $now, $usecommonwords).', ';
1584 if ($showtime == $usermidnightend) {
1587 $timeend = calendar_time_representation($event->timestart +
$event->timeduration
);
1589 // Set printable representation
1590 if ($now >= $usermidnightstart && $now < ($usermidnightstart +
86400)) {
1591 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1592 $eventtime = $timestart.' <strong>»</strong> '.html_writer
::link($url, $dayend).$timeend;
1594 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $linkparams), $enddate['mday'], $enddate['mon'], $enddate['year']);
1595 $eventtime = html_writer
::link($url, $daystart).$timestart.' <strong>»</strong> ';
1597 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1598 $eventtime .= html_writer
::link($url, $dayend).$timeend;
1602 $time = calendar_time_representation($event->timestart
);
1604 // Set printable representation
1606 $day = calendar_day_representation($event->timestart
, $now, $usecommonwords);
1607 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL
.'view.php', $linkparams), $startdate['mday'], $startdate['mon'], $startdate['year']);
1608 $eventtime = html_writer
::link($url, $day).', '.trim($time);
1614 if($event->timestart +
$event->timeduration
< $now) {
1616 $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
1623 * Display month selector options
1625 * @param string $name for the select element
1626 * @param string|array $selected options for select elements
1628 function calendar_print_month_selector($name, $selected) {
1630 for ($i=1; $i<=12; $i++
) {
1631 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
1633 echo html_writer
::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
1634 echo html_writer
::select($months, $name, $selected, false);
1638 * Checks to see if the requested type of event should be shown for the given user.
1640 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1641 * The type to check the display for (default is to display all)
1642 * @param stdClass|int|null $user The user to check for - by default the current user
1643 * @return bool True if the tyep should be displayed false otherwise
1645 function calendar_show_event_type($type, $user = null) {
1646 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER
;
1647 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
1649 if (!isset($SESSION->calendarshoweventtype
)) {
1650 $SESSION->calendarshoweventtype
= $default;
1652 return $SESSION->calendarshoweventtype
& $type;
1654 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
1659 * Sets the display of the event type given $display.
1661 * If $display = true the event type will be shown.
1662 * If $display = false the event type will NOT be shown.
1663 * If $display = null the current value will be toggled and saved.
1665 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type object of CALENDAR_EVENT_XXX
1666 * @param bool $display option to display event type
1667 * @param stdClass|int $user moodle user object or id, null means current user
1669 function calendar_set_event_type_display($type, $display = null, $user = null) {
1670 $persist = get_user_preferences('calendar_persistflt', 0, $user);
1671 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER
;
1672 if ($persist === 0) {
1674 if (!isset($SESSION->calendarshoweventtype
)) {
1675 $SESSION->calendarshoweventtype
= $default;
1677 $preference = $SESSION->calendarshoweventtype
;
1679 $preference = get_user_preferences('calendar_savedflt', $default, $user);
1681 $current = $preference & $type;
1682 if ($display === null) {
1683 $display = !$current;
1685 if ($display && !$current) {
1686 $preference +
= $type;
1687 } else if (!$display && $current) {
1688 $preference -= $type;
1690 if ($persist === 0) {
1691 $SESSION->calendarshoweventtype
= $preference;
1693 if ($preference == $default) {
1694 unset_user_preference('calendar_savedflt', $user);
1696 set_user_preference('calendar_savedflt', $preference, $user);
1702 * Get calendar's allowed types
1704 * @param stdClass $allowed list of allowed edit for event type
1705 * @param stdClass|int $course object of a course or course id
1707 function calendar_get_allowed_types(&$allowed, $course = null) {
1708 global $USER, $CFG, $DB;
1709 $allowed = new stdClass();
1710 $allowed->user
= has_capability('moodle/calendar:manageownentries', get_system_context());
1711 $allowed->groups
= false; // This may change just below
1712 $allowed->courses
= false; // This may change just below
1713 $allowed->site
= has_capability('moodle/calendar:manageentries', context_course
::instance(SITEID
));
1715 if (!empty($course)) {
1716 if (!is_object($course)) {
1717 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST
);
1719 if ($course->id
!= SITEID
) {
1720 $coursecontext = context_course
::instance($course->id
);
1721 $allowed->user
= has_capability('moodle/calendar:manageownentries', $coursecontext);
1723 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1724 $allowed->courses
= array($course->id
=> 1);
1726 if ($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
1727 $allowed->groups
= groups_get_all_groups($course->id
);
1729 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1730 if($course->groupmode
!= NOGROUPS ||
!$course->groupmodeforce
) {
1731 $allowed->groups
= groups_get_all_groups($course->id
);
1739 * See if user can add calendar entries at all
1740 * used to print the "New Event" button
1742 * @param stdClass $course object of a course or course id
1743 * @return bool has the capability to add at least one event type
1745 function calendar_user_can_add_event($course) {
1746 if (!isloggedin() ||
isguestuser()) {
1749 calendar_get_allowed_types($allowed, $course);
1750 return (bool)($allowed->user ||
$allowed->groups ||
$allowed->courses ||
$allowed->site
);
1754 * Check wether the current user is permitted to add events
1756 * @param stdClass $event object of event
1757 * @return bool has the capability to add event
1759 function calendar_add_event_allowed($event) {
1762 // can not be using guest account
1763 if (!isloggedin() or isguestuser()) {
1767 $sitecontext = context_system
::instance();
1768 // if user has manageentries at site level, always return true
1769 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1773 switch ($event->eventtype
) {
1775 return has_capability('moodle/calendar:manageentries', $event->context
);
1778 // Allow users to add/edit group events if:
1779 // 1) They have manageentries (= entries for whole course)
1780 // 2) They have managegroupentries AND are in the group
1781 $group = $DB->get_record('groups', array('id'=>$event->groupid
));
1783 has_capability('moodle/calendar:manageentries', $event->context
) ||
1784 (has_capability('moodle/calendar:managegroupentries', $event->context
)
1785 && groups_is_member($event->groupid
)));
1788 if ($event->userid
== $USER->id
) {
1789 return (has_capability('moodle/calendar:manageownentries', $event->context
));
1791 //there is no 'break;' intentionally
1794 return has_capability('moodle/calendar:manageentries', $event->context
);
1797 return has_capability('moodle/calendar:manageentries', $event->context
);
1802 * Manage calendar events
1804 * This class provides the required functionality in order to manage calendar events.
1805 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1806 * better framework for dealing with calendar events in particular regard to file
1807 * handling through the new file API
1809 * @package core_calendar
1810 * @category calendar
1811 * @copyright 2009 Sam Hemelryk
1812 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1814 * @property int $id The id within the event table
1815 * @property string $name The name of the event
1816 * @property string $description The description of the event
1817 * @property int $format The format of the description FORMAT_?
1818 * @property int $courseid The course the event is associated with (0 if none)
1819 * @property int $groupid The group the event is associated with (0 if none)
1820 * @property int $userid The user the event is associated with (0 if none)
1821 * @property int $repeatid If this is a repeated event this will be set to the
1822 * id of the original
1823 * @property string $modulename If added by a module this will be the module name
1824 * @property int $instance If added by a module this will be the module instance
1825 * @property string $eventtype The event type
1826 * @property int $timestart The start time as a timestamp
1827 * @property int $timeduration The duration of the event in seconds
1828 * @property int $visible 1 if the event is visible
1829 * @property int $uuid ?
1830 * @property int $sequence ?
1831 * @property int $timemodified The time last modified as a timestamp
1833 class calendar_event
{
1835 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
1836 protected $properties = null;
1839 * @var string The converted event discription with file paths resolved. This gets populated when someone requests description for the first time */
1840 protected $_description = null;
1842 /** @var array The options to use with this description editor */
1843 protected $editoroptions = array(
1845 'forcehttps'=>false,
1848 'trusttext'=>false);
1850 /** @var object The context to use with the description editor */
1851 protected $editorcontext = null;
1854 * Instantiates a new event and optionally populates its properties with the
1857 * @param stdClass $data Optional. An object containing the properties to for
1860 public function __construct($data=null) {
1863 // First convert to object if it is not already (should either be object or assoc array)
1864 if (!is_object($data)) {
1865 $data = (object)$data;
1868 $this->editoroptions
['maxbytes'] = $CFG->maxbytes
;
1870 $data->eventrepeats
= 0;
1872 if (empty($data->id
)) {
1876 // Default to a user event
1877 if (empty($data->eventtype
)) {
1878 $data->eventtype
= 'user';
1881 // Default to the current user
1882 if (empty($data->userid
)) {
1883 $data->userid
= $USER->id
;
1886 if (!empty($data->timeduration
) && is_array($data->timeduration
)) {
1887 $data->timeduration
= make_timestamp($data->timeduration
['year'], $data->timeduration
['month'], $data->timeduration
['day'], $data->timeduration
['hour'], $data->timeduration
['minute']) - $data->timestart
;
1889 if (!empty($data->description
) && is_array($data->description
)) {
1890 $data->format
= $data->description
['format'];
1891 $data->description
= $data->description
['text'];
1892 } else if (empty($data->description
)) {
1893 $data->description
= '';
1894 $data->format
= editors_get_preferred_format();
1896 // Ensure form is defaulted correctly
1897 if (empty($data->format
)) {
1898 $data->format
= editors_get_preferred_format();
1901 if (empty($data->context
)) {
1902 $data->context
= $this->calculate_context($data);
1904 $this->properties
= $data;
1908 * Magic property method
1910 * Attempts to call a set_$key method if one exists otherwise falls back
1911 * to simply set the property
1913 * @param string $key property name
1914 * @param mixed $value value of the property
1916 public function __set($key, $value) {
1917 if (method_exists($this, 'set_'.$key)) {
1918 $this->{'set_'.$key}($value);
1920 $this->properties
->{$key} = $value;
1926 * Attempts to call a get_$key method to return the property and ralls over
1927 * to return the raw property
1929 * @param string $key property name
1930 * @return mixed property value
1932 public function __get($key) {
1933 if (method_exists($this, 'get_'.$key)) {
1934 return $this->{'get_'.$key}();
1936 if (!isset($this->properties
->{$key})) {
1937 throw new coding_exception('Undefined property requested');
1939 return $this->properties
->{$key};
1943 * Stupid PHP needs an isset magic method if you use the get magic method and
1944 * still want empty calls to work.... blah ~!
1946 * @param string $key $key property name
1947 * @return bool|mixed property value, false if property is not exist
1949 public function __isset($key) {
1950 return !empty($this->properties
->{$key});
1954 * Calculate the context value needed for calendar_event.
1955 * Event's type can be determine by the available value store in $data
1956 * It is important to check for the existence of course/courseid to determine
1958 * Default value is set to CONTEXT_USER
1960 * @param stdClass $data information about event
1961 * @return stdClass The context object.
1963 protected function calculate_context(stdClass
$data) {
1967 if (isset($data->courseid
) && $data->courseid
> 0) {
1968 $context = context_course
::instance($data->courseid
);
1969 } else if (isset($data->course
) && $data->course
> 0) {
1970 $context = context_course
::instance($data->course
);
1971 } else if (isset($data->groupid
) && $data->groupid
> 0) {
1972 $group = $DB->get_record('groups', array('id'=>$data->groupid
));
1973 $context = context_course
::instance($group->courseid
);
1974 } else if (isset($data->userid
) && $data->userid
> 0 && $data->userid
== $USER->id
) {
1975 $context = context_user
::instance($data->userid
);
1976 } else if (isset($data->userid
) && $data->userid
> 0 && $data->userid
!= $USER->id
&&
1977 isset($data->instance
) && $data->instance
> 0) {
1978 $cm = get_coursemodule_from_instance($data->modulename
, $data->instance
, 0, false, MUST_EXIST
);
1979 $context = context_course
::instance($cm->course
);
1981 $context = context_user
::instance();
1988 * Returns an array of editoroptions for this event: Called by __get
1989 * Please use $blah = $event->editoroptions;
1991 * @return array event editor options
1993 protected function get_editoroptions() {
1994 return $this->editoroptions
;
1998 * Returns an event description: Called by __get
1999 * Please use $blah = $event->description;
2001 * @return string event description
2003 protected function get_description() {
2006 require_once($CFG->libdir
. '/filelib.php');
2008 if ($this->_description
=== null) {
2009 // Check if we have already resolved the context for this event
2010 if ($this->editorcontext
=== null) {
2011 // Switch on the event type to decide upon the appropriate context
2012 // to use for this event
2013 $this->editorcontext
= $this->properties
->context
;
2014 if ($this->properties
->eventtype
!= 'user' && $this->properties
->eventtype
!= 'course'
2015 && $this->properties
->eventtype
!= 'site' && $this->properties
->eventtype
!= 'group') {
2016 return clean_text($this->properties
->description
, $this->properties
->format
);
2020 // Work out the item id for the editor, if this is a repeated event then the files will
2021 // be associated with the original
2022 if (!empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
2023 $itemid = $this->properties
->repeatid
;
2025 $itemid = $this->properties
->id
;
2028 // Convert file paths in the description so that things display correctly
2029 $this->_description
= file_rewrite_pluginfile_urls($this->properties
->description
, 'pluginfile.php', $this->editorcontext
->id
, 'calendar', 'event_description', $itemid);
2030 // Clean the text so no nasties get through
2031 $this->_description
= clean_text($this->_description
, $this->properties
->format
);
2033 // Finally return the description
2034 return $this->_description
;
2038 * Return the number of repeat events there are in this events series
2040 * @return int number of event repeated
2042 public function count_repeats() {
2044 if (!empty($this->properties
->repeatid
)) {
2045 $this->properties
->eventrepeats
= $DB->count_records('event', array('repeatid'=>$this->properties
->repeatid
));
2046 // We don't want to count ourselves
2047 $this->properties
->eventrepeats
--;
2049 return $this->properties
->eventrepeats
;
2053 * Update or create an event within the database
2055 * Pass in a object containing the event properties and this function will
2056 * insert it into the database and deal with any associated files
2059 * @see update_event()
2061 * @param stdClass $data object of event
2062 * @param bool $checkcapability if moodle should check calendar managing capability or not
2063 * @return bool event updated
2065 public function update($data, $checkcapability=true) {
2066 global $CFG, $DB, $USER;
2068 foreach ($data as $key=>$value) {
2069 $this->properties
->$key = $value;
2072 $this->properties
->timemodified
= time();
2073 $usingeditor = (!empty($this->properties
->description
) && is_array($this->properties
->description
));
2075 if (empty($this->properties
->id
) ||
$this->properties
->id
< 1) {
2077 if ($checkcapability) {
2078 if (!calendar_add_event_allowed($this->properties
)) {
2079 print_error('nopermissiontoupdatecalendar');
2084 switch ($this->properties
->eventtype
) {
2086 $this->editorcontext
= $this->properties
->context
;
2087 $this->properties
->courseid
= 0;
2088 $this->properties
->groupid
= 0;
2089 $this->properties
->userid
= $USER->id
;
2092 $this->editorcontext
= $this->properties
->context
;
2093 $this->properties
->courseid
= SITEID
;
2094 $this->properties
->groupid
= 0;
2095 $this->properties
->userid
= $USER->id
;
2098 $this->editorcontext
= $this->properties
->context
;
2099 $this->properties
->groupid
= 0;
2100 $this->properties
->userid
= $USER->id
;
2103 $this->editorcontext
= $this->properties
->context
;
2104 $this->properties
->userid
= $USER->id
;
2107 // Ewww we should NEVER get here, but just incase we do lets
2109 $usingeditor = false;
2113 $editor = $this->properties
->description
;
2114 $this->properties
->format
= $this->properties
->description
['format'];
2115 $this->properties
->description
= $this->properties
->description
['text'];
2118 // Insert the event into the database
2119 $this->properties
->id
= $DB->insert_record('event', $this->properties
);
2122 $this->properties
->description
= file_save_draft_area_files(
2124 $this->editorcontext
->id
,
2126 'event_description',
2127 $this->properties
->id
,
2128 $this->editoroptions
,
2130 $this->editoroptions
['forcehttps']);
2132 $DB->set_field('event', 'description', $this->properties
->description
, array('id'=>$this->properties
->id
));
2135 // Log the event entry.
2136 add_to_log($this->properties
->courseid
, 'calendar', 'add', 'event.php?action=edit&id='.$this->properties
->id
, $this->properties
->name
);
2138 $repeatedids = array();
2140 if (!empty($this->properties
->repeat
)) {
2141 $this->properties
->repeatid
= $this->properties
->id
;
2142 $DB->set_field('event', 'repeatid', $this->properties
->repeatid
, array('id'=>$this->properties
->id
));
2144 $eventcopy = clone($this->properties
);
2145 unset($eventcopy->id
);
2147 for($i = 1; $i < $eventcopy->repeats
; $i++
) {
2149 $eventcopy->timestart
= ($eventcopy->timestart+WEEKSECS
) +
dst_offset_on($eventcopy->timestart
) - dst_offset_on($eventcopy->timestart+WEEKSECS
);
2151 // Get the event id for the log record.
2152 $eventcopyid = $DB->insert_record('event', $eventcopy);
2154 // If the context has been set delete all associated files
2156 $fs = get_file_storage();
2157 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description', $this->properties
->id
);
2158 foreach ($files as $file) {
2159 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
2163 $repeatedids[] = $eventcopyid;
2164 // Log the event entry.
2165 add_to_log($eventcopy->courseid
, 'calendar', 'add', 'event.php?action=edit&id='.$eventcopyid, $eventcopy->name
);
2169 // Hook for tracking added events
2170 self
::calendar_event_hook('add_event', array($this->properties
, $repeatedids));
2174 if ($checkcapability) {
2175 if(!calendar_edit_event_allowed($this->properties
)) {
2176 print_error('nopermissiontoupdatecalendar');
2181 if ($this->editorcontext
!== null) {
2182 $this->properties
->description
= file_save_draft_area_files(
2183 $this->properties
->description
['itemid'],
2184 $this->editorcontext
->id
,
2186 'event_description',
2187 $this->properties
->id
,
2188 $this->editoroptions
,
2189 $this->properties
->description
['text'],
2190 $this->editoroptions
['forcehttps']);
2192 $this->properties
->format
= $this->properties
->description
['format'];
2193 $this->properties
->description
= $this->properties
->description
['text'];
2197 $event = $DB->get_record('event', array('id'=>$this->properties
->id
));
2199 $updaterepeated = (!empty($this->properties
->repeatid
) && !empty($this->properties
->repeateditall
));
2201 if ($updaterepeated) {
2203 if ($this->properties
->timestart
!= $event->timestart
) {
2204 $timestartoffset = $this->properties
->timestart
- $event->timestart
;
2205 $sql = "UPDATE {event}
2208 timestart = timestart + ?,
2211 WHERE repeatid = ?";
2212 $params = array($this->properties
->name
, $this->properties
->description
, $timestartoffset, $this->properties
->timeduration
, time(), $event->repeatid
);
2214 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2215 $params = array($this->properties
->name
, $this->properties
->description
, $this->properties
->timeduration
, time(), $event->repeatid
);
2217 $DB->execute($sql, $params);
2219 // Log the event update.
2220 add_to_log($this->properties
->courseid
, 'calendar', 'edit all', 'event.php?action=edit&id='.$this->properties
->id
, $this->properties
->name
);
2222 $DB->update_record('event', $this->properties
);
2223 $event = calendar_event
::load($this->properties
->id
);
2224 $this->properties
= $event->properties();
2225 add_to_log($this->properties
->courseid
, 'calendar', 'edit', 'event.php?action=edit&id='.$this->properties
->id
, $this->properties
->name
);
2228 // Hook for tracking event updates
2229 self
::calendar_event_hook('update_event', array($this->properties
, $updaterepeated));
2235 * Deletes an event and if selected an repeated events in the same series
2237 * This function deletes an event, any associated events if $deleterepeated=true,
2238 * and cleans up any files associated with the events.
2240 * @see delete_event()
2242 * @param bool $deleterepeated delete event repeatedly
2243 * @return bool succession of deleting event
2245 public function delete($deleterepeated=false) {
2248 // If $this->properties->id is not set then something is wrong
2249 if (empty($this->properties
->id
)) {
2250 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER
);
2255 $DB->delete_records('event', array('id'=>$this->properties
->id
));
2257 // If we are deleting parent of a repeated event series, promote the next event in the series as parent
2258 if (($this->properties
->id
== $this->properties
->repeatid
) && !$deleterepeated) {
2259 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC", array($this->properties
->id
), IGNORE_MULTIPLE
);
2260 if (!empty($newparent)) {
2261 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?", array($newparent, $this->properties
->id
));
2262 // Get all records where the repeatid is the same as the event being removed
2263 $events = $DB->get_records('event', array('repeatid' => $newparent));
2264 // For each of the returned events trigger the event_update hook.
2265 foreach ($events as $event) {
2266 self
::calendar_event_hook('update_event', array($event, false));
2271 // If the editor context hasn't already been set then set it now
2272 if ($this->editorcontext
=== null) {
2273 $this->editorcontext
= $this->properties
->context
;
2276 // If the context has been set delete all associated files
2277 if ($this->editorcontext
!== null) {
2278 $fs = get_file_storage();
2279 $files = $fs->get_area_files($this->editorcontext
->id
, 'calendar', 'event_description', $this->properties
->id
);
2280 foreach ($files as $file) {
2285 // Fire the event deleted hook
2286 self
::calendar_event_hook('delete_event', array($this->properties
->id
, $deleterepeated));
2288 // If we need to delete repeated events then we will fetch them all and delete one by one
2289 if ($deleterepeated && !empty($this->properties
->repeatid
) && $this->properties
->repeatid
> 0) {
2290 // Get all records where the repeatid is the same as the event being removed
2291 $events = $DB->get_records('event', array('repeatid'=>$this->properties
->repeatid
));
2292 // For each of the returned events populate a calendar_event object and call delete
2293 // make sure the arg passed is false as we are already deleting all repeats
2294 foreach ($events as $event) {
2295 $event = new calendar_event($event);
2296 $event->delete(false);
2304 * Fetch all event properties
2306 * This function returns all of the events properties as an object and optionally
2307 * can prepare an editor for the description field at the same time. This is
2308 * designed to work when the properties are going to be used to set the default
2309 * values of a moodle forms form.
2311 * @param bool $prepareeditor If set to true a editor is prepared for use with
2312 * the mforms editor element. (for description)
2313 * @return stdClass Object containing event properties
2315 public function properties($prepareeditor=false) {
2316 global $USER, $CFG, $DB;
2318 // First take a copy of the properties. We don't want to actually change the
2319 // properties or we'd forever be converting back and forwards between an
2320 // editor formatted description and not
2321 $properties = clone($this->properties
);
2322 // Clean the description here
2323 $properties->description
= clean_text($properties->description
, $properties->format
);
2325 // If set to true we need to prepare the properties for use with an editor
2326 // and prepare the file area
2327 if ($prepareeditor) {
2329 // We may or may not have a property id. If we do then we need to work
2330 // out the context so we can copy the existing files to the draft area
2331 if (!empty($properties->id
)) {
2333 if ($properties->eventtype
=== 'site') {
2335 $this->editorcontext
= $this->properties
->context
;
2336 } else if ($properties->eventtype
=== 'user') {
2338 $this->editorcontext
= $this->properties
->context
;
2339 } else if ($properties->eventtype
=== 'group' ||
$properties->eventtype
=== 'course') {
2340 // First check the course is valid
2341 $course = $DB->get_record('course', array('id'=>$properties->courseid
));
2343 print_error('invalidcourse');
2346 $this->editorcontext
= $this->properties
->context
;
2347 // We have a course and are within the course context so we had
2348 // better use the courses max bytes value
2349 $this->editoroptions
['maxbytes'] = $course->maxbytes
;
2351 // If we get here we have a custom event type as used by some
2352 // modules. In this case the event will have been added by
2353 // code and we won't need the editor
2354 $this->editoroptions
['maxbytes'] = 0;
2355 $this->editoroptions
['maxfiles'] = 0;
2358 if (empty($this->editorcontext
) ||
empty($this->editorcontext
->id
)) {
2361 // Get the context id that is what we really want
2362 $contextid = $this->editorcontext
->id
;
2366 // If we get here then this is a new event in which case we don't need a
2367 // context as there is no existing files to copy to the draft area.
2371 // If the contextid === false we don't support files so no preparing
2373 if ($contextid !== false) {
2374 // Just encase it has already been submitted
2375 $draftiddescription = file_get_submitted_draft_itemid('description');
2376 // Prepare the draft area, this copies existing files to the draft area as well
2377 $properties->description
= file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id
, $this->editoroptions
, $properties->description
);
2379 $draftiddescription = 0;
2382 // Structure the description field as the editor requires
2383 $properties->description
= array('text'=>$properties->description
, 'format'=>$properties->format
, 'itemid'=>$draftiddescription);
2386 // Finally return the properties
2391 * Toggles the visibility of an event
2393 * @param null|bool $force If it is left null the events visibility is flipped,
2394 * If it is false the event is made hidden, if it is true it
2396 * @return bool if event is successfully updated, toggle will be visible
2398 public function toggle_visibility($force=null) {
2401 // Set visible to the default if it is not already set
2402 if (empty($this->properties
->visible
)) {
2403 $this->properties
->visible
= 1;
2406 if ($force === true ||
($force !== false && $this->properties
->visible
== 0)) {
2407 // Make this event visible
2408 $this->properties
->visible
= 1;
2410 self
::calendar_event_hook('show_event', array($this->properties
));
2412 // Make this event hidden
2413 $this->properties
->visible
= 0;
2415 self
::calendar_event_hook('hide_event', array($this->properties
));
2418 // Update the database to reflect this change
2419 return $DB->set_field('event', 'visible', $this->properties
->visible
, array('id'=>$this->properties
->id
));
2423 * Attempts to call the hook for the specified action should a calendar type
2424 * by set $CFG->calendar, and the appopriate function defined
2426 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2427 * @param array $args The args to pass to the hook, usually the event is the first element
2428 * @return bool attempts to call event hook
2430 public static function calendar_event_hook($action, array $args) {
2432 static $extcalendarinc;
2433 if ($extcalendarinc === null) {
2434 if (!empty($CFG->calendar
)) {
2435 if (is_readable($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php')) {
2436 include_once($CFG->dirroot
.'/calendar/'. $CFG->calendar
.'/lib.php');
2437 $extcalendarinc = true;
2439 debugging("Calendar lib file missing or not readable at /calendar/{$CFG->calendar}/lib.php.",
2441 $extcalendarinc = false;
2444 $extcalendarinc = false;
2447 if($extcalendarinc === false) {
2450 $hook = $CFG->calendar
.'_'.$action;
2451 if (function_exists($hook)) {
2452 call_user_func_array($hook, $args);
2459 * Returns a calendar_event object when provided with an event id
2461 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2462 * it will result in an exception being thrown
2464 * @param int|object $param event object or event id
2465 * @return calendar_event|false status for loading calendar_event
2467 public static function load($param) {
2469 if (is_object($param)) {
2470 $event = new calendar_event($param);
2472 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST
);
2473 $event = new calendar_event($event);
2479 * Creates a new event and returns a calendar_event object
2481 * @param object|array $properties An object containing event properties
2482 * @return calendar_event|false The event object or false if it failed
2484 public static function create($properties) {
2485 if (is_array($properties)) {
2486 $properties = (object)$properties;
2488 if (!is_object($properties)) {
2489 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2491 $event = new calendar_event($properties);
2492 if ($event->update($properties)) {
2501 * Calendar information class
2503 * This class is used simply to organise the information pertaining to a calendar
2504 * and is used primarily to make information easily available.
2506 * @package core_calendar
2507 * @category calendar
2508 * @copyright 2010 Sam Hemelryk
2509 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2511 class calendar_information
{
2512 /** @var int The day */
2515 /** @var int The month */
2518 /** @var int The year */
2521 /** @var int A course id */
2522 public $courseid = null;
2524 /** @var array An array of courses */
2525 public $courses = array();
2527 /** @var array An array of groups */
2528 public $groups = array();
2530 /** @var array An array of users */
2531 public $users = array();
2534 * Creates a new instance
2536 * @param int $day the number of the day
2537 * @param int $month the number of the month
2538 * @param int $year the number of the year
2540 public function __construct($day=0, $month=0, $year=0) {
2542 $date = usergetdate(time());
2545 $day = $date['mday'];
2548 if (empty($month)) {
2549 $month = $date['mon'];
2553 $year = $date['year'];
2557 $this->month
= $month;
2558 $this->year
= $year;
2562 * Initialize calendar information
2564 * @param stdClass $course object
2565 * @param array $coursestoload An array of courses [$course->id => $course]
2566 * @param bool $ignorefilters options to use filter
2568 public function prepare_for_view(stdClass
$course, array $coursestoload, $ignorefilters = false) {
2569 $this->courseid
= $course->id
;
2570 $this->course
= $course;
2571 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2572 $this->courses
= $courses;
2573 $this->groups
= $group;
2574 $this->users
= $user;
2578 * Ensures the date for the calendar is correct and either sets it to now
2579 * or throws a moodle_exception if not
2581 * @param bool $defaultonow use current time
2582 * @throws moodle_exception
2583 * @return bool validation of checkdate
2585 public function checkdate($defaultonow = true) {
2586 if (!checkdate($this->month
, $this->day
, $this->year
)) {
2588 $now = usergetdate(time());
2589 $this->day
= intval($now['mday']);
2590 $this->month
= intval($now['mon']);
2591 $this->year
= intval($now['year']);
2594 throw new moodle_exception('invaliddate');
2600 * Gets todays timestamp for the calendar
2602 * @return int today timestamp
2604 public function timestamp_today() {
2605 return make_timestamp($this->year
, $this->month
, $this->day
);
2608 * Gets tomorrows timestamp for the calendar
2610 * @return int tomorrow timestamp
2612 public function timestamp_tomorrow() {
2613 return make_timestamp($this->year
, $this->month
, $this->day+
1);
2616 * Adds the pretend blocks for teh calendar
2618 * @param core_calendar_renderer $renderer
2619 * @param bool $showfilters display filters, false is set as default
2620 * @param string|null $view preference view options (eg: day, month, upcoming)
2622 public function add_sidecalendar_blocks(core_calendar_renderer
$renderer, $showfilters=false, $view=null) {
2624 $filters = new block_contents();
2625 $filters->content
= $renderer->fake_block_filters($this->courseid
, $this->day
, $this->month
, $this->year
, $view, $this->courses
);
2626 $filters->footer
= '';
2627 $filters->title
= get_string('eventskey', 'calendar');
2628 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT
);
2630 $block = new block_contents
;
2631 $block->content
= $renderer->fake_block_threemonths($this);
2632 $block->footer
= '';
2633 $block->title
= get_string('monthlyview', 'calendar');
2634 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT
);