WIKI MDL-24162 added comments deletion to wiki reset function, added $data->reset_wik...
[moodle.git] / calendar / lib.php
CommitLineData
93c91ee4 1<?php
7423f116 2
3/////////////////////////////////////////////////////////////////////////////
4// //
5// NOTICE OF COPYRIGHT //
6// //
7// Moodle - Calendar extension //
8// //
9// Copyright (C) 2003-2004 Greek School Network www.sch.gr //
10// //
11// Designed by: //
bdcb26b7 12// Avgoustos Tsinakos (tsinakos@teikav.edu.gr) //
13// Jon Papaioannou (pj@moodle.org) //
7423f116 14// //
15// Programming and development: //
bdcb26b7 16// Jon Papaioannou (pj@moodle.org) //
7423f116 17// //
18// For bugs, suggestions, etc contact: //
bdcb26b7 19// Jon Papaioannou (pj@moodle.org) //
7423f116 20// //
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. //
26// //
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. //
31// //
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: //
36// //
37// http://www.gnu.org/copyleft/gpl.html //
38// //
39/////////////////////////////////////////////////////////////////////////////
40
bb4a2e85 41// These are read by the administration component to provide default values
42define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
43define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
44define('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
47define('CALENDAR_DEFAULT_WEEKEND', 65);
76d9df3f
SH
48define('CALENDAR_UPCOMING_DAYS', isset($CFG->calendar_lookahead) ? intval($CFG->calendar_lookahead) : CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD);
49define('CALENDAR_UPCOMING_MAXEVENTS', isset($CFG->calendar_maxevents) ? intval($CFG->calendar_maxevents) : CALENDAR_DEFAULT_UPCOMING_MAXEVENTS);
50define('CALENDAR_WEEKEND', isset($CFG->calendar_weekend) ? intval($CFG->calendar_weekend) : CALENDAR_DEFAULT_WEEKEND);
51define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
52define('CALENDAR_TF_24', '%H:%M');
53define('CALENDAR_TF_12', '%I:%M %p');
bb4a2e85 54
76d9df3f
SH
55/**
56 * CALENDAR_STARTING_WEEKDAY has since been deprecated please call calendar_get_starting_weekday() instead
57 * @deprecated
58 */
59define('CALENDAR_STARTING_WEEKDAY', CALENDAR_DEFAULT_STARTING_WEEKDAY);
7423f116 60
f2bffd9e 61$CALENDARDAYS = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
62
76d9df3f
SH
63/**
64 * Gets the first day of the week
65 *
66 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
67 *
68 * @return int
69 */
70function calendar_get_starting_weekday() {
71 global $CFG;
37d87d11 72
76d9df3f
SH
73 if (isset($CFG->calendar_startwday)) {
74 $firstday = $CFG->calendar_startwday;
75 } else {
0a933ae6 76 $firstday = get_string('firstdayofweek', 'langconfig');
76d9df3f
SH
77 }
78
79 if(!is_numeric($firstday)) {
80 return CALENDAR_DEFAULT_STARTING_WEEKDAY;
81 } else {
82 return intval($firstday) % 7;
83 }
84}
bd119567 85
7423f116 86function calendar_get_mini($courses, $groups, $users, $cal_month = false, $cal_year = false) {
6b608f8f 87 global $CFG, $USER, $OUTPUT;
7423f116 88
dd97c328 89 $display = new stdClass;
76d9df3f 90 $display->minwday = get_user_preferences('calendar_startwday', calendar_get_starting_weekday());
7423f116 91 $display->maxwday = $display->minwday + 6;
92
93 $content = '';
94
95 if(!empty($cal_month) && !empty($cal_year)) {
96 $thisdate = usergetdate(time()); // Date and time the user sees at his location
97 if($cal_month == $thisdate['mon'] && $cal_year == $thisdate['year']) {
98 // Navigated to this month
99 $date = $thisdate;
100 $display->thismonth = true;
36dc3b71 101 } else {
7423f116 102 // Navigated to other month, let's do a nice trick and save us a lot of work...
103 if(!checkdate($cal_month, 1, $cal_year)) {
104 $date = array('mday' => 1, 'mon' => $thisdate['mon'], 'year' => $thisdate['year']);
105 $display->thismonth = true;
36dc3b71 106 } else {
7423f116 107 $date = array('mday' => 1, 'mon' => $cal_month, 'year' => $cal_year);
108 $display->thismonth = false;
109 }
110 }
36dc3b71 111 } else {
7423f116 112 $date = usergetdate(time()); // Date and time the user sees at his location
113 $display->thismonth = true;
114 }
115
116 // Fill in the variables we 're going to use, nice and tidy
117 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display
118 $display->maxdays = calendar_days_in_month($m, $y);
119
d6198903 120 if (get_user_timezone_offset() < 99) {
121 // We 'll keep these values as GMT here, and offset them when the time comes to query the db
61240489 122 $display->tstart = gmmktime(0, 0, 0, $m, 1, $y); // This is GMT
123 $display->tend = gmmktime(23, 59, 59, $m, $display->maxdays, $y); // GMT
d6198903 124 } else {
125 // no timezone info specified
61240489 126 $display->tstart = mktime(0, 0, 0, $m, 1, $y);
127 $display->tend = mktime(23, 59, 59, $m, $display->maxdays, $y);
d6198903 128 }
7423f116 129
69244b91 130 $startwday = dayofweek(1, $m, $y);
7423f116 131
132 // Align the starting weekday to fall in our display range
133 // This is simple, not foolproof.
134 if($startwday < $display->minwday) {
135 $startwday += 7;
136 }
137
c0b507d1 138 // TODO: THIS IS TEMPORARY CODE!
139 // [pj] I was just reading through this and realized that I when writing this code I was probably
140 // asking for trouble, as all these time manipulations seem to be unnecessary and a simple
141 // make_timestamp would accomplish the same thing. So here goes a test:
1747ee05 142 //$test_start = make_timestamp($y, $m, 1);
143 //$test_end = make_timestamp($y, $m, $display->maxdays, 23, 59, 59);
144 //if($test_start != usertime($display->tstart) - dst_offset_on($display->tstart)) {
145 //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);
146 //}
147 //if($test_end != usertime($display->tend) - dst_offset_on($display->tend)) {
148 //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);
149 //}
c0b507d1 150
151
7423f116 152 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
8263f802 153 $events = calendar_get_events(
d3555a2f 154 usertime($display->tstart) - dst_offset_on($display->tstart),
155 usertime($display->tend) - dst_offset_on($display->tend),
156 $users, $groups, $courses);
7423f116 157
b4892fa2 158 // Set event course class for course events
159 if (!empty($events)) {
13534ef7 160 foreach ($events as $eventid => $event) {
13534ef7
ML
161 if (!empty($event->modulename)) {
162 $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
163 if (!groups_course_module_visible($cm)) {
164 unset($events[$eventid]);
165 }
166 }
b4892fa2 167 }
168 }
6619eba4 169
c635dcda 170 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
9064751b 171 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
c635dcda 172 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
173 // arguments to this function.
174
7bd1677c 175 $morehref = '';
176 if(!empty($courses)) {
e749554e 177 $courses = array_diff($courses, array(SITEID));
7bd1677c 178 if(count($courses) == 1) {
179 $morehref = '&amp;course='.reset($courses);
180 }
c635dcda 181 }
182
7423f116 183 // We want to have easy access by day, since the display is on a per-day basis.
184 // Arguments passed by reference.
7b38bfa6 185 //calendar_events_by_day($events, $display->tstart, $eventsbyday, $durationbyday, $typesbyday);
7c50db30 186 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
7423f116 187
f20c4d02 188 //Accessibility: added summary and <abbr> elements.
189 ///global $CALENDARDAYS; appears to be broken.
190 $days_title = array('sunday','monday','tuesday','wednesday','thursday','friday','saturday');
191
2a06efcc 192 $summary = get_string('calendarheading', 'calendar', userdate(make_timestamp($y, $m), get_string('strftimemonthyear')));
193 $summary = get_string('tabledata', 'access', $summary);
90723839 194 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table
f136e4c5 195 $content .= '<tr class="weekdays">'; // Header row: day names
7423f116 196
197 // Print out the names of the weekdays
198 $days = array('sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat');
199 for($i = $display->minwday; $i <= $display->maxwday; ++$i) {
200 // This uses the % operator to get the correct weekday no matter what shift we have
201 // applied to the $display->minwday : $display->maxwday range from the default 0 : 6
f20c4d02 202 $content .= '<th scope="col"><abbr title="'. get_string($days_title[$i % 7], 'calendar') .'">'.
203 get_string($days[$i % 7], 'calendar') ."</abbr></th>\n";
7423f116 204 }
205
f136e4c5 206 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
7423f116 207
208 // For the table display. $week is the row; $dayweek is the column.
7423f116 209 $dayweek = $startwday;
210
211 // Paddding (the first week may have blank days in the beginning)
212 for($i = $display->minwday; $i < $startwday; ++$i) {
3bfd8bc8 213 $content .= '<td class="dayblank">&nbsp;</td>'."\n";
7423f116 214 }
215
216 // Now display all the calendar
217 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
218 if($dayweek > $display->maxwday) {
219 // We need to change week (table row)
d56d4e23 220 $content .= '</tr><tr>';
7423f116 221 $dayweek = $display->minwday;
7423f116 222 }
92668ad2 223
7423f116 224 // Reset vars
7423f116 225 $cell = '';
bb4a2e85 226 if(CALENDAR_WEEKEND & (1 << ($dayweek % 7))) {
7423f116 227 // Weekend. This is true no matter what the exact range is.
e2aa618b 228 $class = 'weekend day';
90723839 229 } else {
7423f116 230 // Normal working day.
e2aa618b 231 $class = 'day';
7423f116 232 }
233
234 // Special visual fx if an event is defined
235 if(isset($eventsbyday[$day])) {
90723839 236 $class .= ' hasevent';
c635dcda 237 $dayhref = calendar_get_link_href(CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $day, $m, $y);
f434283f 238
7423f116 239 // OverLib popup
240 $popupcontent = '';
241 foreach($eventsbyday[$day] as $eventid) {
41d30a8e 242 if (!isset($events[$eventid])) {
243 continue;
4e17c6f3 244 }
41d30a8e 245 $event = $events[$eventid];
41d30a8e 246 if(!empty($event->modulename)) {
b5d0cafc 247 $popupicon = $OUTPUT->pix_url('icon', $event->modulename) . '';
41d30a8e 248 $popupalt = $event->modulename;
249
9064751b 250 } else if ($event->courseid == SITEID) { // Site event
b5d0cafc 251 $popupicon = $OUTPUT->pix_url('c/site');
41d30a8e 252 $popupalt = '';
c3d3b6d4 253 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
b5d0cafc 254 $popupicon = $OUTPUT->pix_url('c/course');
c9b05b32 255 $popupalt = '';
41d30a8e 256 } else if ($event->groupid) { // Group event
b5d0cafc 257 $popupicon = $OUTPUT->pix_url('c/group');
41d30a8e 258 $popupalt = '';
259 } else if ($event->userid) { // User event
b5d0cafc 260 $popupicon = $OUTPUT->pix_url('c/user');
41d30a8e 261 $popupalt = '';
4e17c6f3 262 }
53d8fac0 263 $popupcontent .= '<div><img class="icon" src="'.$popupicon.'" alt="'.$popupalt.'" /><a href="'.$dayhref.'#event_'.$event->id.'">'.format_string($event->name, true).'</a></div>';
7423f116 264 }
e295df44 265
b5c42e70 266 //Accessibility: functionality moved to calendar_get_popup.
267 if($display->thismonth && $day == $d) {
450a0a7d 268 $popup = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
b5c42e70 269 } else {
450a0a7d 270 $popup = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
e295df44 271 }
f20c4d02 272
7423f116 273 // Class and cell content
274 if(isset($typesbyday[$day]['startglobal'])) {
90723839
SH
275 $class .= ' calendar_event_global';
276 } else if(isset($typesbyday[$day]['startcourse'])) {
277 $class .= ' calendar_event_course';
278 } else if(isset($typesbyday[$day]['startgroup'])) {
279 $class .= ' calendar_event_group';
280 } else if(isset($typesbyday[$day]['startuser'])) {
281 $class .= ' calendar_event_user';
7423f116 282 }
05fcc5fd 283 $cell = '<a href="'.$dayhref.'" '.$popup.'>'.$day.'</a>';
90723839 284 } else {
05fcc5fd 285 $cell = $day;
7423f116 286 }
287
90723839
SH
288 $durationclass = false;
289 if (isset($typesbyday[$day]['durationglobal'])) {
290 $durationclass = ' duration_global';
291 } else if(isset($typesbyday[$day]['durationcourse'])) {
292 $durationclass = ' duration_course';
293 } else if(isset($typesbyday[$day]['durationgroup'])) {
294 $durationclass = ' duration_group';
295 } else if(isset($typesbyday[$day]['durationuser'])) {
296 $durationclass = ' duration_user';
7423f116 297 }
90723839
SH
298 if ($durationclass) {
299 $class .= ' duration '.$durationclass;
7423f116 300 }
301
b4892fa2 302 // If event has a class set then add it to the table day <td> tag
303 // Note: only one colour for minicalendar
304 if(isset($eventsbyday[$day])) {
305 foreach($eventsbyday[$day] as $eventid) {
306 if (!isset($events[$eventid])) {
307 continue;
308 }
309 $event = $events[$eventid];
310 if (!empty($event->class)) {
311 $class .= ' '.$event->class;
312 }
313 break;
314 }
315 }
316
7423f116 317 // Special visual fx for today
450a0a7d 318 //Accessibility: hidden text for today, and popup.
7423f116 319 if($display->thismonth && $day == $d) {
edbe6c1b 320 $class .= ' today';
b5c42e70 321 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
e295df44 322
b5c42e70 323 if(! isset($eventsbyday[$day])) {
450a0a7d 324 $class .= ' eventnone';
325 $popup = calendar_get_popup(true, false);
326 $cell = '<a href="#" '.$popup.'>'.$day.'</a>';
b5c42e70 327 }
f79f2494 328 $cell = get_accesshide($today.' ').$cell;
7423f116 329 }
330
331 // Just display it
92668ad2 332 if(!empty($class)) {
d56d4e23 333 $class = ' class="'.$class.'"';
92668ad2 334 }
335 $content .= '<td'.$class.'>'.$cell."</td>\n";
7423f116 336 }
337
338 // Paddding (the last week may have blank days at the end)
339 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
3bfd8bc8 340 $content .= '<td class="dayblank">&nbsp;</td>';
7423f116 341 }
342 $content .= '</tr>'; // Last row ends
343
f136e4c5 344 $content .= '</table>'; // Tabular display of days ends
7423f116 345
346 return $content;
347}
348
b5c42e70 349/**
350 * calendar_get_popup, called at multiple points in from calendar_get_mini.
351 * Copied and modified from calendar_get_mini.
33e48a1a 352 * @global moodle_page $PAGE
b5c42e70 353 * @param $is_today bool, false except when called on the current day.
354 * @param $event_timestart mixed, $events[$eventid]->timestart, OR false if there are no events.
355 * @param $popupcontent string.
e295df44 356 * @return $popup string, contains onmousover and onmouseout events.
b5c42e70 357 */
358function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
458eb0d1 359 global $PAGE;
360 static $popupcount;
361 if ($popupcount === null) {
362 $popupcount = 1;
363 }
b5c42e70 364 $popupcaption = '';
365 if($is_today) {
366 $popupcaption = get_string('today', 'calendar').' ';
367 }
368 if (false === $event_timestart) {
369 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
370 $popupcontent = get_string('eventnone', 'calendar');
450a0a7d 371
b5c42e70 372 } else {
373 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
374 }
458eb0d1 375 $id = 'calendar_tooltip_'.$popupcount;
33e48a1a 376 $PAGE->requires->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
bdbae764 377
458eb0d1 378 $popupcount++;
379 return 'id="'.$id.'"';
b5c42e70 380}
381
9958a08c 382function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
62d11d77 383 global $CFG, $COURSE, $DB;
7423f116 384
dd97c328 385 $display = new stdClass;
7423f116 386 $display->range = $daysinfuture; // How many days in the future we 'll look
387 $display->maxevents = $maxevents;
388
389 $output = array();
390
391 // Prepare "course caching", since it may save us a lot of queries
392 $coursecache = array();
393
394 $processed = 0;
395 $now = time(); // We 'll need this later
9d567178 396 $usermidnighttoday = usergetmidnight($now);
7423f116 397
9958a08c 398 if ($fromtime) {
399 $display->tstart = $fromtime;
400 } else {
9d567178 401 $display->tstart = $usermidnighttoday;
9958a08c 402 }
7423f116 403
1f473774 404 // This works correctly with respect to the user's DST, but it is accurate
405 // only because $fromtime is always the exact midnight of some day!
406 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
7423f116 407
408 // Get the events matching our criteria
8263f802 409 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
7423f116 410
c635dcda 411 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
9064751b 412 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
c635dcda 413 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
414 // arguments to this function.
415
7bd1677c 416 $morehref = '';
417 if(!empty($courses)) {
e749554e 418 $courses = array_diff($courses, array(SITEID));
7bd1677c 419 if(count($courses) == 1) {
420 $morehref = '&amp;course='.reset($courses);
421 }
c635dcda 422 }
423
dd97c328 424 if ($events !== false) {
425
426 $modinfo =& get_fast_modinfo($COURSE);
fa22fd5f 427
7423f116 428 foreach($events as $event) {
dc6cb74e 429
dd97c328 430
431 if (!empty($event->modulename)) {
432 if ($event->courseid == $COURSE->id) {
433 if (isset($modinfo->instances[$event->modulename][$event->instance])) {
434 $cm = $modinfo->instances[$event->modulename][$event->instance];
435 if (!$cm->uservisible) {
436 continue;
437 }
438 }
439 } else {
440 if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
dc6cb74e 441 continue;
442 }
dd97c328 443 if (!coursemodule_visible_for_user($cm)) {
dc6cb74e 444 continue;
445 }
dd97c328 446 }
447 if ($event->modulename == 'assignment'){
448 // TODO: rewrite this hack somehow
aa6c1ced 449 if (!calendar_edit_event_allowed($event)){ // cannot manage entries, eg. student
62d11d77 450 if (!$assignment = $DB->get_record('assignment', array('id'=>$event->instance))) {
f581f8d6 451 // print_error("invalidid", 'assignment');
dd97c328 452 continue;
453 }
454 // assign assignment to assignment object to use hidden_is_hidden method
455 require_once($CFG->dirroot.'/mod/assignment/lib.php');
456
457 if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php')) {
458 continue;
459 }
460 require_once ($CFG->dirroot.'/mod/assignment/type/'.$assignment->assignmenttype.'/assignment.class.php');
461
462 $assignmentclass = 'assignment_'.$assignment->assignmenttype;
463 $assignmentinstance = new $assignmentclass($cm->id, $assignment, $cm);
464
465 if ($assignmentinstance->description_is_hidden()){//force not to show description before availability
466 $event->description = get_string('notavailableyet', 'assignment');
467 }
dc6cb74e 468 }
469 }
470 }
9d567178 471
dd97c328 472 if ($processed >= $display->maxevents) {
9d567178 473 break;
474 }
7423f116 475
3c134875 476 $event->time = calendar_format_event_time($event, $now, $morehref);
477 $output[] = $event;
478 ++$processed;
479 }
480 }
481 return $output;
482}
7423f116 483
9df8ff44 484function calendar_add_event_metadata($event) {
6b608f8f 485 global $CFG, $OUTPUT;
fb73f3b3 486
e295df44 487 //Support multilang in event->name
fb73f3b3 488 $event->name = format_string($event->name,true);
e295df44 489
3c134875 490 if(!empty($event->modulename)) { // Activity event
491 // The module name is set. I will assume that it has to be displayed, and
492 // also that it is an automatically-generated event. And of course that the
493 // fields for get_coursemodule_from_instance are set correctly.
494 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
7423f116 495
3c134875 496 if ($module === false) {
497 return;
498 }
9958a08c 499
3c134875 500 $modulename = get_string('modulename', $event->modulename);
a48bf079
DM
501 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
502 // will be used as alt text if the event icon
503 $eventtype = get_string($event->eventtype, $event->modulename);
504 } else {
505 $eventtype = '';
506 }
b5d0cafc 507 $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
9958a08c 508
10daca92 509 $event->icon = '<img height="16" width="16" src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" style="vertical-align: middle;" />';
fb73f3b3 510 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
3c134875 511 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$module->course.'">'.$coursecache[$module->course]->fullname.'</a>';
512 $event->cmid = $module->id;
9958a08c 513
9958a08c 514
3c134875 515 } else if($event->courseid == SITEID) { // Site event
b5d0cafc 516 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/site') . '" alt="'.get_string('globalevent', 'calendar').'" style="vertical-align: middle;" />';
90723839 517 $event->cssclass = 'calendar_event_global';
3c134875 518 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
519 calendar_get_course_cached($coursecache, $event->courseid);
b5d0cafc 520 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/course') . '" alt="'.get_string('courseevent', 'calendar').'" style="vertical-align: middle;" />';
3c134875 521 $event->courselink = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$event->courseid.'">'.$coursecache[$event->courseid]->fullname.'</a>';
90723839 522 $event->cssclass = 'calendar_event_course';
3c134875 523 } else if ($event->groupid) { // Group event
b5d0cafc 524 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/group') . '" alt="'.get_string('groupevent', 'calendar').'" style="vertical-align: middle;" />';
90723839 525 $event->cssclass = 'calendar_event_group';
3c134875 526 } else if($event->userid) { // User event
b5d0cafc 527 $event->icon = '<img height="16" width="16" src="'.$OUTPUT->pix_url('c/user') . '" alt="'.get_string('userevent', 'calendar').'" style="vertical-align: middle;" />';
90723839 528 $event->cssclass = 'calendar_event_user';
3c134875 529 }
9df8ff44 530 return $event;
e295df44 531}
9df8ff44 532
36dc3b71
SH
533/**
534 * Prints a calendar event
535 *
536 * @deprecated 2.0
537 */
76d9df3f 538function calendar_print_event($event, $showactions=true) {
ae53bd1d 539 global $CFG, $USER, $OUTPUT, $PAGE;
36dc3b71
SH
540 debugging('calendar_print_event is deprecated please update your code', DEBUG_DEVELOPER);
541 $renderer = $PAGE->get_renderer('core_calendar');
8bdc9cac
SH
542 if (!($event instanceof calendar_event)) {
543 $event = new calendar_event($event);
544 }
36dc3b71 545 echo $renderer->event($event);
7423f116 546}
547
8263f802 548/**
549 * Get calendar events
550 * @param int $tstart Start time of time range for events
551 * @param int $tend End time of time range for events
552 * @param array/int/boolean $users array of users, user id or boolean for all/no user events
553 * @param array/int/boolean $groups array of groups, group id or boolean for all/no group events
554 * @param array/int/boolean $courses array of courses, course id or boolean for all/no course events
555 * @param boolean $withduration whether only events starting within time range selected
556 * or events in progress/already started selected as well
557 * @param boolean $ignorehidden whether to select only visible events or all events
558 * @return array of selected events or an empty array if there aren't any (or there was an error)
559 */
560function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
62d11d77 561 global $DB;
562
7423f116 563 $whereclause = '';
564 // Quick test
565 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
8263f802 566 return array();
7423f116 567 }
482dbe0c 568
7423f116 569 if(is_array($users) && !empty($users)) {
570 // Events from a number of users
571 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 572 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
36dc3b71 573 } else if(is_numeric($users)) {
7423f116 574 // Events from one user
575 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 576 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
36dc3b71 577 } else if($users === true) {
7423f116 578 // Events from ALL users
579 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 580 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
36dc3b71 581 } else if($users === false) {
6e957c41 582 // No user at all, do nothing
f52f7413 583 }
482dbe0c 584
7423f116 585 if(is_array($groups) && !empty($groups)) {
586 // Events from a number of groups
587 if(!empty($whereclause)) $whereclause .= ' OR';
588 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
36dc3b71 589 } else if(is_numeric($groups)) {
7423f116 590 // Events from one group
591 if(!empty($whereclause)) $whereclause .= ' OR ';
592 $whereclause .= ' groupid = '.$groups;
36dc3b71 593 } else if($groups === true) {
7423f116 594 // Events from ALL groups
595 if(!empty($whereclause)) $whereclause .= ' OR ';
596 $whereclause .= ' groupid != 0';
597 }
482dbe0c 598 // boolean false (no groups at all): we don't need to do anything
599
36dc3b71
SH
600 if(is_array($courses) && !empty($courses)) {
601 if(!empty($whereclause)) {
602 $whereclause .= ' OR';
f52f7413 603 }
36dc3b71
SH
604 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
605 } else if(is_numeric($courses)) {
7423f116 606 // One course
607 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 608 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
36dc3b71 609 } else if ($courses === true) {
7423f116 610 // Events from ALL courses
611 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 612 $whereclause .= ' (groupid = 0 AND courseid != 0)';
7423f116 613 }
8c165fe9 614
482dbe0c 615 // Security check: if, by now, we have NOTHING in $whereclause, then it means
616 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
617 // events no matter what. Allowing the code to proceed might return a completely
618 // valid query with only time constraints, thus selecting ALL events in that time frame!
619 if(empty($whereclause)) {
8263f802 620 return array();
482dbe0c 621 }
622
7423f116 623 if($withduration) {
b4892fa2 624 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
7423f116 625 }
626 else {
627 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
628 }
629 if(!empty($whereclause)) {
630 // We have additional constraints
631 $whereclause = $timeclause.' AND ('.$whereclause.')';
632 }
633 else {
634 // Just basic time filtering
635 $whereclause = $timeclause;
636 }
f52f7413 637
0ad072de 638 if ($ignorehidden) {
639 $whereclause .= ' AND visible = 1';
640 }
641
62d11d77 642 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
8263f802 643 if ($events === false) {
644 $events = array();
645 }
646 return $events;
7423f116 647}
648
649function calendar_top_controls($type, $data) {
78946b9b 650 global $CFG, $CALENDARDAYS;
7423f116 651 $content = '';
652 if(!isset($data['d'])) {
653 $data['d'] = 1;
654 }
5147ad48 655
f21ed0f3 656 // Ensure course id passed if relevant
657 // Required due to changes in view/lib.php mainly (calendar_session_vars())
658 $courseid = '';
659 if (!empty($data['id'])) {
660 $courseid = '&amp;course='.$data['id'];
661 }
662
5147ad48 663 if(!checkdate($data['m'], $data['d'], $data['y'])) {
664 $time = time();
665 }
666 else {
667 $time = make_timestamp($data['y'], $data['m'], $data['d']);
668 }
669 $date = usergetdate($time);
e295df44 670
7423f116 671 $data['m'] = $date['mon'];
672 $data['y'] = $date['year'];
7423f116 673
2a06efcc 674 //Accessibility: calendar block controls, replaced <table> with <div>.
a84dea2c 675 //$nexttext = link_arrow_right(get_string('monthnext', 'access'), $url='', $accesshide=true);
676 //$prevtext = link_arrow_left(get_string('monthprev', 'access'), $url='', $accesshide=true);
2a06efcc 677
7423f116 678 switch($type) {
679 case 'frontpage':
680 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
681 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
a84dea2c 682 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'index.php?', 0, $nextmonth, $nextyear, $accesshide=true);
683 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'index.php?', 0, $prevmonth, $prevyear, true);
ae53bd1d 684
43c90b9b
RW
685 if (right_to_left()) {
686 $content .= "\n".'<div class="calendar-controls">'. $nextlink;
687 $content .= '<span class="hide"> | </span><span class="current"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month'.$courseid.'&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear')).'</a></span>';
688 $content .= '<span class="hide"> | </span>'. $prevlink ."\n";
689 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
690 } else {
691 $content .= "\n".'<div class="calendar-controls">'. $prevlink;
692 $content .= '<span class="hide"> | </span><span class="current"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month'.$courseid.'&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear')).'</a></span>';
693 $content .= '<span class="hide"> | </span>'. $nextlink ."\n";
694 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
695 }
ae53bd1d 696
7423f116 697 break;
698 case 'course':
699 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
700 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
a84dea2c 701 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $nextmonth, $nextyear, $accesshide=true);
702 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), 'view.php?id='.$data['id'].'&amp;', 0, $prevmonth, $prevyear, true);
703 $content .= "\n".'<div class="calendar-controls">'. $prevlink;
54052a7a 704 $content .= '<span class="hide"> | </span><span class="current"><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month'.$courseid.'&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear')).'</a></span>';
a84dea2c 705 $content .= '<span class="hide"> | </span>'. $nextlink ."\n";
f2de62da 706 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
7423f116 707 break;
708 case 'upcoming':
f21ed0f3 709 $content .= '<div style="text-align: center;"><a href="'.CALENDAR_URL.'view.php?view=upcoming"'.$courseid.'>'.userdate($time, get_string('strftimemonthyear'))."</a></div>\n";
7423f116 710 break;
711 case 'display':
e2ce18a5 712 $content .= '<h3><a href="'.calendar_get_link_href(CALENDAR_URL.'view.php?view=month'.$courseid.'&amp;', 1, $data['m'], $data['y']).'">'.userdate($time, get_string('strftimemonthyear'))."</a></h3>\n";
7423f116 713 break;
714 case 'month':
715 list($prevmonth, $prevyear) = calendar_sub_month($data['m'], $data['y']);
716 list($nextmonth, $nextyear) = calendar_add_month($data['m'], $data['y']);
5147ad48 717 $prevdate = make_timestamp($prevyear, $prevmonth, 1);
718 $nextdate = make_timestamp($nextyear, $nextmonth, 1);
a84dea2c 719 $content .= "\n".'<div class="calendar-controls">';
f21ed0f3 720 $content .= calendar_get_link_previous(userdate($prevdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $prevmonth, $prevyear);
ed9f9947 721 $content .= '<span class="hide"> | </span><h1 class="current">'.userdate($time, get_string('strftimemonthyear'))."</h1>\n";
f21ed0f3 722 $content .= '<span class="hide"> | </span>'.calendar_get_link_next(userdate($nextdate, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', 1, $nextmonth, $nextyear);
f2de62da 723 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
7423f116 724 break;
725 case 'day':
726 $data['d'] = $date['mday']; // Just for convenience
5147ad48 727 $prevdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] - 1));
728 $nextdate = usergetdate(make_timestamp($data['y'], $data['m'], $data['d'] + 1));
f2bffd9e 729 $prevname = calendar_wday_name($CALENDARDAYS[$prevdate['wday']]);
730 $nextname = calendar_wday_name($CALENDARDAYS[$nextdate['wday']]);
a84dea2c 731 $content .= "\n".'<div class="calendar-controls">';
f21ed0f3 732 $content .= calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', $prevdate['mday'], $prevdate['mon'], $prevdate['year']);
e295df44 733
6e8e8ec6 734 // Get the format string
735 $text = get_string('strftimedaydate');
3477a900 736 /*
6e8e8ec6 737 // Regexp hackery to make a link out of the month/year part
6dbcacee 738 $text = preg_replace('/(%B.+%Y|%Y.+%B|%Y.+%m[^ ]+)/', '<a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $data['m'], $data['y']).'">\\1</a>', $text);
739 $text = preg_replace('/(F.+Y|Y.+F|Y.+m[^ ]+)/', '<a href="'.calendar_get_link_href('view.php?view=month&amp;', 1, $data['m'], $data['y']).'">\\1</a>', $text);
3477a900 740 */
6e8e8ec6 741 // Replace with actual values and lose any day leading zero
3477a900 742 $text = userdate($time, $text);
6e8e8ec6 743 // Print the actual thing
a7c385e6 744 $content .= '<span class="hide"> | </span><span class="current">'.$text.'</span>';
6e8e8ec6 745
f21ed0f3 746 $content .= '<span class="hide"> | </span>'. calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', $nextdate['mday'], $nextdate['mon'], $nextdate['year']);
f2de62da 747 $content .= "<span class=\"clearer\"><!-- --></span></div>\n";
7423f116 748 break;
749 }
750 return $content;
751}
752
b4892fa2 753function calendar_filter_controls($type, $vars = NULL, $course = NULL, $courses = NULL) {
6b608f8f 754 global $CFG, $SESSION, $USER, $OUTPUT;
7423f116 755
48f508ab 756 $groupevents = true;
3cb9ee39 757 $getvars = '';
e295df44 758
7f4d18fc 759 $id = optional_param( 'id',0,PARAM_INT );
d715f7c4 760
34bf3ad4 761 switch($type) {
eb15f829 762 case 'event':
34bf3ad4 763 case 'upcoming':
34bf3ad4 764 case 'day':
c3f463ca 765 case 'month':
eb15f829 766 $getvars = '&amp;from='.$type;
34bf3ad4 767 break;
768 case 'course':
fac01360 769 if ($id > 0) {
7f4d18fc 770 $getvars = '&amp;from=course&amp;id='.$id;
2eb68e6f 771 } else {
772 $getvars = '&amp;from=course';
773 }
5a74ffd3 774 if (isset($course->groupmode) and $course->groupmode == NOGROUPS and $course->groupmodeforce) {
34bf3ad4 775 $groupevents = false;
776 }
777 break;
d715f7c4 778 }
34bf3ad4 779
3cb9ee39 780 if (!empty($vars)) {
34bf3ad4 781 $getvars .= '&amp;'.$vars;
48f508ab 782 }
7423f116 783
2ad2cbc3 784 $content = '<table>';
7423f116 785
48f508ab 786 $content .= '<tr>';
787 if($SESSION->cal_show_global) {
90723839 788 $content .= '<td class="eventskey calendar_event_global" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showglobal'.$getvars."'".'" /></td>';
b4892fa2 789 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_hideglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
fdbffa54 790 } else {
b5d0cafc 791 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showglobal', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showglobal'.$getvars."'".'" /></td>';
b4892fa2 792 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showglobal'.$getvars.'" title="'.get_string('tt_showglobal', 'calendar').'">'.get_string('global', 'calendar').'</a></td>'."\n";
48f508ab 793 }
e3bb6401 794 if($SESSION->cal_show_course) {
90723839 795 $content .= '<td class="eventskey calendar_event_course" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidecourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showcourses'.$getvars."'".'" /></td>';
fdbffa54 796 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_hidecourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
797 } else {
b5d0cafc 798 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_showcourse', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showcourses'.$getvars."'".'" /></td>';
fdbffa54 799 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showcourses'.$getvars.'" title="'.get_string('tt_showcourse', 'calendar').'">'.get_string('course', 'calendar').'</a></td>'."\n";
aa6c1ced 800
e3bb6401 801 }
48f508ab 802
b4892fa2 803
4f0c2d00 804 if (isloggedin() && !isguestuser()) {
e3bb6401 805 $content .= "</tr>\n<tr>";
10b1d598 806
807 if($groupevents) {
43c3ffbe 808 // This course MIGHT have group events defined, so show the filter
809 if($SESSION->cal_show_groups) {
90723839 810 $content .= '<td class="eventskey calendar_event_group" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hidegroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showgroups'.$getvars."'".'" /></td>';
fdbffa54 811 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_hidegroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
e3bb6401 812 } else {
b5d0cafc 813 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showgroups', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showgroups'.$getvars."'".'" /></td>';
fdbffa54 814 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showgroups'.$getvars.'" title="'.get_string('tt_showgroups', 'calendar').'">'.get_string('group', 'calendar').'</a></td>'."\n";
43c3ffbe 815 }
e3bb6401 816 } else {
43c3ffbe 817 // This course CANNOT have group events, so lose the filter
5c53988f 818 $content .= '<td style="width: 11px;"></td><td>&nbsp;</td>'."\n";
fdbffa54 819 }
820 if($SESSION->cal_show_user) {
90723839 821 $content .= '<td class="eventskey calendar_event_user" style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/hide') . '" class="iconsmall" alt="'.get_string('hide').'" title="'.get_string('tt_hideuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showuser'.$getvars."'".'" /></td>';
fdbffa54 822 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_hideuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
823 } else {
b5d0cafc 824 $content .= '<td style="width: 11px;"><img src="'.$OUTPUT->pix_url('t/show') . '" class="iconsmall" alt="'.get_string('show').'" title="'.get_string('tt_showuser', 'calendar').'" style="cursor:pointer" onclick="location.href='."'".CALENDAR_URL.'set.php?var=showuser'.$getvars."'".'" /></td>';
fdbffa54 825 $content .= '<td><a href="'.CALENDAR_URL.'set.php?var=showuser'.$getvars.'" title="'.get_string('tt_showuser', 'calendar').'">'.get_string('user', 'calendar').'</a></td>'."\n";
48f508ab 826 }
827 }
828 $content .= "</tr>\n</table>\n";
829
7423f116 830 return $content;
831}
832
833function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
834
0ef7c973 835 static $shortformat;
836 if(empty($shortformat)) {
e70fdac0 837 $shortformat = get_string('strftimedayshort');
0ef7c973 838 }
839
7423f116 840 if($now === false) {
841 $now = time();
842 }
843
844 // To have it in one place, if a change is needed
e70fdac0 845 $formal = userdate($tstamp, $shortformat);
7423f116 846
7b38bfa6 847 $datestamp = usergetdate($tstamp);
848 $datenow = usergetdate($now);
7423f116 849
850 if($usecommonwords == false) {
851 // We don't want words, just a date
852 return $formal;
853 }
7b38bfa6 854 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
7423f116 855 // Today
856 return get_string('today', 'calendar');
857 }
7b38bfa6 858 else if(
859 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
860 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
861 ) {
7423f116 862 // Yesterday
863 return get_string('yesterday', 'calendar');
864 }
7b38bfa6 865 else if(
866 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
867 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
868 ) {
7423f116 869 // Tomorrow
870 return get_string('tomorrow', 'calendar');
871 }
872 else {
873 return $formal;
874 }
875}
876
877function calendar_time_representation($time) {
1b0ebe79 878 static $langtimeformat = NULL;
879 if($langtimeformat === NULL) {
880 $langtimeformat = get_string('strftimetime');
881 }
882 $timeformat = get_user_preferences('calendar_timeformat');
c7dd2550 883 if(empty($timeformat)){
884 $timeformat = get_config(NULL,'calendar_site_timeformat');
885 }
1b0ebe79 886 // The ? is needed because the preference might be present, but empty
887 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
7423f116 888}
889
e295df44 890/**
891 * TODO document
892 */
7423f116 893function calendar_get_link_href($linkbase, $d, $m, $y) {
894 if(empty($linkbase)) return '';
895 $paramstr = '';
896 if(!empty($d)) $paramstr .= '&amp;cal_d='.$d;
897 if(!empty($m)) $paramstr .= '&amp;cal_m='.$m;
898 if(!empty($y)) $paramstr .= '&amp;cal_y='.$y;
899 if(!empty($paramstr)) $paramstr = substr($paramstr, 5);
900 return $linkbase.$paramstr;
901}
902
e295df44 903/**
904 * TODO document
905 */
7423f116 906function calendar_get_link_tag($text, $linkbase, $d, $m, $y) {
907 $href = calendar_get_link_href($linkbase, $d, $m, $y);
908 if(empty($href)) return $text;
909 return '<a href="'.$href.'">'.$text.'</a>';
910}
911
a84dea2c 912/**
913 * Build and return a previous month HTML link, with an arrow.
914 * @param string $text The text label.
915 * @param string $linkbase The URL stub.
916 * @param int $d $m $y Day of month, month and year numbers.
917 * @param bool $accesshide Default visible, or hide from all except screenreaders.
918 * @return string HTML string.
919 */
920function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide=false) {
921 $href = calendar_get_link_href($linkbase, $d, $m, $y);
922 if(empty($href)) return $text;
923 return link_arrow_left($text, $href, $accesshide, 'previous');
924}
925
926/**
927 * Build and return a next month HTML link, with an arrow.
928 * @param string $text The text label.
929 * @param string $linkbase The URL stub.
930 * @param int $d $m $y Day of month, month and year numbers.
931 * @param bool $accesshide Default visible, or hide from all except screenreaders.
932 * @return string HTML string.
933 */
934function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide=false) {
935 $href = calendar_get_link_href($linkbase, $d, $m, $y);
936 if(empty($href)) return $text;
ae53bd1d 937
a84dea2c 938 return link_arrow_right($text, $href, $accesshide, 'next');
939}
940
7423f116 941function calendar_wday_name($englishname) {
942 return get_string(strtolower($englishname), 'calendar');
943}
944
945function calendar_days_in_month($month, $year) {
7b38bfa6 946 return intval(date('t', mktime(0, 0, 0, $month, 1, $year)));
7423f116 947}
948
6605ff8c 949function calendar_get_block_upcoming($events, $linkhref = NULL) {
7423f116 950 $content = '';
951 $lines = count($events);
396b61f0 952 if (!$lines) {
953 return $content;
954 }
7423f116 955
396b61f0 956 for ($i = 0; $i < $lines; ++$i) {
b0ac9180 957 if (!isset($events[$i]->time)) { // Just for robustness
958 continue;
959 }
9df8ff44 960 $events[$i] = calendar_add_event_metadata($events[$i]);
ea21c1f4 961 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span> ';
43c3ffbe 962 if (!empty($events[$i]->referer)) {
7423f116 963 // That's an activity event, so let's provide the hyperlink
396b61f0 964 $content .= $events[$i]->referer;
965 } else {
e749554e 966 if(!empty($linkhref)) {
967 $ed = usergetdate($events[$i]->timestart);
968 $href = calendar_get_link_href(CALENDAR_URL.$linkhref, $ed['mday'], $ed['mon'], $ed['year']);
53d8fac0 969 $content .= '<a href="'.$href.'#event_'.$events[$i]->id.'">'.$events[$i]->name.'</a>';
e749554e 970 }
971 else {
972 $content .= $events[$i]->name;
973 }
7423f116 974 }
9ecf051d 975 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
976 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
396b61f0 977 if ($i < $lines - 1) $content .= '<hr />';
7423f116 978 }
979
980 return $content;
7423f116 981}
982
983function calendar_add_month($month, $year) {
984 if($month == 12) {
985 return array(1, $year + 1);
986 }
987 else {
988 return array($month + 1, $year);
989 }
990}
991
992function calendar_sub_month($month, $year) {
993 if($month == 1) {
994 return array(12, $year - 1);
995 }
996 else {
997 return array($month - 1, $year);
998 }
999}
1000
7c50db30 1001function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
7423f116 1002 $eventsbyday = array();
1003 $typesbyday = array();
1004 $durationbyday = array();
1005
1006 if($events === false) {
1007 return;
1008 }
1009
7423f116 1010 foreach($events as $event) {
7423f116 1011
7b38bfa6 1012 $startdate = usergetdate($event->timestart);
b4892fa2 1013 // Set end date = start date if no duration
1014 if ($event->timeduration) {
1015 $enddate = usergetdate($event->timestart + $event->timeduration - 1);
1016 } else {
1017 $enddate = $startdate;
1018 }
7423f116 1019
7b38bfa6 1020 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
ef618501 1021 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
7b38bfa6 1022 // Out of bounds
1023 continue;
7423f116 1024 }
1025
7b38bfa6 1026 $eventdaystart = intval($startdate['mday']);
7423f116 1027
7b38bfa6 1028 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1029 // Give the event to its day
1030 $eventsbyday[$eventdaystart][] = $event->id;
7423f116 1031
7b38bfa6 1032 // Mark the day as having such an event
9064751b 1033 if($event->courseid == SITEID && $event->groupid == 0) {
7b38bfa6 1034 $typesbyday[$eventdaystart]['startglobal'] = true;
b4892fa2 1035 // Set event class for global event
90723839 1036 $events[$event->id]->class = 'calendar_event_global';
7b38bfa6 1037 }
c3d3b6d4 1038 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
7b38bfa6 1039 $typesbyday[$eventdaystart]['startcourse'] = true;
b4892fa2 1040 // Set event class for course event
90723839 1041 $events[$event->id]->class = 'calendar_event_course';
7b38bfa6 1042 }
1043 else if($event->groupid) {
1044 $typesbyday[$eventdaystart]['startgroup'] = true;
b4892fa2 1045 // Set event class for group event
90723839 1046 $events[$event->id]->class = 'calendar_event_group';
7b38bfa6 1047 }
1048 else if($event->userid) {
1049 $typesbyday[$eventdaystart]['startuser'] = true;
b4892fa2 1050 // Set event class for user event
90723839 1051 $events[$event->id]->class = 'calendar_event_user';
7b38bfa6 1052 }
1053 }
7423f116 1054
7b38bfa6 1055 if($event->timeduration == 0) {
1056 // Proceed with the next
1057 continue;
1058 }
7423f116 1059
7b38bfa6 1060 // The event starts on $month $year or before. So...
ef618501 1061 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
7b38bfa6 1062
1063 // Also, it ends on $month $year or later...
1064 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1065
1066 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1067 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1068 $durationbyday[$i][] = $event->id;
9064751b 1069 if($event->courseid == SITEID && $event->groupid == 0) {
7b38bfa6 1070 $typesbyday[$i]['durationglobal'] = true;
1071 }
c3d3b6d4 1072 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
7b38bfa6 1073 $typesbyday[$i]['durationcourse'] = true;
1074 }
1075 else if($event->groupid) {
1076 $typesbyday[$i]['durationgroup'] = true;
1077 }
1078 else if($event->userid) {
1079 $typesbyday[$i]['durationuser'] = true;
7423f116 1080 }
1081 }
7b38bfa6 1082
7423f116 1083 }
1084 return;
1085}
1086
b63c0ee5 1087function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1088 $module = get_coursemodule_from_instance($modulename, $instance);
7423f116 1089
1090 if($module === false) return false;
b63c0ee5 1091 if(!calendar_get_course_cached($coursecache, $module->course)) {
7423f116 1092 return false;
1093 }
1094 return $module;
1095}
1096
1097function calendar_get_course_cached(&$coursecache, $courseid) {
62d11d77 1098 global $COURSE, $DB;
1099
b571c6b3 1100 if (!isset($coursecache[$courseid])) {
1101 if ($courseid == $COURSE->id) {
1102 $coursecache[$courseid] = $COURSE;
1103 } else {
62d11d77 1104 $coursecache[$courseid] = $DB->get_record('course', array('id'=>$courseid));
b571c6b3 1105 }
7423f116 1106 }
1107 return $coursecache[$courseid];
1108}
1109
dd97c328 1110function calendar_session_vars($course=null) {
7423f116 1111 global $SESSION, $USER;
1112
1113 if(!isset($SESSION->cal_course_referer)) {
1114 $SESSION->cal_course_referer = 0;
1115 }
1116 if(!isset($SESSION->cal_show_global)) {
1117 $SESSION->cal_show_global = true;
1118 }
1119 if(!isset($SESSION->cal_show_groups)) {
1120 $SESSION->cal_show_groups = true;
1121 }
1122 if(!isset($SESSION->cal_show_course)) {
1123 $SESSION->cal_show_course = true;
1124 }
1125 if(!isset($SESSION->cal_show_user)) {
89adb174 1126 $SESSION->cal_show_user = true;
7423f116 1127 }
76d9df3f 1128 if ($course !== null) {
dd97c328 1129 // speedup hack for calendar related blocks
1130 $SESSION->cal_courses_shown = array($course->id => $course);
aa6c1ced 1131 } else {
43c3ffbe 1132 $SESSION->cal_courses_shown = calendar_get_default_courses(true);
dd97c328 1133 }
89adb174 1134 if(empty($SESSION->cal_users_shown)) {
1135 // The empty() instead of !isset() here makes a whole world of difference,
1136 // as it will automatically change to the user's id when the user first logs
1137 // in. With !isset(), it would never do that.
4f0c2d00
PS
1138 $SESSION->cal_users_shown = isloggedin() ? $USER->id : false;
1139 } else if(is_numeric($SESSION->cal_users_shown) && isloggedin() && $SESSION->cal_users_shown != $USER->id) {
89adb174 1140 // Follow the white rabbit, for example if a teacher logs in as a student
1141 $SESSION->cal_users_shown = $USER->id;
1142 }
7423f116 1143}
1144
7423f116 1145function calendar_set_referring_course($courseid) {
1146 global $SESSION;
1147 $SESSION->cal_course_referer = intval($courseid);
1148}
1149
43c3ffbe 1150function calendar_set_filters(&$courses, &$group, &$user, $courseeventsfrom = NULL, $groupeventsfrom = NULL, $ignorefilters = false) {
62d11d77 1151 global $SESSION, $USER, $CFG, $DB;
257e3f4c 1152
43c3ffbe 1153 // Insidious bug-wannabe: setting $SESSION->cal_courses_shown to $course->id would cause
51f8a12f 1154 // the code to function incorrectly UNLESS we convert it to an integer. One case where
1155 // PHP's loose type system works against us.
43c3ffbe 1156 if(is_string($SESSION->cal_courses_shown)) {
1157 $SESSION->cal_courses_shown = intval($SESSION->cal_courses_shown);
51f8a12f 1158 }
43c3ffbe 1159 if($courseeventsfrom === NULL) {
aa6c1ced 1160 $courseeventsfrom = $SESSION->cal_courses_shown;
d12e3ff2 1161 }
aa6c1ced 1162
d12e3ff2 1163 // MDL-9059, $courseeventsfrom can be an int, or an array of ints, or an array of course objects
1164 // convert all to array of objects
1165 // we probably should do some clean up and make sure that session is set to use the proper form
1166 if (is_int($courseeventsfrom)) { // case of an int, e.g. calendar view page
1167 $c = array();
62d11d77 1168 $c[$courseeventsfrom] = $DB->get_record('course', array('id'=>$courseeventsfrom));
d12e3ff2 1169 $courseeventsfrom = $c;
1170 } else if (is_array($courseeventsfrom)) { // case of an array of ints, e.g. course home page
dd97c328 1171 foreach ($courseeventsfrom as $i=>$courseid) { // TODO: this seems wrong, the array is often constructed as [courseid] => 1 ???
d12e3ff2 1172 if (is_int($courseid)) {
62d11d77 1173 $courseeventsfrom[$i] = $DB->get_record('course', array('id'=>$courseid));
aa6c1ced
PS
1174 }
1175 }
7423f116 1176 }
d12e3ff2 1177
43c3ffbe 1178 if($groupeventsfrom === NULL) {
1179 $groupeventsfrom = $SESSION->cal_courses_shown;
7423f116 1180 }
1181
43c3ffbe 1182 if(($SESSION->cal_show_course && $SESSION->cal_show_global) || $ignorefilters) {
1183 if(is_int($courseeventsfrom)) {
9064751b 1184 $courses = array(SITEID, $courseeventsfrom);
7423f116 1185 }
43c3ffbe 1186 else if(is_array($courseeventsfrom)) {
1187 $courses = array_keys($courseeventsfrom);
9064751b 1188 $courses[] = SITEID;
7423f116 1189 }
1190 }
43c3ffbe 1191 else if($SESSION->cal_show_course) {
1192 if(is_int($courseeventsfrom)) {
1193 $courses = array($courseeventsfrom);
7423f116 1194 }
43c3ffbe 1195 else if(is_array($courseeventsfrom)) {
1196 $courses = array_keys($courseeventsfrom);
7423f116 1197 }
e749554e 1198 $courses = array_diff($courses, array(SITEID));
7423f116 1199 }
1200 else if($SESSION->cal_show_global) {
e749554e 1201 $courses = array(SITEID);
7423f116 1202 }
1203 else {
1204 $courses = false;
1205 }
e295df44 1206 //BUG 6130 clean $courses array as SESSION has bad entries.
0e6a8f4b 1207 // [pj] TODO: See if this has to do with my new change in get_default_courses and can be taken out
1384da1e 1208 if (is_array($courses)) {
1209 foreach ($courses as $index => $value) {
1210 if (empty($value)) unset($courses[$index]);
1211 }
7c50db30 1212
1213 // Sort courses for consistent colour highlighting
1214 // Effectively ignoring SITEID as setting as last course id
1215 $key = array_search(SITEID, $courses);
1216 if ($key !== false) {
1217 unset($courses[$key]);
1218 sort($courses);
1219 $courses[] = SITEID;
1220 } else {
1221 sort($courses);
1222 }
0e6a8f4b 1223 }
7423f116 1224
43c3ffbe 1225 if($SESSION->cal_show_user || $ignorefilters) {
89adb174 1226 // This doesn't work for arrays yet (maybe someday it will)
1227 $user = $SESSION->cal_users_shown;
7423f116 1228 }
1229 else {
1230 $user = false;
1231 }
43c3ffbe 1232 if($SESSION->cal_show_groups || $ignorefilters) {
1233 if(is_int($groupeventsfrom)) {
1234 $groupcourses = array($groupeventsfrom);
7423f116 1235 }
43c3ffbe 1236 else if(is_array($groupeventsfrom)) {
1237 $groupcourses = array_keys($groupeventsfrom);
1238 }
257e3f4c 1239
9c37662f 1240 // XXX TODO: not sure how to replace $CFG->calendar_adminseesall
ef35441d 1241 if(has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM)) && !empty($CFG->calendar_adminseesall)) {
257e3f4c 1242 $group = true;
1243 }
1244 else {
1245 $grouparray = array();
69762501 1246
257e3f4c 1247 // We already have the courses to examine in $courses
1248 // For each course...
37d87d11 1249
257e3f4c 1250 foreach($groupcourses as $courseid) {
69762501 1251
37875ac5 1252 if (!isset($courseeventsfrom[$courseid]->context)) { // SHOULD be set MDL-11221
8397874d 1253 if (is_object($courseeventsfrom[$courseid])) {
1254 $courseeventsfrom[$courseid]->context = get_context_instance(CONTEXT_COURSE, $courseid);
1255 }
37875ac5 1256 }
1257
257e3f4c 1258 // If the user is an editing teacher in there,
4f0c2d00 1259 if (isloggedin() && isset($courseeventsfrom[$courseid]->context) && has_capability('moodle/calendar:manageentries', $courseeventsfrom[$courseid]->context)) {
69762501 1260 // If this course has groups, show events from all of them
b8227b88 1261 if(is_int($groupeventsfrom)) {
37875ac5 1262 if (is_object($courseeventsfrom[$courseid])) { // SHOULD be set MDL-11221
1263 $courserecord = $courseeventsfrom[$courseid];
1264 } else {
62d11d77 1265 $courserecord = $DB->get_record('course', array('id'=>$courseid));
aa6c1ced 1266 }
62d11d77 1267 $courserecord = $DB->get_record('course', array('id'=>$courseid));
b8227b88 1268 if ($courserecord->groupmode != NOGROUPS || !$courserecord->groupmodeforce) {
1269 $groupids[] = $courseid;
1270 }
1271 }
1272 else if(isset($SESSION->cal_courses_shown[$courseid]) && ($SESSION->cal_courses_shown[$courseid]->groupmode != NOGROUPS || !$SESSION->cal_courses_shown[$courseid]->groupmodeforce)) {
37d87d11 1273 $groupids[] = $courseid;
257e3f4c 1274 }
1275 }
69762501 1276
1277 // Otherwise (not editing teacher) show events from the group he is a member of
257e3f4c 1278 else if(isset($USER->groupmember[$courseid])) {
fa22fd5f 1279 //changed to 2D array
1280 foreach ($USER->groupmember[$courseid] as $groupid){
1281 $grouparray[] = $groupid;
1282 }
7423f116 1283 }
1284 }
e295df44 1285
6b4aeb31 1286 if (!empty($groupids)) {
f6ee5e04 1287 $sql = "SELECT *
62d11d77 1288 FROM {groups}
6b4aeb31 1289 WHERE courseid IN (".implode(',', $groupids).')';
e295df44 1290
62d11d77 1291 if ($grouprecords = $DB->get_records_sql($sql, null)) {
f6ee5e04 1292 foreach ($grouprecords as $grouprecord) {
1293 $grouparray[] = $grouprecord->id;
1294 }
6b4aeb31 1295 }
1296 }
e295df44 1297
257e3f4c 1298 if(empty($grouparray)) {
1299 $group = false;
1300 }
1301 else {
1302 $group = $grouparray;
6c9584d1 1303 }
7423f116 1304 }
e295df44 1305
7423f116 1306 }
1307 else {
1308 $group = false;
1309 }
1310}
1311
1312function calendar_edit_event_allowed($event) {
62d11d77 1313 global $USER, $DB;
7423f116 1314
2ac8da76 1315 // Must be logged in
1316 if (!isloggedin()) {
1317 return false;
1318 }
1319
89491dbd 1320 // can not be using guest account
2396a414 1321 if (isguestuser()) {
e295df44 1322 return false;
89491dbd 1323 }
e295df44 1324
ef35441d 1325 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
89491dbd 1326 // if user has manageentries at site level, return true
28ee98c5 1327 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
89491dbd 1328 return true;
f52f7413 1329 }
e295df44 1330
c0a2c361 1331 // if groupid is set, it's definitely a group event
438e4add 1332 if (!empty($event->groupid)) {
f63d2922 1333 // Allow users to add/edit group events if:
1334 // 1) They have manageentries (= entries for whole course)
1335 // 2) They have managegroupentries AND are in the group
62d11d77 1336 $group = $DB->get_record('groups', array('id'=>$event->groupid));
f63d2922 1337 return $group && (
1338 has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $group->courseid)) ||
1339 (has_capability('moodle/calendar:managegroupentries', get_context_instance(CONTEXT_COURSE, $group->courseid))
1340 && groups_is_member($event->groupid)));
438e4add 1341 } else if (!empty($event->courseid)) {
c0a2c361 1342 // if groupid is not set, but course is set,
1343 // it's definiely a course event
e295df44 1344 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
438e4add 1345 } else if (!empty($event->userid) && $event->userid == $USER->id) {
c0a2c361 1346 // if course is not set, but userid id set, it's a user event
1347 return (has_capability('moodle/calendar:manageownentries', $sitecontext));
e295df44 1348 }
7423f116 1349 return false;
1350}
1351
8c54cec6 1352function calendar_get_default_courses($ignoreref = false) {
62d11d77 1353 global $USER, $CFG, $SESSION, $DB;
9ff136e5 1354
8c54cec6 1355 if(!empty($SESSION->cal_course_referer) && !$ignoreref) {
4c7d1137 1356 return array($SESSION->cal_course_referer => 1);
9ff136e5 1357 }
7423f116 1358
4f0c2d00 1359 if (!isloggedin()) {
2ef75eee 1360 return array();
1361 }
1362
7423f116 1363 $courses = array();
d9d16e56 1364 if (has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_SYSTEM))) {
03bb25e1 1365 if (!empty($CFG->calendar_adminseesall)) {
62d11d77 1366 $courses = $DB->get_records_sql('SELECT id, 1 FROM {course}');
86f092d2 1367 return $courses;
1368 }
95a89225 1369 }
e295df44 1370
df997f84 1371 $courses = enrol_get_my_courses();
37d87d11 1372
1373 return $courses;
7423f116 1374}
1375
1e1ff33b 1376function calendar_preferences_button() {
1377 global $CFG, $USER;
7423f116 1378
1379 // Guests have no preferences
4f0c2d00 1380 if (!isloggedin() || isguestuser()) {
7423f116 1381 return '';
1382 }
1383
4aea3cc7 1384 return "<form method=\"get\" ".
1e1ff33b 1385 " action=\"$CFG->wwwroot/calendar/preferences.php\">".
2aab6488 1386 "<div><input type=\"submit\" value=\"".get_string("preferences", "calendar")." ...\" /></div></form>";
7423f116 1387}
1388
b4892fa2 1389function calendar_format_event_time($event, $now, $morehref, $usecommonwords = true, $showtime=0) {
8f896582 1390 $startdate = usergetdate($event->timestart);
1391 $enddate = usergetdate($event->timestart + $event->timeduration);
1392 $usermidnightstart = usergetmidnight($event->timestart);
1393
1394 if($event->timeduration) {
1395 // To avoid doing the math if one IF is enough :)
1396 $usermidnightend = usergetmidnight($event->timestart + $event->timeduration);
1397 }
1398 else {
1399 $usermidnightend = $usermidnightstart;
1400 }
1401
1402 // OK, now to get a meaningful display...
1403 // First of all we have to construct a human-readable date/time representation
1404
b4892fa2 1405 if($event->timeduration) {
8f896582 1406 // It has a duration
b4892fa2 1407 if($usermidnightstart == $usermidnightend ||
1408 ($event->timestart == $usermidnightstart) && ($event->timeduration == 86400 || $event->timeduration == 86399) ||
1409 ($event->timestart + $event->timeduration <= $usermidnightstart + 86400)) {
8f896582 1410 // But it's all on the same day
8f896582 1411 $timestart = calendar_time_representation($event->timestart);
1412 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
b4892fa2 1413 $time = $timestart.' <strong>&raquo;</strong> '.$timeend;
1414
1415 if ($event->timestart == $usermidnightstart && ($event->timeduration == 86400 || $event->timeduration == 86399)) {
1416 $time = get_string('allday', 'calendar');
1417 }
8f896582 1418
1419 // Set printable representation
b4892fa2 1420 if (!$showtime) {
1421 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1422 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).', '.$time;
1423 } else {
1424 $eventtime = $time;
1425 }
1426 } else {
8f896582 1427 // It spans two or more days
b4892fa2 1428 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords).', ';
1429 if ($showtime == $usermidnightstart) {
1430 $daystart = '';
1431 }
8f896582 1432 $timestart = calendar_time_representation($event->timestart);
b4892fa2 1433 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords).', ';
1434 if ($showtime == $usermidnightend) {
1435 $dayend = '';
1436 }
8f896582 1437 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1438
1439 // Set printable representation
b4892fa2 1440 if ($now >= $usermidnightstart && $now < ($usermidnightstart + 86400)) {
1441 $eventtime = $timestart.' <strong>&raquo;</strong> '.calendar_get_link_tag($dayend, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
1442 $timeend;
1443 } else {
1444 $eventtime = calendar_get_link_tag($daystart, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).
1445 $timestart.' <strong>&raquo;</strong> '.calendar_get_link_tag($dayend, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $enddate['mday'], $enddate['mon'], $enddate['year']).
1446 $timeend;
1447 }
8f896582 1448 }
b4892fa2 1449 } else {
1c4bedd7 1450 $time = ' ';
8f896582 1451
1452 // Set printable representation
b4892fa2 1453 if (!$showtime) {
1454 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
1455 $eventtime = calendar_get_link_tag($day, CALENDAR_URL.'view.php?view=day'.$morehref.'&amp;', $startdate['mday'], $startdate['mon'], $startdate['year']).trim($time);
1456 } else {
1457 $eventtime = $time;
1458 }
1459 }
1460
1461 if($event->timestart + $event->timeduration < $now) {
1462 // It has expired
1463 $eventtime = '<span class="dimmed_text">'.str_replace(' href=', ' class="dimmed" href=', $eventtime).'</span>';
8f896582 1464 }
09d36284 1465
8f896582 1466 return $eventtime;
1467}
054193be 1468
86f092d2 1469function calendar_print_month_selector($name, $selected) {
86f092d2 1470 $months = array();
86f092d2 1471 for ($i=1; $i<=12; $i++) {
76ab1c33 1472 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
86f092d2 1473 }
d776d59e 1474 echo html_writer::select($months, $name, $selected, false);
86f092d2 1475}
1476
054193be 1477function calendar_get_filters_status() {
1478 global $SESSION;
1479
1480 $status = 0;
1481 if($SESSION->cal_show_global) {
1482 $status += 1;
1483 }
1484 if($SESSION->cal_show_course) {
1485 $status += 2;
1486 }
1487 if($SESSION->cal_show_groups) {
1488 $status += 4;
1489 }
1490 if($SESSION->cal_show_user) {
1491 $status += 8;
1492 }
1493 return $status;
1494}
1495
1496function calendar_set_filters_status($packed_bitfield) {
1497 global $SESSION, $USER;
1498
4f0c2d00 1499 if (!isloggedin()) {
054193be 1500 return false;
1501 }
1502
1503 $SESSION->cal_show_global = ($packed_bitfield & 1);
1504 $SESSION->cal_show_course = ($packed_bitfield & 2);
e295df44 1505 $SESSION->cal_show_groups = ($packed_bitfield & 4);
054193be 1506 $SESSION->cal_show_user = ($packed_bitfield & 8);
1507
1508 return true;
1509}
1510
86ac8b24 1511function calendar_get_allowed_types(&$allowed) {
62d11d77 1512 global $USER, $CFG, $SESSION, $DB;
86ac8b24 1513 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1514 $allowed->user = has_capability('moodle/calendar:manageownentries', $sitecontext);
1515 $allowed->groups = false; // This may change just below
1516 $allowed->courses = false; // This may change just below
1517 $allowed->site = has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
1518
f63d2922 1519 if(!empty($SESSION->cal_course_referer) && $SESSION->cal_course_referer != SITEID) {
62d11d77 1520 $course = $DB->get_record('course', array('id'=>$SESSION->cal_course_referer));
f63d2922 1521 $coursecontext = get_context_instance(CONTEXT_COURSE, $SESSION->cal_course_referer);
86ac8b24 1522
f63d2922 1523 if(has_capability('moodle/calendar:manageentries', $coursecontext)) {
1524 $allowed->courses = array($course->id => 1);
aa6c1ced 1525
f63d2922 1526 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1527 $allowed->groups = groups_get_all_groups($SESSION->cal_course_referer);
1528 }
1529 } else if(has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1530 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1531 $allowed->groups = groups_get_all_groups($SESSION->cal_course_referer, $USER->id);
1532 }
86ac8b24 1533 }
1534 }
1535}
1536
1537/**
1538 * see if user can add calendar entries at all
1539 * used to print the "New Event" button
1540 * @return bool
1541 */
1542function calendar_user_can_add_event() {
1543 calendar_get_allowed_types($allowed);
e295df44 1544 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
86ac8b24 1545}
76d9df3f
SH
1546
1547/**
1548 * Check wether the current user is permitted to add events
1549 *
1550 * @param object $event
1551 * @return bool
1552 */
1553function calendar_add_event_allowed($event) {
1554 global $USER, $DB;
1555
1556 // can not be using guest account
4f0c2d00 1557 if (!isloggedin() or isguestuser()) {
76d9df3f
SH
1558 return false;
1559 }
1560
1561 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
1562 // if user has manageentries at site level, always return true
1563 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1564 return true;
1565 }
1566
1567 switch ($event->eventtype) {
1568 case 'course':
1569 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1570
1571 case 'group':
1572 // Allow users to add/edit group events if:
1573 // 1) They have manageentries (= entries for whole course)
1574 // 2) They have managegroupentries AND are in the group
1575 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1576 return $group && (
1577 has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $group->courseid)) ||
1578 (has_capability('moodle/calendar:managegroupentries', get_context_instance(CONTEXT_COURSE, $group->courseid))
1579 && groups_is_member($event->groupid)));
1580
1581 case 'user':
1582 if ($event->userid == $USER->id) {
1583 return (has_capability('moodle/calendar:manageownentries', $sitecontext));
1584 }
1585 //there is no 'break;' intentionally
1586
1587 case 'site':
1588 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, SITEID));
1589
1590 default:
ddaff608
SH
1591 if (isset($event->courseid) && $event->courseid > 0) {
1592 return has_capability('moodle/calendar:manageentries', get_context_instance(CONTEXT_COURSE, $event->courseid));
1593 }
76d9df3f
SH
1594 return false;
1595 }
1596}
1597
1598/**
1599 * A class to manage calendar events
1600 *
1601 * This class provides the required functionality in order to manage calendar events.
1602 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1603 * better framework for dealing with calendar events in particular regard to file
1604 * handling through the new file API
1605 *
1606 * @property int $id The id within the event table
1607 * @property string $name The name of the event
1608 * @property string $description The description of the event
1609 * @property int $format The format of the description FORMAT_?
1610 * @property int $courseid The course the event is associated with (0 if none)
1611 * @property int $groupid The group the event is associated with (0 if none)
1612 * @property int $userid The user the event is associated with (0 if none)
1613 * @property int $repeatid If this is a repeated event this will be set to the
1614 * id of the original
1615 * @property string $modulename If added by a module this will be the module name
1616 * @property int $instance If added by a module this will be the module instance
1617 * @property string $eventtype The event type
1618 * @property int $timestart The start time as a timestamp
1619 * @property int $timeduration The duration of the event in seconds
1620 * @property int $visible 1 if the event is visible
1621 * @property int $uuid ?
1622 * @property int $sequence ?
1623 * @property int $timemodified The time last modified as a timestamp
1624 */
1625class calendar_event {
1626
1627 /**
1628 * An object containing the event properties can be accessed via the
1629 * magic __get/set methods
1630 * @var array
1631 */
1632 protected $properties = null;
1633 /**
1634 * The converted event discription with file paths resolved
1635 * This gets populated when someone requests description for the first time
1636 * @var string
1637 */
1638 protected $_description = null;
76d9df3f
SH
1639 /**
1640 * The options to use with this description editor
1641 * @var array
1642 */
1643 protected $editoroptions = array(
1644 'subdirs'=>false,
1645 'forcehttps'=>false,
2b35ed1a 1646 'maxfiles'=>-1,
76d9df3f
SH
1647 'maxbytes'=>null,
1648 'trusttext'=>false);
1649 /**
1650 * The context to use with the description editor
1651 * @var object
1652 */
1653 protected $editorcontext = null;
1654
1655 /**
1656 * Instantiates a new event and optionally populates its properties with the
1657 * data provided
1658 *
1659 * @param stdClass $data Optional. An object containing the properties to for
1660 * an event
1661 */
1662 public function __construct($data=null) {
c203a277 1663 global $CFG, $USER;
76d9df3f
SH
1664
1665 // First convert to object if it is not already (should either be object or assoc array)
1666 if (!is_object($data)) {
1667 $data = (object)$data;
1668 }
1669
1670 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
1671
1672 $data->eventrepeats = 0;
1673
1674 if (empty($data->id)) {
1675 $data->id = null;
1676 }
1677
c203a277
SH
1678 // Default to a user event
1679 if (empty($data->eventtype)) {
1680 $data->eventtype = 'user';
1681 }
1682
1683 // Default to the current user
1684 if (empty($data->userid)) {
1685 $data->userid = $USER->id;
1686 }
1687
76d9df3f
SH
1688 if (!empty($data->timeduration) && is_array($data->timeduration)) {
1689 $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
1690 }
1691 if (!empty($data->description) && is_array($data->description)) {
1692 $data->format = $data->description['format'];
1693 $data->description = $data->description['text'];
1694 } else if (empty($data->description)) {
1695 $data->description = '';
20e5da7d 1696 $data->format = editors_get_preferred_format();
76d9df3f 1697 }
c203a277
SH
1698 // Ensure form is defaulted correctly
1699 if (empty($data->format)) {
1700 $data->format = editors_get_preferred_format();
1701 }
76d9df3f
SH
1702
1703 $this->properties = $data;
1704 }
1705
1706 /**
1707 * Magic property method
1708 *
1709 * Attempts to call a set_$key method if one exists otherwise falls back
1710 * to simply set the property
1711 *
1712 * @param string $key
1713 * @param mixed $value
1714 */
1715 public function __set($key, $value) {
1716 if (method_exists($this, 'set_'.$key)) {
1717 $this->{'set_'.$key}($value);
1718 }
1719 $this->properties->{$key} = $value;
1720 }
1721
1722 /**
1723 * Magic get method
1724 *
1725 * Attempts to call a get_$key method to return the property and ralls over
1726 * to return the raw property
1727 *
1728 * @param str $key
1729 * @return mixed
1730 */
1731 public function __get($key) {
1732 if (method_exists($this, 'get_'.$key)) {
1733 return $this->{'get_'.$key}();
1734 }
c203a277
SH
1735 if (!isset($this->properties->{$key})) {
1736 throw new coding_exception('Undefined property requested');
1737 }
76d9df3f
SH
1738 return $this->properties->{$key};
1739 }
1740
1741 /**
1742 * Stupid PHP needs an isset magic method if you use the get magic method and
1743 * still want empty calls to work.... blah ~!
1744 *
1745 * @param string $key
1746 * @return bool
1747 */
1748 public function __isset($key) {
1749 return !empty($this->properties->{$key});
1750 }
1751
1752 /**
1753 * Returns an array of editoroptions for this event: Called by __get
1754 * Please use $blah = $event->editoroptions;
1755 * @return array
1756 */
1757 protected function get_editoroptions() {
1758 return $this->editoroptions;
1759 }
1760
1761 /**
1762 * Returns an event description: Called by __get
1763 * Please use $blah = $event->description;
1764 *
1765 * @return string
1766 */
1767 protected function get_description() {
1768 global $USER;
1769 if ($this->_description === null) {
1770 // Check if we have already resolved the context for this event
1771 if ($this->editorcontext === null) {
1772 // Switch on the event type to decide upon the appropriate context
1773 // to use for this event
1774 switch ($this->properties->eventtype) {
1775 case 'course':
1776 case 'group':
1777 // Course and group event files are served from the course context
1778 // and there are checks in plugin.php to ensure permissions are
1779 // followed
1780 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
1781 break;
1782 case 'user':
1783 // User context
1784 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
1785 break;
1786 case 'site':
1787 // Site context
1788 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
1789 break;
1790 default:
1791 // Hmmmm some modules use custom eventtype strings, if that is the
1792 // case we are going to abandon using files. Anything that uses a
1793 // custom type is being added manually through code
1794 return clean_text($this->properties->description, $this->properties->format);
1795 break;
1796 }
1797 }
1798
1799 // Work out the item id for the editor, if this is a repeated event then the files will
1800 // be associated with the original
1801 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
1802 $itemid = $this->properties->repeatid;
1803 } else {
1804 $itemid = $this->properties->id;
1805 }
1806
1807 // Convert file paths in the description so that things display correctly
64f93798 1808 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, 'calendar', 'event_description', $itemid);
76d9df3f
SH
1809 // Clean the text so no nasties get through
1810 $this->_description = clean_text($this->_description, $this->properties->format);
1811 }
1812 // Finally return the description
1813 return $this->_description;
1814 }
1815
1816 /**
1817 * Return the number of repeat events there are in this events series
aa6c1ced 1818 *
76d9df3f
SH
1819 * @return int
1820 */
1821 public function count_repeats() {
1822 global $DB;
1823 if (!empty($this->properties->repeatid)) {
1824 $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
1825 // We don't want to count ourselves
1826 $this->properties->eventrepeats--;
1827 }
1828 return $this->properties->eventrepeats;
1829 }
1830
1831 /**
1832 * Update or create an event within the database
1833 *
1834 * Pass in a object containing the event properties and this function will
1835 * insert it into the database and deal with any associated files
1836 *
1837 * @see add_event()
1838 * @see update_event()
1839 *
1840 * @param stdClass $data
1841 */
1842 public function update($data) {
1843 global $CFG, $DB, $USER;
1844
438e4add
SH
1845 foreach ($data as $key=>$value) {
1846 $this->properties->$key = $value;
1847 }
1848
76d9df3f
SH
1849 $this->properties->timemodified = time();
1850 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
1851
1852 if (empty($this->properties->id) || $this->properties->id < 1) {
1853
1854 if (!calendar_add_event_allowed($this->properties)) {
1855 print_error('nopermissions');
1856 }
1857
1858 if ($usingeditor) {
1859 switch ($this->properties->eventtype) {
1860 case 'user':
1861 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
1862 $this->properties->courseid = 0;
1863 $this->properties->groupid = 0;
1864 $this->properties->userid = $USER->id;
1865 break;
1866 case 'site':
1867 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
1868 $this->properties->courseid = SITEID;
1869 $this->properties->groupid = 0;
1870 $this->properties->userid = $USER->id;
1871 break;
1872 case 'course':
1873 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
1874 $this->properties->groupid = 0;
1875 $this->properties->userid = $USER->id;
1876 break;
1877 case 'group':
1878 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
1879 $this->properties->groupid = 0;
1880 $this->properties->userid = $USER->id;
1881 break;
1882 default:
1883 // Ewww we should NEVER get here, but just incase we do lets
1884 // fail gracefully
1885 $usingeditor = false;
1886 break;
1887 }
1888
1889 $editor = $this->properties->description;
1890 $this->properties->format = $this->properties->description['format'];
1891 $this->properties->description = $this->properties->description['text'];
1892 }
1893
1894 // Insert the event into the database
1895 $this->properties->id = $DB->insert_record('event', $this->properties);
1896
1897 if ($usingeditor) {
1898 $this->properties->description = file_save_draft_area_files(
1899 $editor['itemid'],
1900 $this->editorcontext->id,
64f93798
PS
1901 'calendar',
1902 'event_description',
76d9df3f
SH
1903 $this->properties->id,
1904 $this->editoroptions,
1905 $editor['text'],
1906 $this->editoroptions['forcehttps']);
1907
1908 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
1909 }
aa6c1ced 1910
76d9df3f
SH
1911 // Log the event entry.
1912 add_to_log($this->properties->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
1913
1914 $repeatedids = array();
1915
1916 if (!empty($this->properties->repeat)) {
1917 $this->properties->repeatid = $this->properties->id;
1918 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));
1919
1920 $eventcopy = clone($this->properties);
1921 unset($eventcopy->id);
1922
1923 for($i = 1; $i < $eventcopy->repeats; $i++) {
1924
1925 $eventcopy->timestart = ($eventcopy->timestart+WEEKSECS) + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart+WEEKSECS);
1926
1927 // Get the event id for the log record.
1928 $eventcopyid = $DB->insert_record('event', $eventcopy);
1929
1930 // If the context has been set delete all associated files
1931 if ($usingeditor) {
1932 $fs = get_file_storage();
64f93798 1933 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
76d9df3f
SH
1934 foreach ($files as $file) {
1935 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
1936 }
1937 }
1938
1939 $repeatedids[] = $eventcopyid;
1940 // Log the event entry.
1941 add_to_log($eventcopy->courseid, 'calendar', 'add', 'event.php?action=edit&amp;id='.$eventcopyid, $eventcopy->name);
1942 }
1943 }
1944
1945 // Hook for tracking added events
1946 self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
1947 return true;
1948 } else {
1949
1950 if(!calendar_edit_event_allowed($this->properties)) {
1951 print_error('nopermissions');
1952 }
1953
1954 if ($usingeditor) {
1955 if ($this->editorcontext !== null) {
1956 $this->properties->description = file_save_draft_area_files(
1957 $this->properties->description['itemid'],
1958 $this->editorcontext->id,
64f93798
PS
1959 'calendar',
1960 'event_description',
76d9df3f
SH
1961 $this->properties->id,
1962 $this->editoroptions,
1963 $this->properties->description['text'],
1964 $this->editoroptions['forcehttps']);
1965 } else {
1966 $this->properties->format = $this->properties->description['format'];
1967 $this->properties->description = $this->properties->description['text'];
1968 }
1969 }
1970
1971 $event = $DB->get_record('event', array('id'=>$this->properties->id));
1972
1973 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
1974
1975 if ($updaterepeated) {
1976 // Update all
1977 if ($this->properties->timestart != $event->timestart) {
1978 $timestartoffset = $this->properties->timestart - $event->timestart;
1979 $sql = "UPDATE {event}
1980 SET name = ?,
1981 description = ?,
1982 timestart = timestart + ?,
1983 timeduration = ?,
1984 timemodified = ?
1985 WHERE repeatid = ?";
1986 $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
1987 } else {
1988 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
1989 $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
1990 }
1991 $DB->execute($sql, $params);
1992
1993 // Log the event update.
1994 add_to_log($this->properties->courseid, 'calendar', 'edit all', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
1995 } else {
1996 $DB->update_record('event', $this->properties);
ddaff608
SH
1997 $event = calendar_event::load($this->properties->id);
1998 $this->properties = $event->properties();
76d9df3f
SH
1999 add_to_log($this->properties->courseid, 'calendar', 'edit', 'event.php?action=edit&amp;id='.$this->properties->id, $this->properties->name);
2000 }
2001
2002 // Hook for tracking event updates
2003 self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
2004 return true;
2005 }
2006 }
2007
2008 /**
2009 * Deletes an event and if selected an repeated events in the same series
2010 *
2011 * This function deletes an event, any associated events if $deleterepeated=true,
2012 * and cleans up any files associated with the events.
2013 *
2014 * @see delete_event()
2015 *
2016 * @param bool $deleterepeated
2017 * @return bool
2018 */
2019 public function delete($deleterepeated=false) {
2020 global $DB, $USER, $CFG;
2021
2022 // If $this->properties->id is not set then something is wrong
2023 if (empty($this->properties->id)) {
2024 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
2025 return false;
2026 }
2027
2028 // Delete the event
2029 $DB->delete_records('event', array('id'=>$this->properties->id));
2030
2031 // If the editor context hasn't already been set then set it now
2032 if ($this->editorcontext === null) {
2033 switch ($this->properties->eventtype) {
2034 case 'course':
2035 case 'group':
2036 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $this->properties->courseid);
2037 break;
2038 case 'user':
2039 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
2040 break;
2041 case 'site':
2042 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
2043 break;
2044 default:
2045 // There is a chance we can get here as some modules use there own
2046 // eventtype strings. In this case the event has been added by code
2047 // and we don't need to worry about it anyway
2048 break;
2049 }
2050 }
2051
2052 // If the context has been set delete all associated files
2053 if ($this->editorcontext !== null) {
2054 $fs = get_file_storage();
64f93798 2055 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
76d9df3f
SH
2056 foreach ($files as $file) {
2057 $file->delete();
2058 }
2059 }
2060
2061 // Fire the event deleted hook
2062 self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));
2063
2064 // If we need to delete repeated events then we will fetch them all and delete one by one
2065 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2066 // Get all records where the repeatid is the same as the event being removed
2067 $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
2068 // For each of the returned events populate a calendar_event object and call delete
2069 // make sure the arg passed is false as we are already deleting all repeats
2070 foreach ($events as $event) {
2071 $event = new calendar_event($event);
2072 $event->delete(false);
2073 }
2074 }
2075
2076 return true;
2077 }
2078
2079 /**
2080 * Fetch all event properties
2081 *
2082 * This function returns all of the events properties as an object and optionally
2083 * can prepare an editor for the description field at the same time. This is
2084 * designed to work when the properties are going to be used to set the default
2085 * values of a moodle forms form.
2086 *
2087 * @param bool $prepareeditor If set to true a editor is prepared for use with
2088 * the mforms editor element. (for description)
2089 * @return stdClass Object containing event properties
2090 */
2091 public function properties($prepareeditor=false) {
2092 global $USER, $CFG, $DB;
2093
2094 // First take a copy of the properties. We don't want to actually change the
2095 // properties or we'd forever be converting back and forwards between an
2096 // editor formatted description and not
2097 $properties = clone($this->properties);
2098 // Clean the description here
2099 $properties->description = clean_text($properties->description, $properties->format);
2100
2101 // If set to true we need to prepare the properties for use with an editor
2102 // and prepare the file area
2103 if ($prepareeditor) {
2104
2105 // We may or may not have a property id. If we do then we need to work
2106 // out the context so we can copy the existing files to the draft area
2107 if (!empty($properties->id)) {
2108
2109 if ($properties->eventtype === 'site') {
2110 // Site context
2111 $this->editorcontext = get_context_instance(CONTEXT_SYSTEM);
2112 } else if ($properties->eventtype === 'user') {
2113 // User context
2114 $this->editorcontext = get_context_instance(CONTEXT_USER, $USER->id);
2115 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
2116 // First check the course is valid
2117 $course = $DB->get_record('course', array('id'=>$properties->courseid));
2118 if (!$course) {
2119 print_error('invalidcourse');
2120 }
2121 // Course context
2122 $this->editorcontext = get_context_instance(CONTEXT_COURSE, $course->id);
2123 // We have a course and are within the course context so we had
2124 // better use the courses max bytes value
2125 $this->editoroptions['maxbytes'] = $course->maxbytes;
2126 } else {
2127 // If we get here we have a custom event type as used by some
2128 // modules. In this case the event will have been added by
2129 // code and we won't need the editor
2130 $this->editoroptions['maxbytes'] = 0;
2131 $this->editoroptions['maxfiles'] = 0;
2132 }
2133
2134 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2135 $contextid = false;
2136 } else {
2137 // Get the context id that is what we really want
2138 $contextid = $this->editorcontext->id;
2139 }
2140 } else {
2141
2142 // If we get here then this is a new event in which case we don't need a
2143 // context as there is no existing files to copy to the draft area.
2144 $contextid = null;
2145 }
2146
2147 // If the contextid === false we don't support files so no preparing
2148 // a draft area
2149 if ($contextid !== false) {
2150 // Just encase it has already been submitted
2151 $draftiddescription = file_get_submitted_draft_itemid('description');
2152 // Prepare the draft area, this copies existing files to the draft area as well
64f93798 2153 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id, $this->editoroptions, $properties->description);
76d9df3f
SH
2154 } else {
2155 $draftiddescription = 0;
2156 }
aa6c1ced 2157
76d9df3f
SH
2158 // Structure the description field as the editor requires
2159 $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2160 }
2161
2162 // Finally return the properties
2163 return $properties;
2164 }
2165
2166 /**
2167 * Toggles the visibility of an event
2168 *
2169 * @param null|bool $force If it is left null the events visibility is flipped,
2170 * If it is false the event is made hidden, if it is true it
2171 * is made visible.
2172 */
2173 public function toggle_visibility($force=null) {
2174 global $CFG, $DB;
2175
2176 // Set visible to the default if it is not already set
2177 if (empty($this->properties->visible)) {
2178 $this->properties->visible = 1;
2179 }
2180
2181 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2182 // Make this event visible
2183 $this->properties->visible = 1;
2184 // Fire the hook
2185 self::calendar_event_hook('show_event', array($this->properties));
2186 } else {
2187 // Make this event hidden
2188 $this->properties->visible = 0;
2189 // Fire the hook
2190 self::calendar_event_hook('hide_event', array($this->properties));
2191 }
2192
2193 // Update the database to reflect this change
2194 return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2195 }
2196
2197 /**
2198 * Attempts to call the hook for the specified action should a calendar type
2199 * by set $CFG->calendar, and the appopriate function defined
2200 *
2201 * @static
2202 * @staticvar bool $extcalendarinc Used to track the inclusion of the calendar lib
2203 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2204 * @param array $args The args to pass to the hook, usually the event is the first element
2205 * @return bool
2206 */
2207 public static function calendar_event_hook($action, array $args) {
2208 global $CFG;
2209 static $extcalendarinc;
2210 if ($extcalendarinc === null) {
2211 if (!empty($CFG->calendar) && file_exists($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
2212 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
2213 $extcalendarinc = true;
2214 } else {
2215 $extcalendarinc = false;
2216 }
2217 }
2218 if($extcalendarinc === false) {
2219 return false;
2220 }
438e4add 2221 $hook = $CFG->calendar .'_'.$action;
76d9df3f
SH
2222 if (function_exists($hook)) {
2223 call_user_func_array($hook, $args);
2224 return true;
2225 }
2226 return false;
2227 }
2228
2229 /**
2230 * Returns a calendar_event object when provided with an event id
2231 *
2232 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2233 * it will result in an exception being thrown
2234 *
fd699564 2235 * @param int|object $param
76d9df3f
SH
2236 * @return calendar_event|false
2237 */
fd699564 2238 public static function load($param) {
76d9df3f 2239 global $DB;
fd699564
SH
2240 if (is_object($param)) {
2241 $event = new calendar_event($param);
2242 } else {
2243 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2244 $event = new calendar_event($event);
2245 }
76d9df3f
SH
2246 return $event;
2247 }
2248
2249 /**
2250 * Creates a new event and returns a calendar_event object
2251 *
2252 * @param object|array $properties An object containing event properties
2253 * @return calendar_event|false The event object or false if it failed
2254 */
2255 public static function create($properties) {
2256 if (is_array($properties)) {
2257 $properties = (object)$properties;
2258 }
2259 if (!is_object($properties)) {
2260 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2261 }
2262 $event = new calendar_event();
2263 if ($event->update($properties)) {
2264 return $event;
2265 } else {
2266 return false;
2267 }
2268 }
2269}
36dc3b71
SH
2270
2271/**
2272 * Calendar information class
2273 *
2274 * This class is used simply to organise the information pertaining to a calendar
2275 * and is used primarily to make information easily available.
2276 */
2277class calendar_information {
2278 /**
2279 * The day
2280 * @var int
2281 */
2282 public $day;
2283 /**
2284 * The month
2285 * @var int
2286 */
2287 public $month;
2288 /**
2289 * The year
2290 * @var int
2291 */
2292 public $year;
2293
2294 /**
2295 * A course id
2296 * @var int
2297 */
2298 public $courseid = null;
2299 /**
2300 * An array of courses
2301 * @var array
2302 */
2303 public $courses = array();
2304 /**
2305 * An array of groups
2306 * @var array
2307 */
2308 public $groups = array();
2309 /**
2310 * An array of users
2311 * @var array
2312 */
2313 public $users = array();
2314
2315 /**
2316 * Creates a new instance
2317 *
2318 * @param int $day
2319 * @param int $month
2320 * @param int $year
2321 */
2322 public function __construct($day, $month, $year) {
2323 $this->day = $day;
2324 $this->month = $month;
2325 $this->year = $year;
2326 }
2327
2328 /**
2329 * Ensures the date for the calendar is correct and either sets it to now
2330 * or throws a moodle_exception if not
2331 *
2332 * @param bool $defaultonow
2333 * @return bool
2334 */
2335 public function checkdate($defaultonow = true) {
2336 if (!checkdate($this->month, $this->day, $this->year)) {
2337 if ($defaultonow) {
2338 $now = usergetdate(time());
2339 $this->day = intval($now['mday']);
2340 $this->month = intval($now['mon']);
2341 $this->year = intval($now['year']);
2342 return true;
2343 } else {
2344 throw new moodle_exception('invaliddate');
2345 }
2346 }
2347 return true;
2348 }
2349 /**
2350 * Gets todays timestamp for the calendar
2351 * @return int
2352 */
2353 public function timestamp_today() {
2354 return make_timestamp($this->year, $this->month, $this->day);
2355 }
2356 /**
2357 * Gets tomorrows timestamp for the calendar
2358 * @return int
2359 */
2360 public function timestamp_tomorrow() {
2361 return make_timestamp($this->year, $this->month, $this->day+1);
2362 }
2363 /**
2364 * Adds the pretend blocks for teh calendar
2365 *
2366 * @param core_calendar_renderer $renderer
2367 * @param bool $showfilters
2368 * @param string|null $view
2369 */
2370 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
2371 if ($showfilters) {
2372 $filters = new block_contents();
2373 $filters->content = $renderer->fake_block_filters($this->courseid, $this->day, $this->month, $this->year, $view, $this->courses);
2374 $filters->footer = '';
2375 $filters->title = get_string('eventskey', 'calendar');
2376 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
2377 }
2378 $block = new block_contents;
2379 $block->content = $renderer->fake_block_threemonths($this);
2380 $block->footer = '';
2381 $block->title = get_string('monthlyview', 'calendar');
2382 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
2383 }
2384}