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