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