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