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