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