NOBUG: Fixed file access permissions
[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
e30390a0
SH
26if (!defined('MOODLE_INTERNAL')) {
27 die('Direct access to this script is forbidden.'); /// It must be included from a Moodle page
28}
b5a52acd 29
08b4a4e1
RW
30/**
31 * These are read by the administration component to provide default values
32 */
33
34/**
35 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
36 */
bb4a2e85 37define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
08b4a4e1
RW
38
39/**
40 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
41 */
bb4a2e85 42define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
08b4a4e1
RW
43
44/**
45 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
46 */
47define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
48
bb4a2e85 49// This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
50// Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
08b4a4e1
RW
51
52/**
53 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
54 */
55define('CALENDAR_DEFAULT_WEEKEND', 65);
56
57/**
58 * CALENDAR_URL - path to calendar's folder
59 */
76d9df3f 60define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
08b4a4e1
RW
61
62/**
63 * CALENDAR_TF_24 - Calendar time in 24 hours format
64 */
76d9df3f 65define('CALENDAR_TF_24', '%H:%M');
08b4a4e1
RW
66
67/**
68 * CALENDAR_TF_12 - Calendar time in 12 hours format
69 */
76d9df3f 70define('CALENDAR_TF_12', '%I:%M %p');
bb4a2e85 71
08b4a4e1
RW
72/**
73 * CALENDAR_EVENT_GLOBAL - Global calendar event types
74 */
797cedc7 75define('CALENDAR_EVENT_GLOBAL', 1);
08b4a4e1
RW
76
77/**
78 * CALENDAR_EVENT_COURSE - Course calendar event types
79 */
797cedc7 80define('CALENDAR_EVENT_COURSE', 2);
08b4a4e1
RW
81
82/**
83 * CALENDAR_EVENT_GROUP - group calendar event types
84 */
797cedc7 85define('CALENDAR_EVENT_GROUP', 4);
08b4a4e1
RW
86
87/**
88 * CALENDAR_EVENT_USER - user calendar event types
89 */
797cedc7
SH
90define('CALENDAR_EVENT_USER', 8);
91
7423f116 92
b5a52acd
JH
93/**
94 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
95 */
96define('CALENDAR_IMPORT_FROM_FILE', 0);
97
98/**
99 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
100 */
101define('CALENDAR_IMPORT_FROM_URL', 1);
102
103/**
104 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
105 */
106define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
107
108/**
109 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
110 */
111define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
112
ee74a2a1
AA
113/**
114 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
115 */
116define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
117
118/**
119 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
120 */
121define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
122
797cedc7
SH
123/**
124 * Return the days of the week
125 *
08b4a4e1 126 * @return array array of days
797cedc7
SH
127 */
128function calendar_get_days() {
da304137
MN
129 $calendartype = \core_calendar\type_factory::get_calendar_instance();
130 return $calendartype->get_weekdays();
797cedc7 131}
f2bffd9e 132
e73b527c
AA
133/**
134 * Get the subscription from a given id
135 *
136 * @since Moodle 2.5
137 * @param int $id id of the subscription
138 * @return stdClass Subscription record from DB
139 * @throws moodle_exception for an invalid id
140 */
141function calendar_get_subscription($id) {
142 global $DB;
143
144 $cache = cache::make('core', 'calendar_subscriptions');
145 $subscription = $cache->get($id);
146 if (empty($subscription)) {
147 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
148 // cache the data.
149 $cache->set($id, $subscription);
150 }
151 return $subscription;
152}
153
76d9df3f
SH
154/**
155 * Gets the first day of the week
156 *
157 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
158 *
159 * @return int
160 */
161function calendar_get_starting_weekday() {
da304137
MN
162 $calendartype = \core_calendar\type_factory::get_calendar_instance();
163 return $calendartype->get_starting_weekday();
76d9df3f 164}
bd119567 165
0f927f1e 166/**
14236cbd 167 * Generates the HTML for a miniature calendar
0f927f1e 168 *
512edd65 169 * @param array $courses list of course to list events from
08b4a4e1
RW
170 * @param array $groups list of group
171 * @param array $users user's info
da304137
MN
172 * @param int|bool $calmonth calendar month in numeric, default is set to false
173 * @param int|bool $calyear calendar month in numeric, default is set to false
174 * @param string|bool $placement the place/page the calendar is set to appear - passed on the the controls function
175 * @param int|bool $courseid id of the course the calendar is displayed on - passed on the the controls function
176 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
177 * and $calyear to support multiple calendars
08b4a4e1 178 * @return string $content return html table for mini calendar
0f927f1e 179 */
da304137
MN
180function calendar_get_mini($courses, $groups, $users, $calmonth = false, $calyear = false, $placement = false,
181 $courseid = false, $time = 0) {
182 global $CFG, $OUTPUT;
183
184 // Get the calendar type we are using.
185 $calendartype = \core_calendar\type_factory::get_calendar_instance();
7423f116 186
dd97c328 187 $display = new stdClass;
da304137
MN
188
189 // Assume we are not displaying this month for now.
190 $display->thismonth = false;
7423f116 191
192 $content = '';
193
da304137
MN
194 // Do this check for backwards compatibility. The core should be passing a timestamp rather than month and year.
195 // If a month and year are passed they will be in Gregorian.
196 if (!empty($calmonth) && !empty($calyear)) {
197 // Ensure it is a valid date, else we will just set it to the current timestamp.
198 if (checkdate($calmonth, 1, $calyear)) {
199 $time = make_timestamp($calyear, $calmonth, 1);
36dc3b71 200 } else {
da304137
MN
201 $time = time();
202 }
203 $date = usergetdate($time);
204 if ($calmonth == $date['mon'] && $calyear == $date['year']) {
205 $display->thismonth = true;
206 }
207 // We can overwrite date now with the date used by the calendar type, if it is not Gregorian, otherwise
208 // there is no need as it is already in Gregorian.
209 if ($calendartype->get_name() != 'gregorian') {
210 $date = $calendartype->timestamp_to_date_array($time);
211 }
212 } else if (!empty($time)) {
213 // Get the specified date in the calendar type being used.
214 $date = $calendartype->timestamp_to_date_array($time);
215 $thisdate = $calendartype->timestamp_to_date_array(time());
216 if ($date['month'] == $thisdate['month'] && $date['year'] == $thisdate['year']) {
217 $display->thismonth = true;
218 // If we are the current month we want to set the date to the current date, not the start of the month.
219 $date = $thisdate;
7423f116 220 }
36dc3b71 221 } else {
da304137
MN
222 // Get the current date in the calendar type being used.
223 $time = time();
224 $date = $calendartype->timestamp_to_date_array($time);
7423f116 225 $display->thismonth = true;
226 }
227
da304137 228 list($d, $m, $y) = array($date['mday'], $date['mon'], $date['year']); // This is what we want to display.
7423f116 229
1032966c 230 // Get Gregorian date for the start of the month.
da304137
MN
231 $gregoriandate = $calendartype->convert_to_gregorian($date['year'], $date['mon'], 1);
232
1032966c 233 // Store the gregorian date values to be used later.
da304137
MN
234 list($gy, $gm, $gd, $gh, $gmin) = array($gregoriandate['year'], $gregoriandate['month'], $gregoriandate['day'],
235 $gregoriandate['hour'], $gregoriandate['minute']);
7423f116 236
da304137
MN
237 // Get the max number of days in this month for this calendar type.
238 $display->maxdays = calendar_days_in_month($m, $y);
239 // Get the starting week day for this month.
69244b91 240 $startwday = dayofweek(1, $m, $y);
da304137
MN
241 // Get the days in a week.
242 $daynames = calendar_get_days();
243 // Store the number of days in a week.
244 $numberofdaysinweek = $calendartype->get_num_weekdays();
245
246 // Set the min and max weekday.
247 $display->minwday = calendar_get_starting_weekday();
248 $display->maxwday = $display->minwday + ($numberofdaysinweek - 1);
249
250 // These are used for DB queries, so we want unixtime, so we need to use Gregorian dates.
251 $display->tstart = make_timestamp($gy, $gm, $gd, $gh, $gmin, 0);
1032966c 252 $display->tend = $display->tstart + ($display->maxdays * DAYSECS) - 1;
7423f116 253
254 // Align the starting weekday to fall in our display range
255 // This is simple, not foolproof.
da304137
MN
256 if ($startwday < $display->minwday) {
257 $startwday += $numberofdaysinweek;
7423f116 258 }
259
260 // Get the events matching our criteria. Don't forget to offset the timestamps for the user's TZ!
da304137 261 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
7423f116 262
b4892fa2 263 // Set event course class for course events
264 if (!empty($events)) {
13534ef7 265 foreach ($events as $eventid => $event) {
13534ef7
ML
266 if (!empty($event->modulename)) {
267 $cm = get_coursemodule_from_instance($event->modulename, $event->instance);
8270f0d0 268 if (!\core_availability\info_module::is_user_visible($cm, 0, false)) {
13534ef7
ML
269 unset($events[$eventid]);
270 }
271 }
b4892fa2 272 }
273 }
6619eba4 274
c635dcda 275 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
9064751b 276 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
c635dcda 277 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
278 // arguments to this function.
0f927f1e 279 $hrefparams = array();
7bd1677c 280 if(!empty($courses)) {
e749554e 281 $courses = array_diff($courses, array(SITEID));
7bd1677c 282 if(count($courses) == 1) {
0f927f1e 283 $hrefparams['course'] = reset($courses);
7bd1677c 284 }
c635dcda 285 }
286
7423f116 287 // We want to have easy access by day, since the display is on a per-day basis.
7c50db30 288 calendar_events_by_day($events, $m, $y, $eventsbyday, $durationbyday, $typesbyday, $courses);
7423f116 289
da304137
MN
290 // Accessibility: added summary and <abbr> elements.
291 $summary = get_string('calendarheading', 'calendar', userdate($display->tstart, get_string('strftimemonthyear')));
292 $content .= '<table class="minicalendar calendartable" summary="'.$summary.'">'; // Begin table.
293 if (($placement !== false) && ($courseid !== false)) {
294 $content .= '<caption>'. calendar_top_controls($placement, array('id' => $courseid, 'time' => $time)) .'</caption>';
512edd65 295 }
f136e4c5 296 $content .= '<tr class="weekdays">'; // Header row: day names
7423f116 297
da304137
MN
298 // Print out the names of the weekdays.
299 for ($i = $display->minwday; $i <= $display->maxwday; ++$i) {
300 $pos = $i % $numberofdaysinweek;
301 $content .= '<th scope="col"><abbr title="'. $daynames[$pos]['fullname'] .'">'.
302 $daynames[$pos]['shortname'] ."</abbr></th>\n";
7423f116 303 }
304
f136e4c5 305 $content .= '</tr><tr>'; // End of day names; prepare for day numbers
7423f116 306
307 // For the table display. $week is the row; $dayweek is the column.
7423f116 308 $dayweek = $startwday;
309
310 // Paddding (the first week may have blank days in the beginning)
311 for($i = $display->minwday; $i < $startwday; ++$i) {
3bfd8bc8 312 $content .= '<td class="dayblank">&nbsp;</td>'."\n";
7423f116 313 }
314
797cedc7
SH
315 $weekend = CALENDAR_DEFAULT_WEEKEND;
316 if (isset($CFG->calendar_weekend)) {
317 $weekend = intval($CFG->calendar_weekend);
318 }
319
7423f116 320 // Now display all the calendar
da304137 321 $daytime = $display->tstart - DAYSECS;
7423f116 322 for($day = 1; $day <= $display->maxdays; ++$day, ++$dayweek) {
da304137 323 $daytime += DAYSECS;
7423f116 324 if($dayweek > $display->maxwday) {
325 // We need to change week (table row)
d56d4e23 326 $content .= '</tr><tr>';
7423f116 327 $dayweek = $display->minwday;
7423f116 328 }
92668ad2 329
da304137
MN
330 // Reset vars.
331 if ($weekend & (1 << ($dayweek % $numberofdaysinweek))) {
7423f116 332 // Weekend. This is true no matter what the exact range is.
e2aa618b 333 $class = 'weekend day';
90723839 334 } else {
7423f116 335 // Normal working day.
e2aa618b 336 $class = 'day';
7423f116 337 }
338
339 // Special visual fx if an event is defined
340 if(isset($eventsbyday[$day])) {
da304137 341
90723839 342 $class .= ' hasevent';
0f927f1e 343 $hrefparams['view'] = 'day';
da304137 344 $dayhref = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $hrefparams), 0, 0, 0, $daytime);
f434283f 345
7423f116 346 $popupcontent = '';
347 foreach($eventsbyday[$day] as $eventid) {
41d30a8e 348 if (!isset($events[$eventid])) {
349 continue;
4e17c6f3 350 }
07c03ff9 351 $event = new calendar_event($events[$eventid]);
0f927f1e
SH
352 $popupalt = '';
353 $component = 'moodle';
da304137 354 if (!empty($event->modulename)) {
0f927f1e 355 $popupicon = 'icon';
41d30a8e 356 $popupalt = $event->modulename;
0f927f1e 357 $component = $event->modulename;
da304137 358 } else if ($event->courseid == SITEID) { // Site event.
5326675e 359 $popupicon = 'i/siteevent';
da304137 360 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
5326675e 361 $popupicon = 'i/courseevent';
da304137 362 } else if ($event->groupid) { // Group event.
5326675e 363 $popupicon = 'i/groupevent';
da304137 364 } else { // Must be a user event.
5326675e 365 $popupicon = 'i/userevent';
4e17c6f3 366 }
1d5bd3d2 367
0f927f1e 368 $dayhref->set_anchor('event_'.$event->id);
1d5bd3d2 369
0f927f1e 370 $popupcontent .= html_writer::start_tag('div');
adc3cfc7 371 $popupcontent .= $OUTPUT->pix_icon($popupicon, $popupalt, $component);
07c03ff9 372 $name = format_string($event->name, true);
e73b527c
AA
373 // Show ical source if needed.
374 if (!empty($event->subscription) && $CFG->calendar_showicalsource) {
07c03ff9
AA
375 $a = new stdClass();
376 $a->name = $name;
377 $a->source = $event->subscription->name;
378 $name = get_string('namewithsource', 'calendar', $a);
379 }
380 $popupcontent .= html_writer::link($dayhref, $name);
0f927f1e 381 $popupcontent .= html_writer::end_tag('div');
7423f116 382 }
e295df44 383
b5c42e70 384 //Accessibility: functionality moved to calendar_get_popup.
385 if($display->thismonth && $day == $d) {
7df3ea15 386 $popupid = calendar_get_popup(true, $events[$eventid]->timestart, $popupcontent);
b5c42e70 387 } else {
7df3ea15 388 $popupid = calendar_get_popup(false, $events[$eventid]->timestart, $popupcontent);
e295df44 389 }
f20c4d02 390
7423f116 391 // Class and cell content
392 if(isset($typesbyday[$day]['startglobal'])) {
90723839
SH
393 $class .= ' calendar_event_global';
394 } else if(isset($typesbyday[$day]['startcourse'])) {
395 $class .= ' calendar_event_course';
396 } else if(isset($typesbyday[$day]['startgroup'])) {
397 $class .= ' calendar_event_group';
398 } else if(isset($typesbyday[$day]['startuser'])) {
399 $class .= ' calendar_event_user';
7423f116 400 }
9c7f855b 401 $cell = html_writer::link($dayhref, $day, array('id' => $popupid));
90723839 402 } else {
05fcc5fd 403 $cell = $day;
7423f116 404 }
405
90723839
SH
406 $durationclass = false;
407 if (isset($typesbyday[$day]['durationglobal'])) {
408 $durationclass = ' duration_global';
409 } else if(isset($typesbyday[$day]['durationcourse'])) {
410 $durationclass = ' duration_course';
411 } else if(isset($typesbyday[$day]['durationgroup'])) {
412 $durationclass = ' duration_group';
413 } else if(isset($typesbyday[$day]['durationuser'])) {
414 $durationclass = ' duration_user';
7423f116 415 }
90723839
SH
416 if ($durationclass) {
417 $class .= ' duration '.$durationclass;
7423f116 418 }
419
b4892fa2 420 // If event has a class set then add it to the table day <td> tag
421 // Note: only one colour for minicalendar
422 if(isset($eventsbyday[$day])) {
423 foreach($eventsbyday[$day] as $eventid) {
424 if (!isset($events[$eventid])) {
425 continue;
426 }
427 $event = $events[$eventid];
428 if (!empty($event->class)) {
429 $class .= ' '.$event->class;
430 }
431 break;
432 }
433 }
434
7423f116 435 // Special visual fx for today
450a0a7d 436 //Accessibility: hidden text for today, and popup.
7423f116 437 if($display->thismonth && $day == $d) {
edbe6c1b 438 $class .= ' today';
b5c42e70 439 $today = get_string('today', 'calendar').' '.userdate(time(), get_string('strftimedayshort'));
e295df44 440
b5c42e70 441 if(! isset($eventsbyday[$day])) {
450a0a7d 442 $class .= ' eventnone';
7df3ea15 443 $popupid = calendar_get_popup(true, false);
9c7f855b 444 $cell = html_writer::link('#', $day, array('id' => $popupid));
b5c42e70 445 }
f79f2494 446 $cell = get_accesshide($today.' ').$cell;
7423f116 447 }
448
449 // Just display it
92668ad2 450 if(!empty($class)) {
d56d4e23 451 $class = ' class="'.$class.'"';
92668ad2 452 }
453 $content .= '<td'.$class.'>'.$cell."</td>\n";
7423f116 454 }
455
456 // Paddding (the last week may have blank days at the end)
457 for($i = $dayweek; $i <= $display->maxwday; ++$i) {
3bfd8bc8 458 $content .= '<td class="dayblank">&nbsp;</td>';
7423f116 459 }
460 $content .= '</tr>'; // Last row ends
461
f136e4c5 462 $content .= '</table>'; // Tabular display of days ends
7423f116 463
464 return $content;
465}
466
b5c42e70 467/**
08b4a4e1
RW
468 * Gets the calendar popup
469 *
470 * It called at multiple points in from calendar_get_mini.
471 * Copied and modified from calendar_get_mini.
472 *
473 * @param bool $is_today false except when called on the current day.
474 * @param mixed $event_timestart $events[$eventid]->timestart, OR false if there are no events.
7df3ea15
AA
475 * @param string $popupcontent content for the popup window/layout.
476 * @return string eventid for the calendar_tooltip popup window/layout.
b5c42e70 477 */
478function calendar_get_popup($is_today, $event_timestart, $popupcontent='') {
458eb0d1 479 global $PAGE;
480 static $popupcount;
481 if ($popupcount === null) {
482 $popupcount = 1;
483 }
b5c42e70 484 $popupcaption = '';
485 if($is_today) {
486 $popupcaption = get_string('today', 'calendar').' ';
487 }
488 if (false === $event_timestart) {
489 $popupcaption .= userdate(time(), get_string('strftimedayshort'));
490 $popupcontent = get_string('eventnone', 'calendar');
450a0a7d 491
b5c42e70 492 } else {
493 $popupcaption .= get_string('eventsfor', 'calendar', userdate($event_timestart, get_string('strftimedayshort')));
494 }
458eb0d1 495 $id = 'calendar_tooltip_'.$popupcount;
33e48a1a 496 $PAGE->requires->yui_module('moodle-calendar-eventmanager', 'M.core_calendar.add_event', array(array('eventId'=>$id,'title'=>$popupcaption, 'content'=>$popupcontent)));
bdbae764 497
458eb0d1 498 $popupcount++;
7df3ea15 499 return $id;
b5c42e70 500}
501
08b4a4e1
RW
502/**
503 * Gets the calendar upcoming event
504 *
505 * @param array $courses array of courses
506 * @param array|int|bool $groups array of groups, group id or boolean for all/no group events
507 * @param array|int|bool $users array of users, user id or boolean for all/no user events
508 * @param int $daysinfuture number of days in the future we 'll look
509 * @param int $maxevents maximum number of events
510 * @param int $fromtime start time
511 * @return array $output array of upcoming events
512 */
9958a08c 513function calendar_get_upcoming($courses, $groups, $users, $daysinfuture, $maxevents, $fromtime=0) {
62d11d77 514 global $CFG, $COURSE, $DB;
7423f116 515
dd97c328 516 $display = new stdClass;
7423f116 517 $display->range = $daysinfuture; // How many days in the future we 'll look
518 $display->maxevents = $maxevents;
519
520 $output = array();
521
522 // Prepare "course caching", since it may save us a lot of queries
523 $coursecache = array();
524
525 $processed = 0;
526 $now = time(); // We 'll need this later
9d567178 527 $usermidnighttoday = usergetmidnight($now);
7423f116 528
9958a08c 529 if ($fromtime) {
530 $display->tstart = $fromtime;
531 } else {
9d567178 532 $display->tstart = $usermidnighttoday;
9958a08c 533 }
7423f116 534
1f473774 535 // This works correctly with respect to the user's DST, but it is accurate
536 // only because $fromtime is always the exact midnight of some day!
537 $display->tend = usergetmidnight($display->tstart + DAYSECS * $display->range + 3 * HOURSECS) - 1;
7423f116 538
539 // Get the events matching our criteria
8263f802 540 $events = calendar_get_events($display->tstart, $display->tend, $users, $groups, $courses);
7423f116 541
c635dcda 542 // This is either a genius idea or an idiot idea: in order to not complicate things, we use this rule: if, after
9064751b 543 // possibly removing SITEID from $courses, there is only one course left, then clicking on a day in the month
c635dcda 544 // will also set the $SESSION->cal_courses_shown variable to that one course. Otherwise, we 'd need to add extra
545 // arguments to this function.
546
0f927f1e 547 $hrefparams = array();
7bd1677c 548 if(!empty($courses)) {
e749554e 549 $courses = array_diff($courses, array(SITEID));
7bd1677c 550 if(count($courses) == 1) {
0f927f1e 551 $hrefparams['course'] = reset($courses);
7bd1677c 552 }
c635dcda 553 }
554
dd97c328 555 if ($events !== false) {
556
f20edd52 557 $modinfo = get_fast_modinfo($COURSE);
fa22fd5f 558
7423f116 559 foreach($events as $event) {
dc6cb74e 560
dd97c328 561
562 if (!empty($event->modulename)) {
563 if ($event->courseid == $COURSE->id) {
564 if (isset($modinfo->instances[$event->modulename][$event->instance])) {
565 $cm = $modinfo->instances[$event->modulename][$event->instance];
566 if (!$cm->uservisible) {
567 continue;
568 }
569 }
570 } else {
571 if (!$cm = get_coursemodule_from_instance($event->modulename, $event->instance)) {
dc6cb74e 572 continue;
573 }
8270f0d0 574 if (!\core_availability\info_module::is_user_visible($cm, 0, false)) {
dc6cb74e 575 continue;
576 }
dd97c328 577 }
dc6cb74e 578 }
9d567178 579
dd97c328 580 if ($processed >= $display->maxevents) {
9d567178 581 break;
582 }
7423f116 583
0f927f1e 584 $event->time = calendar_format_event_time($event, $now, $hrefparams);
3c134875 585 $output[] = $event;
586 ++$processed;
587 }
588 }
589 return $output;
590}
7423f116 591
f6a5ffe8
HB
592
593/**
f37c923d 594 * Get a HTML link to a course.
f6a5ffe8
HB
595 *
596 * @param int $courseid the course id
597 * @return string a link to the course (as HTML); empty if the course id is invalid
598 */
599function calendar_get_courselink($courseid) {
600
601 if (!$courseid) {
602 return '';
603 }
604
f37c923d 605 calendar_get_course_cached($coursecache, $courseid);
f6a5ffe8
HB
606 $context = context_course::instance($courseid);
607 $fullname = format_string($coursecache[$courseid]->fullname, true, array('context' => $context));
608 $url = new moodle_url('/course/view.php', array('id' => $courseid));
609 $link = html_writer::link($url, $fullname);
610
611 return $link;
612}
613
614
08b4a4e1
RW
615/**
616 * Add calendar event metadata
617 *
618 * @param stdClass $event event info
619 * @return stdClass $event metadata
620 */
9df8ff44 621function calendar_add_event_metadata($event) {
6b608f8f 622 global $CFG, $OUTPUT;
fb73f3b3 623
e295df44 624 //Support multilang in event->name
fb73f3b3 625 $event->name = format_string($event->name,true);
e295df44 626
3c134875 627 if(!empty($event->modulename)) { // Activity event
628 // The module name is set. I will assume that it has to be displayed, and
629 // also that it is an automatically-generated event. And of course that the
630 // fields for get_coursemodule_from_instance are set correctly.
631 $module = calendar_get_module_cached($coursecache, $event->modulename, $event->instance);
7423f116 632
3c134875 633 if ($module === false) {
634 return;
635 }
9958a08c 636
3c134875 637 $modulename = get_string('modulename', $event->modulename);
a48bf079
DM
638 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
639 // will be used as alt text if the event icon
640 $eventtype = get_string($event->eventtype, $event->modulename);
641 } else {
642 $eventtype = '';
643 }
b5d0cafc 644 $icon = $OUTPUT->pix_url('icon', $event->modulename) . '';
9958a08c 645
857c5f90 646 $event->icon = '<img src="'.$icon.'" alt="'.$eventtype.'" title="'.$modulename.'" class="icon" />';
fb73f3b3 647 $event->referer = '<a href="'.$CFG->wwwroot.'/mod/'.$event->modulename.'/view.php?id='.$module->id.'">'.$event->name.'</a>';
f6a5ffe8 648 $event->courselink = calendar_get_courselink($module->course);
3c134875 649 $event->cmid = $module->id;
9958a08c 650
3c134875 651 } else if($event->courseid == SITEID) { // Site event
857c5f90 652 $event->icon = '<img src="'.$OUTPUT->pix_url('i/siteevent') . '" alt="'.get_string('globalevent', 'calendar').'" class="icon" />';
90723839 653 $event->cssclass = 'calendar_event_global';
3c134875 654 } else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event
857c5f90 655 $event->icon = '<img src="'.$OUTPUT->pix_url('i/courseevent') . '" alt="'.get_string('courseevent', 'calendar').'" class="icon" />';
f6a5ffe8 656 $event->courselink = calendar_get_courselink($event->courseid);
90723839 657 $event->cssclass = 'calendar_event_course';
3c134875 658 } else if ($event->groupid) { // Group event
857c5f90 659 $event->icon = '<img src="'.$OUTPUT->pix_url('i/groupevent') . '" alt="'.get_string('groupevent', 'calendar').'" class="icon" />';
f6a5ffe8 660 $event->courselink = calendar_get_courselink($event->courseid);
90723839 661 $event->cssclass = 'calendar_event_group';
3c134875 662 } else if($event->userid) { // User event
857c5f90 663 $event->icon = '<img src="'.$OUTPUT->pix_url('i/userevent') . '" alt="'.get_string('userevent', 'calendar').'" class="icon" />';
90723839 664 $event->cssclass = 'calendar_event_user';
3c134875 665 }
9df8ff44 666 return $event;
e295df44 667}
9df8ff44 668
8263f802 669/**
670 * Get calendar events
08b4a4e1 671 *
8263f802 672 * @param int $tstart Start time of time range for events
08b4a4e1
RW
673 * @param int $tend End time of time range for events
674 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
675 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
676 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
8263f802 677 * @param boolean $withduration whether only events starting within time range selected
678 * or events in progress/already started selected as well
679 * @param boolean $ignorehidden whether to select only visible events or all events
08b4a4e1 680 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
8263f802 681 */
682function calendar_get_events($tstart, $tend, $users, $groups, $courses, $withduration=true, $ignorehidden=true) {
62d11d77 683 global $DB;
684
7423f116 685 $whereclause = '';
686 // Quick test
687 if(is_bool($users) && is_bool($groups) && is_bool($courses)) {
8263f802 688 return array();
7423f116 689 }
482dbe0c 690
7423f116 691 if(is_array($users) && !empty($users)) {
692 // Events from a number of users
693 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 694 $whereclause .= ' (userid IN ('.implode(',', $users).') AND courseid = 0 AND groupid = 0)';
36dc3b71 695 } else if(is_numeric($users)) {
7423f116 696 // Events from one user
697 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 698 $whereclause .= ' (userid = '.$users.' AND courseid = 0 AND groupid = 0)';
36dc3b71 699 } else if($users === true) {
7423f116 700 // Events from ALL users
701 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 702 $whereclause .= ' (userid != 0 AND courseid = 0 AND groupid = 0)';
36dc3b71 703 } else if($users === false) {
6e957c41 704 // No user at all, do nothing
f52f7413 705 }
482dbe0c 706
7423f116 707 if(is_array($groups) && !empty($groups)) {
708 // Events from a number of groups
709 if(!empty($whereclause)) $whereclause .= ' OR';
710 $whereclause .= ' groupid IN ('.implode(',', $groups).')';
36dc3b71 711 } else if(is_numeric($groups)) {
7423f116 712 // Events from one group
713 if(!empty($whereclause)) $whereclause .= ' OR ';
714 $whereclause .= ' groupid = '.$groups;
36dc3b71 715 } else if($groups === true) {
7423f116 716 // Events from ALL groups
717 if(!empty($whereclause)) $whereclause .= ' OR ';
718 $whereclause .= ' groupid != 0';
719 }
482dbe0c 720 // boolean false (no groups at all): we don't need to do anything
721
36dc3b71
SH
722 if(is_array($courses) && !empty($courses)) {
723 if(!empty($whereclause)) {
724 $whereclause .= ' OR';
f52f7413 725 }
36dc3b71
SH
726 $whereclause .= ' (groupid = 0 AND courseid IN ('.implode(',', $courses).'))';
727 } else if(is_numeric($courses)) {
7423f116 728 // One course
729 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 730 $whereclause .= ' (groupid = 0 AND courseid = '.$courses.')';
36dc3b71 731 } else if ($courses === true) {
7423f116 732 // Events from ALL courses
733 if(!empty($whereclause)) $whereclause .= ' OR';
6e957c41 734 $whereclause .= ' (groupid = 0 AND courseid != 0)';
7423f116 735 }
8c165fe9 736
482dbe0c 737 // Security check: if, by now, we have NOTHING in $whereclause, then it means
738 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
739 // events no matter what. Allowing the code to proceed might return a completely
740 // valid query with only time constraints, thus selecting ALL events in that time frame!
741 if(empty($whereclause)) {
8263f802 742 return array();
482dbe0c 743 }
744
7423f116 745 if($withduration) {
b4892fa2 746 $timeclause = '(timestart >= '.$tstart.' OR timestart + timeduration > '.$tstart.') AND timestart <= '.$tend;
7423f116 747 }
748 else {
749 $timeclause = 'timestart >= '.$tstart.' AND timestart <= '.$tend;
750 }
751 if(!empty($whereclause)) {
752 // We have additional constraints
753 $whereclause = $timeclause.' AND ('.$whereclause.')';
754 }
755 else {
756 // Just basic time filtering
757 $whereclause = $timeclause;
758 }
f52f7413 759
0ad072de 760 if ($ignorehidden) {
761 $whereclause .= ' AND visible = 1';
762 }
763
62d11d77 764 $events = $DB->get_records_select('event', $whereclause, null, 'timestart');
8263f802 765 if ($events === false) {
766 $events = array();
767 }
768 return $events;
7423f116 769}
770
475896bd
AA
771/** Get calendar events by id
772 *
773 * @since Moodle 2.5
774 * @param array $eventids list of event ids
775 * @return array Array of event entries, empty array if nothing found
776 */
777
778function calendar_get_events_by_id($eventids) {
779 global $DB;
780
781 if (!is_array($eventids) || empty($eventids)) {
782 return array();
783 }
784 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
785 $wheresql = "id $wheresql";
786
787 return $DB->get_records_select('event', $wheresql, $params);
788}
789
08b4a4e1
RW
790/**
791 * Get control options for Calendar
792 *
793 * @param string $type of calendar
794 * @param array $data calendar information
795 * @return string $content return available control for the calender in html
796 */
7423f116 797function calendar_top_controls($type, $data) {
1d3972ad 798 global $PAGE, $OUTPUT;
da304137
MN
799
800 // Get the calendar type we are using.
801 $calendartype = \core_calendar\type_factory::get_calendar_instance();
802
7423f116 803 $content = '';
5147ad48 804
da304137 805 // Ensure course id passed if relevant.
f21ed0f3 806 $courseid = '';
807 if (!empty($data['id'])) {
808 $courseid = '&amp;course='.$data['id'];
809 }
810
da304137
MN
811 // If we are passing a month and year then we need to convert this to a timestamp to
812 // support multiple calendars. No where in core should these be passed, this logic
813 // here is for third party plugins that may use this function.
814 if (!empty($data['m']) && !empty($date['y'])) {
815 if (!isset($data['d'])) {
816 $data['d'] = 1;
817 }
818 if (!checkdate($data['m'], $data['d'], $data['y'])) {
819 $time = time();
820 } else {
821 $time = make_timestamp($data['y'], $data['m'], $data['d']);
822 }
823 } else if (!empty($data['time'])) {
824 $time = $data['time'];
825 } else {
5147ad48 826 $time = time();
827 }
e295df44 828
da304137
MN
829 // Get the date for the calendar type.
830 $date = $calendartype->timestamp_to_date_array($time);
831
769c73ae 832 $urlbase = $PAGE->url;
7423f116 833
da304137
MN
834 // We need to get the previous and next months in certain cases.
835 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
836 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1032966c
MN
837 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
838 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
839 $prevmonthtime['hour'], $prevmonthtime['minute']);
da304137
MN
840
841 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1032966c
MN
842 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
843 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
844 $nextmonthtime['hour'], $nextmonthtime['minute']);
da304137 845 }
2a06efcc 846
da304137 847 switch ($type) {
7423f116 848 case 'frontpage':
da304137
MN
849 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false, true, $prevmonthtime);
850 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true, $nextmonthtime);
851 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'month')), false, false, false, $time);
ae53bd1d 852
0f927f1e
SH
853 if (!empty($data['id'])) {
854 $calendarlink->param('course', $data['id']);
855 }
856
43c90b9b 857 if (right_to_left()) {
0f927f1e
SH
858 $left = $nextlink;
859 $right = $prevlink;
43c90b9b 860 } else {
0f927f1e
SH
861 $left = $prevlink;
862 $right = $nextlink;
43c90b9b 863 }
ae53bd1d 864
0f927f1e
SH
865 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
866 $content .= $left.'<span class="hide"> | </span>';
e71e340d 867 $content .= html_writer::tag('span', html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')), array('title'=>get_string('monththis','calendar'))), array('class'=>'current'));
0f927f1e 868 $content .= '<span class="hide"> | </span>'. $right;
6694ff84 869 $content .= "<span class=\"clearer\"><!-- --></span>\n";
0f927f1e
SH
870 $content .= html_writer::end_tag('div');
871
872 break;
7423f116 873 case 'course':
da304137
MN
874 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false, true, $prevmonthtime);
875 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true, $nextmonthtime);
876 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'month')), false, false, false, $time);
0f927f1e 877
0f927f1e
SH
878 if (!empty($data['id'])) {
879 $calendarlink->param('course', $data['id']);
880 }
881
882 if (right_to_left()) {
883 $left = $nextlink;
884 $right = $prevlink;
885 } else {
886 $left = $prevlink;
887 $right = $nextlink;
888 }
889
890 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
891 $content .= $left.'<span class="hide"> | </span>';
e71e340d 892 $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
893 $content .= '<span class="hide"> | </span>'. $right;
894 $content .= "<span class=\"clearer\"><!-- --></span>";
895 $content .= html_writer::end_tag('div');
896 break;
7423f116 897 case 'upcoming':
da304137 898 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'upcoming')), false, false, false, $time);
0f927f1e
SH
899 if (!empty($data['id'])) {
900 $calendarlink->param('course', $data['id']);
901 }
902 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
903 $content .= html_writer::tag('div', $calendarlink, array('class'=>'centered'));
904 break;
7423f116 905 case 'display':
da304137 906 $calendarlink = calendar_get_link_href(new moodle_url(CALENDAR_URL.'view.php', array('view' => 'month')), false, false, false, $time);
0f927f1e
SH
907 if (!empty($data['id'])) {
908 $calendarlink->param('course', $data['id']);
909 }
910 $calendarlink = html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
911 $content .= html_writer::tag('h3', $calendarlink);
912 break;
7423f116 913 case 'month':
da304137
MN
914 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', false, false, false, false, $prevmonthtime);
915 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')), 'view.php?view=month'.$courseid.'&amp;', false, false, false, false, $nextmonthtime);
0f927f1e
SH
916
917 if (right_to_left()) {
918 $left = $nextlink;
919 $right = $prevlink;
920 } else {
921 $left = $prevlink;
922 $right = $nextlink;
923 }
924
925 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
1d3972ad
BB
926 $content .= $left . '<span class="hide"> | </span>';
927 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
0f927f1e
SH
928 $content .= '<span class="hide"> | </span>' . $right;
929 $content .= '<span class="clearer"><!-- --></span>';
930 $content .= html_writer::end_tag('div')."\n";
931 break;
7423f116 932 case 'day':
797cedc7 933 $days = calendar_get_days();
da304137
MN
934
935 $prevtimestamp = $time - DAYSECS;
936 $nexttimestamp = $time + DAYSECS;
937
938 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
939 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
940
941 $prevname = $days[$prevdate['wday']]['fullname'];
942 $nextname = $days[$nextdate['wday']]['fullname'];
943 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day'.$courseid.'&amp;', false, false, false, false, $prevtimestamp);
944 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day'.$courseid.'&amp;', false, false, false, false, $nexttimestamp);
0f927f1e
SH
945
946 if (right_to_left()) {
947 $left = $nextlink;
948 $right = $prevlink;
949 } else {
950 $left = $prevlink;
951 $right = $nextlink;
952 }
953
954 $content .= html_writer::start_tag('div', array('class'=>'calendar-controls'));
955 $content .= $left;
956 $content .= '<span class="hide"> | </span><span class="current">'.userdate($time, get_string('strftimedaydate')).'</span>';
957 $content .= '<span class="hide"> | </span>'. $right;
958 $content .= "<span class=\"clearer\"><!-- --></span>";
959 $content .= html_writer::end_tag('div')."\n";
960
961 break;
7423f116 962 }
963 return $content;
964}
965
ef21ad21
FM
966/**
967 * Formats a filter control element.
968 *
969 * @param moodle_url $url of the filter
970 * @param int $type constant defining the type filter
971 * @return string html content of the element
972 */
973function calendar_filter_controls_element(moodle_url $url, $type) {
974 global $OUTPUT;
975 switch ($type) {
976 case CALENDAR_EVENT_GLOBAL:
977 $typeforhumans = 'global';
978 $class = 'calendar_event_global';
979 break;
980 case CALENDAR_EVENT_COURSE:
981 $typeforhumans = 'course';
982 $class = 'calendar_event_course';
983 break;
984 case CALENDAR_EVENT_GROUP:
985 $typeforhumans = 'groups';
986 $class = 'calendar_event_group';
987 break;
988 case CALENDAR_EVENT_USER:
989 $typeforhumans = 'user';
990 $class = 'calendar_event_user';
991 break;
992 }
993 if (calendar_show_event_type($type)) {
994 $icon = $OUTPUT->pix_icon('t/hide', get_string('hide'));
995 $str = get_string('hide'.$typeforhumans.'events', 'calendar');
996 } else {
997 $icon = $OUTPUT->pix_icon('t/show', get_string('show'));
998 $str = get_string('show'.$typeforhumans.'events', 'calendar');
999 }
1000 $content = html_writer::start_tag('li', array('class' => 'calendar_event'));
1001 $content .= html_writer::start_tag('a', array('href' => $url));
1002 $content .= html_writer::tag('span', $icon, array('class' => $class));
1003 $content .= html_writer::tag('span', $str, array('class' => 'eventname'));
1004 $content .= html_writer::end_tag('a');
1005 $content .= html_writer::end_tag('li');
1006 return $content;
1007}
1008
08b4a4e1
RW
1009/**
1010 * Get the controls filter for calendar.
1011 *
1012 * Filter is used to hide calendar info from the display page
1013 *
1014 * @param moodle_url $returnurl return-url for filter controls
1015 * @return string $content return filter controls in html
1016 */
797cedc7
SH
1017function calendar_filter_controls(moodle_url $returnurl) {
1018 global $CFG, $USER, $OUTPUT;
7423f116 1019
48f508ab 1020 $groupevents = true;
7f4d18fc 1021 $id = optional_param( 'id',0,PARAM_INT );
abc5f845 1022 $seturl = new moodle_url('/calendar/set.php', array('return' => base64_encode($returnurl->out_as_local_url(false)), 'sesskey'=>sesskey()));
ef21ad21 1023 $content = html_writer::start_tag('ul');
797cedc7
SH
1024
1025 $seturl->param('var', 'showglobal');
ef21ad21 1026 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GLOBAL);
aa6c1ced 1027
797cedc7 1028 $seturl->param('var', 'showcourses');
ef21ad21 1029 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_COURSE);
48f508ab 1030
4f0c2d00 1031 if (isloggedin() && !isguestuser()) {
797cedc7 1032 if ($groupevents) {
43c3ffbe 1033 // This course MIGHT have group events defined, so show the filter
797cedc7 1034 $seturl->param('var', 'showgroups');
ef21ad21 1035 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_GROUP);
e3bb6401 1036 } else {
43c3ffbe 1037 // This course CANNOT have group events, so lose the filter
fdbffa54 1038 }
797cedc7 1039 $seturl->param('var', 'showuser');
ef21ad21 1040 $content .= calendar_filter_controls_element($seturl, CALENDAR_EVENT_USER);
48f508ab 1041 }
ef21ad21 1042 $content .= html_writer::end_tag('ul');
48f508ab 1043
7423f116 1044 return $content;
1045}
1046
08b4a4e1
RW
1047/**
1048 * Return the representation day
1049 *
1050 * @param int $tstamp Timestamp in GMT
1051 * @param int $now current Unix timestamp
1052 * @param bool $usecommonwords
1053 * @return string the formatted date/time
1054 */
7423f116 1055function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
1056
0ef7c973 1057 static $shortformat;
1058 if(empty($shortformat)) {
e70fdac0 1059 $shortformat = get_string('strftimedayshort');
0ef7c973 1060 }
1061
7423f116 1062 if($now === false) {
1063 $now = time();
1064 }
1065
1066 // To have it in one place, if a change is needed
e70fdac0 1067 $formal = userdate($tstamp, $shortformat);
7423f116 1068
7b38bfa6 1069 $datestamp = usergetdate($tstamp);
1070 $datenow = usergetdate($now);
7423f116 1071
1072 if($usecommonwords == false) {
1073 // We don't want words, just a date
1074 return $formal;
1075 }
7b38bfa6 1076 else if($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
7423f116 1077 // Today
1078 return get_string('today', 'calendar');
1079 }
7b38bfa6 1080 else if(
1081 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1082 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12 && $datenow['yday'] == 1)
1083 ) {
7423f116 1084 // Yesterday
1085 return get_string('yesterday', 'calendar');
1086 }
7b38bfa6 1087 else if(
1088 ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1089 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12 && $datestamp['yday'] == 1)
1090 ) {
7423f116 1091 // Tomorrow
1092 return get_string('tomorrow', 'calendar');
1093 }
1094 else {
1095 return $formal;
1096 }
1097}
1098
08b4a4e1
RW
1099/**
1100 * return the formatted representation time
1101 *
1102 * @param int $time the timestamp in UTC, as obtained from the database
1103 * @return string the formatted date/time
1104 */
7423f116 1105function calendar_time_representation($time) {
1b0ebe79 1106 static $langtimeformat = NULL;
1107 if($langtimeformat === NULL) {
1108 $langtimeformat = get_string('strftimetime');
1109 }
1110 $timeformat = get_user_preferences('calendar_timeformat');
c7dd2550 1111 if(empty($timeformat)){
1112 $timeformat = get_config(NULL,'calendar_site_timeformat');
1113 }
1b0ebe79 1114 // The ? is needed because the preference might be present, but empty
1115 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
7423f116 1116}
1117
e295df44 1118/**
14236cbd
SH
1119 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1120 *
1121 * @param string|moodle_url $linkbase
08b4a4e1
RW
1122 * @param int $d The number of the day.
1123 * @param int $m The number of the month.
1124 * @param int $y The number of the year.
da304137
MN
1125 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1126 * $m and $y are kept for backwards compatibility.
08b4a4e1 1127 * @return moodle_url|null $linkbase
e295df44 1128 */
da304137 1129function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
0f927f1e
SH
1130 if (empty($linkbase)) {
1131 return '';
1132 }
1133 if (!($linkbase instanceof moodle_url)) {
e30390a0 1134 $linkbase = new moodle_url($linkbase);
0f927f1e 1135 }
da304137
MN
1136
1137 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1138 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1139 // should we be passing these values rather than the time.
1140 if (!empty($d) && !empty($m) && !empty($y)) {
1141 if (checkdate($m, $d, $y)) {
1142 $time = make_timestamp($y, $m, $d);
1143 } else {
1144 $time = time();
1145 }
1146 } else if (empty($time)) {
1147 $time = time();
0f927f1e 1148 }
da304137
MN
1149
1150 $linkbase->param('time', $time);
1151
0f927f1e 1152 return $linkbase;
7423f116 1153}
1154
a84dea2c 1155/**
1156 * Build and return a previous month HTML link, with an arrow.
14236cbd 1157 *
a84dea2c 1158 * @param string $text The text label.
14236cbd 1159 * @param string|moodle_url $linkbase The URL stub.
08b4a4e1
RW
1160 * @param int $d The number of the date.
1161 * @param int $m The number of the month.
1162 * @param int $y year The number of the year.
a84dea2c 1163 * @param bool $accesshide Default visible, or hide from all except screenreaders.
da304137
MN
1164 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1165 * $m and $y are kept for backwards compatibility.
a84dea2c 1166 * @return string HTML string.
1167 */
da304137
MN
1168function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1169 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y, $time);
0f927f1e
SH
1170 if (empty($href)) {
1171 return $text;
1172 }
1173 return link_arrow_left($text, (string)$href, $accesshide, 'previous');
a84dea2c 1174}
1175
1176/**
1177 * Build and return a next month HTML link, with an arrow.
1d5bd3d2 1178 *
a84dea2c 1179 * @param string $text The text label.
14236cbd 1180 * @param string|moodle_url $linkbase The URL stub.
08b4a4e1
RW
1181 * @param int $d the number of the Day
1182 * @param int $m The number of the month.
1183 * @param int $y The number of the year.
a84dea2c 1184 * @param bool $accesshide Default visible, or hide from all except screenreaders.
da304137
MN
1185 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1186 * $m and $y are kept for backwards compatibility.
a84dea2c 1187 * @return string HTML string.
1188 */
da304137
MN
1189function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
1190 $href = calendar_get_link_href(new moodle_url($linkbase), $d, $m, $y, $time);
0f927f1e
SH
1191 if (empty($href)) {
1192 return $text;
1193 }
1194 return link_arrow_right($text, (string)$href, $accesshide, 'next');
a84dea2c 1195}
1196
08b4a4e1
RW
1197/**
1198 * Return the name of the weekday
1199 *
1200 * @param string $englishname
1201 * @return string of the weekeday
1202 */
7423f116 1203function calendar_wday_name($englishname) {
1204 return get_string(strtolower($englishname), 'calendar');
1205}
1206
08b4a4e1
RW
1207/**
1208 * Return the number of days in month
1209 *
1210 * @param int $month the number of the month.
1211 * @param int $year the number of the year
1212 * @return int
1213 */
7423f116 1214function calendar_days_in_month($month, $year) {
da304137
MN
1215 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1216 return $calendartype->get_num_days_in_month($year, $month);
7423f116 1217}
1218
08b4a4e1
RW
1219/**
1220 * Get the upcoming event block
1221 *
1222 * @param array $events list of events
1223 * @param moodle_url|string $linkhref link to event referer
f6a5ffe8 1224 * @param boolean $showcourselink whether links to courses should be shown
08b4a4e1
RW
1225 * @return string|null $content html block content
1226 */
f6a5ffe8 1227function calendar_get_block_upcoming($events, $linkhref = NULL, $showcourselink = false) {
7423f116 1228 $content = '';
1229 $lines = count($events);
396b61f0 1230 if (!$lines) {
1231 return $content;
1232 }
7423f116 1233
396b61f0 1234 for ($i = 0; $i < $lines; ++$i) {
b0ac9180 1235 if (!isset($events[$i]->time)) { // Just for robustness
1236 continue;
1237 }
9df8ff44 1238 $events[$i] = calendar_add_event_metadata($events[$i]);
857c5f90 1239 $content .= '<div class="event"><span class="icon c0">'.$events[$i]->icon.'</span>';
43c3ffbe 1240 if (!empty($events[$i]->referer)) {
7423f116 1241 // That's an activity event, so let's provide the hyperlink
396b61f0 1242 $content .= $events[$i]->referer;
1243 } else {
e749554e 1244 if(!empty($linkhref)) {
da304137 1245 $href = calendar_get_link_href(new moodle_url(CALENDAR_URL . $linkhref), 0, 0, 0, $events[$i]->timestart);
0f927f1e
SH
1246 $href->set_anchor('event_'.$events[$i]->id);
1247 $content .= html_writer::link($href, $events[$i]->name);
e749554e 1248 }
1249 else {
1250 $content .= $events[$i]->name;
1251 }
7423f116 1252 }
9ecf051d 1253 $events[$i]->time = str_replace('&raquo;', '<br />&raquo;', $events[$i]->time);
f6a5ffe8
HB
1254 if ($showcourselink && !empty($events[$i]->courselink)) {
1255 $content .= html_writer::div($events[$i]->courselink, 'course');
1256 }
9ecf051d 1257 $content .= '<div class="date">'.$events[$i]->time.'</div></div>';
396b61f0 1258 if ($i < $lines - 1) $content .= '<hr />';
7423f116 1259 }
1260
1261 return $content;
7423f116 1262}
1263
08b4a4e1
RW
1264/**
1265 * Get the next following month
1266 *
08b4a4e1
RW
1267 * @param int $month the number of the month.
1268 * @param int $year the number of the year.
1269 * @return array the following month
1270 */
7423f116 1271function calendar_add_month($month, $year) {
da304137
MN
1272 // Get the calendar type we are using.
1273 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1274 return $calendartype->get_next_month($year, $month);
7423f116 1275}
1276
08b4a4e1 1277/**
da304137 1278 * Get the previous month.
08b4a4e1
RW
1279 *
1280 * @param int $month the number of the month.
1281 * @param int $year the number of the year.
1282 * @return array previous month
1283 */
7423f116 1284function calendar_sub_month($month, $year) {
da304137
MN
1285 // Get the calendar type we are using.
1286 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1287 return $calendartype->get_prev_month($year, $month);
7423f116 1288}
1289
08b4a4e1
RW
1290/**
1291 * Get per-day basis events
1292 *
1293 * @param array $events list of events
1294 * @param int $month the number of the month
1295 * @param int $year the number of the year
1296 * @param array $eventsbyday event on specific day
1297 * @param array $durationbyday duration of the event in days
1298 * @param array $typesbyday event type (eg: global, course, user, or group)
1299 * @param array $courses list of courses
1300 * @return void
1301 */
7c50db30 1302function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
da304137
MN
1303 // Get the calendar type we are using.
1304 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1305
7423f116 1306 $eventsbyday = array();
1307 $typesbyday = array();
1308 $durationbyday = array();
1309
1310 if($events === false) {
1311 return;
1312 }
1313
da304137
MN
1314 foreach ($events as $event) {
1315 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
b4892fa2 1316 // Set end date = start date if no duration
1317 if ($event->timeduration) {
da304137 1318 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
b4892fa2 1319 } else {
1320 $enddate = $startdate;
1321 }
7423f116 1322
7b38bfa6 1323 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair
ef618501 1324 if(!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) && ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
7b38bfa6 1325 // Out of bounds
1326 continue;
7423f116 1327 }
1328
7b38bfa6 1329 $eventdaystart = intval($startdate['mday']);
7423f116 1330
7b38bfa6 1331 if($startdate['mon'] == $month && $startdate['year'] == $year) {
1332 // Give the event to its day
1333 $eventsbyday[$eventdaystart][] = $event->id;
7423f116 1334
7b38bfa6 1335 // Mark the day as having such an event
9064751b 1336 if($event->courseid == SITEID && $event->groupid == 0) {
7b38bfa6 1337 $typesbyday[$eventdaystart]['startglobal'] = true;
b4892fa2 1338 // Set event class for global event
90723839 1339 $events[$event->id]->class = 'calendar_event_global';
7b38bfa6 1340 }
c3d3b6d4 1341 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
7b38bfa6 1342 $typesbyday[$eventdaystart]['startcourse'] = true;
b4892fa2 1343 // Set event class for course event
90723839 1344 $events[$event->id]->class = 'calendar_event_course';
7b38bfa6 1345 }
1346 else if($event->groupid) {
1347 $typesbyday[$eventdaystart]['startgroup'] = true;
b4892fa2 1348 // Set event class for group event
90723839 1349 $events[$event->id]->class = 'calendar_event_group';
7b38bfa6 1350 }
1351 else if($event->userid) {
1352 $typesbyday[$eventdaystart]['startuser'] = true;
b4892fa2 1353 // Set event class for user event
90723839 1354 $events[$event->id]->class = 'calendar_event_user';
7b38bfa6 1355 }
1356 }
7423f116 1357
7b38bfa6 1358 if($event->timeduration == 0) {
1359 // Proceed with the next
1360 continue;
1361 }
7423f116 1362
7b38bfa6 1363 // The event starts on $month $year or before. So...
ef618501 1364 $lowerbound = $startdate['mon'] == $month && $startdate['year'] == $year ? intval($startdate['mday']) : 0;
7b38bfa6 1365
1366 // Also, it ends on $month $year or later...
1367 $upperbound = $enddate['mon'] == $month && $enddate['year'] == $year ? intval($enddate['mday']) : calendar_days_in_month($month, $year);
1368
1369 // Mark all days between $lowerbound and $upperbound (inclusive) as duration
1370 for($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
1371 $durationbyday[$i][] = $event->id;
9064751b 1372 if($event->courseid == SITEID && $event->groupid == 0) {
7b38bfa6 1373 $typesbyday[$i]['durationglobal'] = true;
1374 }
c3d3b6d4 1375 else if($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
7b38bfa6 1376 $typesbyday[$i]['durationcourse'] = true;
1377 }
1378 else if($event->groupid) {
1379 $typesbyday[$i]['durationgroup'] = true;
1380 }
1381 else if($event->userid) {
1382 $typesbyday[$i]['durationuser'] = true;
7423f116 1383 }
1384 }
7b38bfa6 1385
7423f116 1386 }
1387 return;
1388}
1389
08b4a4e1
RW
1390/**
1391 * Get current module cache
1392 *
1393 * @param array $coursecache list of course cache
1394 * @param string $modulename name of the module
1395 * @param int $instance module instance number
1396 * @return stdClass|bool $module information
1397 */
b63c0ee5 1398function calendar_get_module_cached(&$coursecache, $modulename, $instance) {
1399 $module = get_coursemodule_from_instance($modulename, $instance);
7423f116 1400
1401 if($module === false) return false;
b63c0ee5 1402 if(!calendar_get_course_cached($coursecache, $module->course)) {
7423f116 1403 return false;
1404 }
1405 return $module;
1406}
1407
08b4a4e1
RW
1408/**
1409 * Get current course cache
1410 *
1411 * @param array $coursecache list of course cache
1412 * @param int $courseid id of the course
1413 * @return stdClass $coursecache[$courseid] return the specific course cache
1414 */
7423f116 1415function calendar_get_course_cached(&$coursecache, $courseid) {
b571c6b3 1416 if (!isset($coursecache[$courseid])) {
d20b0aa5 1417 $coursecache[$courseid] = get_course($courseid);
7423f116 1418 }
1419 return $coursecache[$courseid];
1420}
1421
797cedc7
SH
1422/**
1423 * Returns the courses to load events for, the
1424 *
797cedc7 1425 * @param array $courseeventsfrom An array of courses to load calendar events for
08b4a4e1 1426 * @param bool $ignorefilters specify the use of filters, false is set as default
797cedc7
SH
1427 * @return array An array of courses, groups, and user to load calendar events for based upon filters
1428 */
1429function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false) {
1430 global $USER, $CFG, $DB;
7423f116 1431
797cedc7
SH
1432 // For backwards compatability we have to check whether the courses array contains
1433 // just id's in which case we need to load course objects.
1434 $coursestoload = array();
1435 foreach ($courseeventsfrom as $id => $something) {
1436 if (!is_object($something)) {
1437 $coursestoload[] = $id;
1438 unset($courseeventsfrom[$id]);
753b799d 1439 }
dd97c328 1440 }
797cedc7
SH
1441 if (!empty($coursestoload)) {
1442 // TODO remove this in 2.2
1443 debugging('calendar_set_filters now preferes an array of course objects with preloaded contexts', DEBUG_DEVELOPER);
1444 $courseeventsfrom = array_merge($courseeventsfrom, $DB->get_records_list('course', 'id', $coursestoload));
89adb174 1445 }
7423f116 1446
797cedc7
SH
1447 $courses = array();
1448 $user = false;
1449 $group = false;
7423f116 1450
7fd5786e
HB
1451 // capabilities that allow seeing group events from all groups
1452 // TODO: rewrite so that moodle/calendar:manageentries is not necessary here
1453 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
1454
797cedc7 1455 $isloggedin = isloggedin();
d12e3ff2 1456
797cedc7
SH
1457 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE)) {
1458 $courses = array_keys($courseeventsfrom);
7423f116 1459 }
797cedc7
SH
1460 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL)) {
1461 $courses[] = SITEID;
7423f116 1462 }
797cedc7
SH
1463 $courses = array_unique($courses);
1464 sort($courses);
7c50db30 1465
797cedc7 1466 if (!empty($courses) && in_array(SITEID, $courses)) {
7c50db30 1467 // Sort courses for consistent colour highlighting
1468 // Effectively ignoring SITEID as setting as last course id
1469 $key = array_search(SITEID, $courses);
797cedc7
SH
1470 unset($courses[$key]);
1471 $courses[] = SITEID;
0e6a8f4b 1472 }
7423f116 1473
797cedc7
SH
1474 if ($ignorefilters || ($isloggedin && calendar_show_event_type(CALENDAR_EVENT_USER))) {
1475 $user = $USER->id;
7423f116 1476 }
257e3f4c 1477
797cedc7
SH
1478 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP) || $ignorefilters)) {
1479
7fd5786e
HB
1480 if (count($courseeventsfrom)==1) {
1481 $course = reset($courseeventsfrom);
6ca657a7 1482 if (has_any_capability($allgroupscaps, context_course::instance($course->id))) {
7fd5786e
HB
1483 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
1484 $group = array_keys($coursegroups);
7423f116 1485 }
7fd5786e
HB
1486 }
1487 if ($group === false) {
0601e0ee 1488 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, context_system::instance())) {
7fd5786e
HB
1489 $group = true;
1490 } else if ($isloggedin) {
1491 $groupids = array();
c46da759 1492
7fd5786e
HB
1493 // We already have the courses to examine in $courses
1494 // For each course...
1495 foreach ($courseeventsfrom as $courseid => $course) {
1496 // If the user is an editing teacher in there,
1497 if (!empty($USER->groupmember[$course->id])) {
1498 // We've already cached the users groups for this course so we can just use that
1499 $groupids = array_merge($groupids, $USER->groupmember[$course->id]);
1500 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
1501 // If this course has groups, show events from all of those related to the current user
1502 $coursegroups = groups_get_user_groups($course->id, $USER->id);
1503 $groupids = array_merge($groupids, $coursegroups['0']);
1504 }
1505 }
1506 if (!empty($groupids)) {
1507 $group = $groupids;
1508 }
6c9584d1 1509 }
7423f116 1510 }
7423f116 1511 }
797cedc7
SH
1512 if (empty($courses)) {
1513 $courses = false;
7423f116 1514 }
797cedc7
SH
1515
1516 return array($courses, $group, $user);
7423f116 1517}
1518
08b4a4e1
RW
1519/**
1520 * Return the capability for editing calendar event
1521 *
1522 * @param calendar_event $event event object
1523 * @return bool capability to edit event
1524 */
7423f116 1525function calendar_edit_event_allowed($event) {
62d11d77 1526 global $USER, $DB;
7423f116 1527
2ac8da76 1528 // Must be logged in
1529 if (!isloggedin()) {
1530 return false;
1531 }
1532
89491dbd 1533 // can not be using guest account
2396a414 1534 if (isguestuser()) {
e295df44 1535 return false;
89491dbd 1536 }
e295df44 1537
e6059873
SH
1538 // You cannot edit calendar subscription events presently.
1539 if (!empty($event->subscriptionid)) {
1540 return false;
1541 }
1542
6ca657a7 1543 $sitecontext = context_system::instance();
89491dbd 1544 // if user has manageentries at site level, return true
28ee98c5 1545 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
89491dbd 1546 return true;
f52f7413 1547 }
e295df44 1548
c0a2c361 1549 // if groupid is set, it's definitely a group event
438e4add 1550 if (!empty($event->groupid)) {
f63d2922 1551 // Allow users to add/edit group events if:
1552 // 1) They have manageentries (= entries for whole course)
1553 // 2) They have managegroupentries AND are in the group
62d11d77 1554 $group = $DB->get_record('groups', array('id'=>$event->groupid));
f63d2922 1555 return $group && (
f4700b91
RW
1556 has_capability('moodle/calendar:manageentries', $event->context) ||
1557 (has_capability('moodle/calendar:managegroupentries', $event->context)
f63d2922 1558 && groups_is_member($event->groupid)));
438e4add 1559 } else if (!empty($event->courseid)) {
c0a2c361 1560 // if groupid is not set, but course is set,
1561 // it's definiely a course event
f4700b91 1562 return has_capability('moodle/calendar:manageentries', $event->context);
438e4add 1563 } else if (!empty($event->userid) && $event->userid == $USER->id) {
c0a2c361 1564 // if course is not set, but userid id set, it's a user event
f4700b91
RW
1565 return (has_capability('moodle/calendar:manageownentries', $event->context));
1566 } else if (!empty($event->userid)) {
1567 return (has_capability('moodle/calendar:manageentries', $event->context));
e295df44 1568 }
7423f116 1569 return false;
1570}
1571
797cedc7
SH
1572/**
1573 * Returns the default courses to display on the calendar when there isn't a specific
1574 * course to display.
1575 *
08b4a4e1 1576 * @return array $courses Array of courses to display
797cedc7
SH
1577 */
1578function calendar_get_default_courses() {
1579 global $CFG, $DB;
7423f116 1580
4f0c2d00 1581 if (!isloggedin()) {
2ef75eee 1582 return array();
1583 }
1584
7423f116 1585 $courses = array();
d083084a 1586 if (!empty($CFG->calendar_adminseesall) && has_capability('moodle/calendar:manageentries', context_system::instance())) {
2e4c0c91
FM
1587 $select = ', ' . context_helper::get_preload_record_columns_sql('ctx');
1588 $join = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
d083084a 1589 $sql = "SELECT c.* $select
797cedc7 1590 FROM {course} c
d083084a
ARN
1591 $join
1592 WHERE EXISTS (SELECT 1 FROM {event} e WHERE e.courseid = c.id)
1593 ";
2e4c0c91 1594 $courses = $DB->get_records_sql($sql, array('contextlevel' => CONTEXT_COURSE), 0, 20);
797cedc7 1595 foreach ($courses as $course) {
d083084a 1596 context_helper::preload_from_record($course);
86f092d2 1597 }
797cedc7 1598 return $courses;
95a89225 1599 }
e295df44 1600
df997f84 1601 $courses = enrol_get_my_courses();
37d87d11 1602
1603 return $courses;
7423f116 1604}
1605
08b4a4e1
RW
1606/**
1607 * Display calendar preference button
1608 *
1609 * @param stdClass $course course object
1610 * @return string return preference button in html
1611 */
797cedc7
SH
1612function calendar_preferences_button(stdClass $course) {
1613 global $OUTPUT;
7423f116 1614
1615 // Guests have no preferences
4f0c2d00 1616 if (!isloggedin() || isguestuser()) {
7423f116 1617 return '';
1618 }
1619
797cedc7 1620 return $OUTPUT->single_button(new moodle_url('/calendar/preferences.php', array('course' => $course->id)), get_string("preferences", "calendar"));
7423f116 1621}
1622
08b4a4e1
RW
1623/**
1624 * Get event format time
1625 *
1626 * @param calendar_event $event event object
1627 * @param int $now current time in gmt
1628 * @param array $linkparams list of params for event link
1629 * @param bool $usecommonwords the words as formatted date/time.
1630 * @param int $showtime determine the show time GMT timestamp
1631 * @return string $eventtime link/string for event time
1632 */
da304137
MN
1633function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
1634 $starttime = $event->timestart;
1635 $endtime = $event->timestart + $event->timeduration;
8f896582 1636
0f927f1e
SH
1637 if (empty($linkparams) || !is_array($linkparams)) {
1638 $linkparams = array();
1639 }
da304137 1640
0f927f1e
SH
1641 $linkparams['view'] = 'day';
1642
8f896582 1643 // OK, now to get a meaningful display...
da304137
MN
1644 // Check if there is a duration for this event.
1645 if ($event->timeduration) {
1646 // Get the midnight of the day the event will start.
1647 $usermidnightstart = usergetmidnight($starttime);
1648 // Get the midnight of the day the event will end.
1649 $usermidnightend = usergetmidnight($endtime);
1650 // Check if we will still be on the same day.
1651 if ($usermidnightstart == $usermidnightend) {
1652 // Check if we are running all day.
1653 if ($event->timeduration == DAYSECS) {
b4892fa2 1654 $time = get_string('allday', 'calendar');
da304137
MN
1655 } else { // Specify the time we will be running this from.
1656 $datestart = calendar_time_representation($starttime);
1657 $dateend = calendar_time_representation($endtime);
1658 $time = $datestart . ' <strong>&raquo;</strong> ' . $dateend;
b4892fa2 1659 }
8f896582 1660
da304137 1661 // Set printable representation.
b4892fa2 1662 if (!$showtime) {
1663 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
da304137
MN
1664 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
1665 $eventtime = html_writer::link($url, $day) . ', ' . $time;
b4892fa2 1666 } else {
1667 $eventtime = $time;
1668 }
da304137
MN
1669 } else { // It must spans two or more days.
1670 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
b4892fa2 1671 if ($showtime == $usermidnightstart) {
1672 $daystart = '';
1673 }
8f896582 1674 $timestart = calendar_time_representation($event->timestart);
da304137 1675 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
b4892fa2 1676 if ($showtime == $usermidnightend) {
1677 $dayend = '';
1678 }
8f896582 1679 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
1680
da304137
MN
1681 // Set printable representation.
1682 if ($now >= $usermidnightstart && $now < ($usermidnightstart + DAYSECS)) {
1683 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
1684 $eventtime = $timestart . ' <strong>&raquo;</strong> ' . html_writer::link($url, $dayend) . $timeend;
b4892fa2 1685 } else {
da304137
MN
1686 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
1687 $eventtime = html_writer::link($url, $daystart) . $timestart . ' <strong>&raquo;</strong> ';
1d5bd3d2 1688
da304137
MN
1689 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
1690 $eventtime .= html_writer::link($url, $dayend) . $timeend;
b4892fa2 1691 }
8f896582 1692 }
da304137 1693 } else { // There is no time duration.
2af268a1 1694 $time = calendar_time_representation($event->timestart);
da304137 1695 // Set printable representation.
b4892fa2 1696 if (!$showtime) {
1697 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
da304137
MN
1698 $url = calendar_get_link_href(new moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
1699 $eventtime = html_writer::link($url, $day) . ', ' . trim($time);
b4892fa2 1700 } else {
1701 $eventtime = $time;
1702 }
1703 }
1704
da304137
MN
1705 // Check if It has expired.
1706 if ($event->timestart + $event->timeduration < $now) {
1707 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
8f896582 1708 }
09d36284 1709
8f896582 1710 return $eventtime;
1711}
054193be 1712
08b4a4e1
RW
1713/**
1714 * Display month selector options
1715 *
1716 * @param string $name for the select element
1717 * @param string|array $selected options for select elements
1718 */
86f092d2 1719function calendar_print_month_selector($name, $selected) {
86f092d2 1720 $months = array();
86f092d2 1721 for ($i=1; $i<=12; $i++) {
76ab1c33 1722 $months[$i] = userdate(gmmktime(12, 0, 0, $i, 15, 2000), '%B');
86f092d2 1723 }
5c576552 1724 echo html_writer::label(get_string('months'), 'menu'. $name, false, array('class' => 'accesshide'));
d776d59e 1725 echo html_writer::select($months, $name, $selected, false);
86f092d2 1726}
1727
797cedc7
SH
1728/**
1729 * Checks to see if the requested type of event should be shown for the given user.
1730 *
1731 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type
1732 * The type to check the display for (default is to display all)
1733 * @param stdClass|int|null $user The user to check for - by default the current user
1734 * @return bool True if the tyep should be displayed false otherwise
1735 */
1736function calendar_show_event_type($type, $user = null) {
1737 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1738 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
1739 global $SESSION;
1740 if (!isset($SESSION->calendarshoweventtype)) {
1741 $SESSION->calendarshoweventtype = $default;
1742 }
1743 return $SESSION->calendarshoweventtype & $type;
1744 } else {
1745 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
054193be 1746 }
797cedc7
SH
1747}
1748
1749/**
1750 * Sets the display of the event type given $display.
08b4a4e1 1751 *
797cedc7
SH
1752 * If $display = true the event type will be shown.
1753 * If $display = false the event type will NOT be shown.
1754 * If $display = null the current value will be toggled and saved.
1755 *
08b4a4e1
RW
1756 * @param CALENDAR_EVENT_GLOBAL|CALENDAR_EVENT_COURSE|CALENDAR_EVENT_GROUP|CALENDAR_EVENT_USER $type object of CALENDAR_EVENT_XXX
1757 * @param bool $display option to display event type
1758 * @param stdClass|int $user moodle user object or id, null means current user
797cedc7
SH
1759 */
1760function calendar_set_event_type_display($type, $display = null, $user = null) {
1761 $persist = get_user_preferences('calendar_persistflt', 0, $user);
1762 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
1763 if ($persist === 0) {
1764 global $SESSION;
1765 if (!isset($SESSION->calendarshoweventtype)) {
1766 $SESSION->calendarshoweventtype = $default;
1767 }
1768 $preference = $SESSION->calendarshoweventtype;
1769 } else {
1770 $preference = get_user_preferences('calendar_savedflt', $default, $user);
054193be 1771 }
797cedc7
SH
1772 $current = $preference & $type;
1773 if ($display === null) {
1774 $display = !$current;
054193be 1775 }
797cedc7
SH
1776 if ($display && !$current) {
1777 $preference += $type;
1778 } else if (!$display && $current) {
1779 $preference -= $type;
054193be 1780 }
797cedc7
SH
1781 if ($persist === 0) {
1782 $SESSION->calendarshoweventtype = $preference;
1783 } else {
1784 if ($preference == $default) {
1785 unset_user_preference('calendar_savedflt', $user);
1786 } else {
1787 set_user_preference('calendar_savedflt', $preference, $user);
1788 }
054193be 1789 }
054193be 1790}
1791
08b4a4e1
RW
1792/**
1793 * Get calendar's allowed types
1794 *
1795 * @param stdClass $allowed list of allowed edit for event type
1796 * @param stdClass|int $course object of a course or course id
1797 */
797cedc7
SH
1798function calendar_get_allowed_types(&$allowed, $course = null) {
1799 global $USER, $CFG, $DB;
b85b25eb 1800 $allowed = new stdClass();
0601e0ee 1801 $allowed->user = has_capability('moodle/calendar:manageownentries', context_system::instance());
86ac8b24 1802 $allowed->groups = false; // This may change just below
1803 $allowed->courses = false; // This may change just below
6ca657a7 1804 $allowed->site = has_capability('moodle/calendar:manageentries', context_course::instance(SITEID));
86ac8b24 1805
797cedc7
SH
1806 if (!empty($course)) {
1807 if (!is_object($course)) {
74df2951 1808 $course = $DB->get_record('course', array('id' => $course), '*', MUST_EXIST);
797cedc7
SH
1809 }
1810 if ($course->id != SITEID) {
6ca657a7 1811 $coursecontext = context_course::instance($course->id);
3c0ea9b2 1812 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
86ac8b24 1813
797cedc7
SH
1814 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
1815 $allowed->courses = array($course->id => 1);
aa6c1ced 1816
797cedc7 1817 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
462e42cb
JP
1818 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
1819 $allowed->groups = groups_get_all_groups($course->id);
1820 } else {
1821 $allowed->groups = groups_get_all_groups($course->id, $USER->id);
1822 }
797cedc7
SH
1823 }
1824 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
1825 if($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
462e42cb
JP
1826 if (has_capability('moodle/site:accessallgroups', $coursecontext)) {
1827 $allowed->groups = groups_get_all_groups($course->id);
1828 } else {
1829 $allowed->groups = groups_get_all_groups($course->id, $USER->id);
1830 }
797cedc7 1831 }
f63d2922 1832 }
86ac8b24 1833 }
1834 }
1835}
1836
1837/**
08b4a4e1 1838 * See if user can add calendar entries at all
86ac8b24 1839 * used to print the "New Event" button
08b4a4e1
RW
1840 *
1841 * @param stdClass $course object of a course or course id
1842 * @return bool has the capability to add at least one event type
86ac8b24 1843 */
797cedc7
SH
1844function calendar_user_can_add_event($course) {
1845 if (!isloggedin() || isguestuser()) {
1846 return false;
1847 }
1848 calendar_get_allowed_types($allowed, $course);
e295df44 1849 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->site);
86ac8b24 1850}
76d9df3f
SH
1851
1852/**
1853 * Check wether the current user is permitted to add events
1854 *
08b4a4e1
RW
1855 * @param stdClass $event object of event
1856 * @return bool has the capability to add event
76d9df3f
SH
1857 */
1858function calendar_add_event_allowed($event) {
1859 global $USER, $DB;
1860
1861 // can not be using guest account
4f0c2d00 1862 if (!isloggedin() or isguestuser()) {
76d9df3f
SH
1863 return false;
1864 }
1865
6ca657a7 1866 $sitecontext = context_system::instance();
76d9df3f
SH
1867 // if user has manageentries at site level, always return true
1868 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
1869 return true;
1870 }
1871
1872 switch ($event->eventtype) {
1873 case 'course':
f4700b91 1874 return has_capability('moodle/calendar:manageentries', $event->context);
76d9df3f
SH
1875
1876 case 'group':
1877 // Allow users to add/edit group events if:
1878 // 1) They have manageentries (= entries for whole course)
1879 // 2) They have managegroupentries AND are in the group
1880 $group = $DB->get_record('groups', array('id'=>$event->groupid));
1881 return $group && (
f4700b91
RW
1882 has_capability('moodle/calendar:manageentries', $event->context) ||
1883 (has_capability('moodle/calendar:managegroupentries', $event->context)
76d9df3f
SH
1884 && groups_is_member($event->groupid)));
1885
1886 case 'user':
1887 if ($event->userid == $USER->id) {
f4700b91 1888 return (has_capability('moodle/calendar:manageownentries', $event->context));
76d9df3f
SH
1889 }
1890 //there is no 'break;' intentionally
1891
1892 case 'site':
f4700b91 1893 return has_capability('moodle/calendar:manageentries', $event->context);
76d9df3f
SH
1894
1895 default:
f4700b91 1896 return has_capability('moodle/calendar:manageentries', $event->context);
76d9df3f
SH
1897 }
1898}
1899
1900/**
08b4a4e1 1901 * Manage calendar events
76d9df3f
SH
1902 *
1903 * This class provides the required functionality in order to manage calendar events.
1904 * It was introduced as part of Moodle 2.0 and was created in order to provide a
1905 * better framework for dealing with calendar events in particular regard to file
1906 * handling through the new file API
1907 *
08b4a4e1
RW
1908 * @package core_calendar
1909 * @category calendar
1910 * @copyright 2009 Sam Hemelryk
1911 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1912 *
76d9df3f
SH
1913 * @property int $id The id within the event table
1914 * @property string $name The name of the event
1915 * @property string $description The description of the event
1916 * @property int $format The format of the description FORMAT_?
1917 * @property int $courseid The course the event is associated with (0 if none)
1918 * @property int $groupid The group the event is associated with (0 if none)
1919 * @property int $userid The user the event is associated with (0 if none)
1920 * @property int $repeatid If this is a repeated event this will be set to the
1921 * id of the original
1922 * @property string $modulename If added by a module this will be the module name
1923 * @property int $instance If added by a module this will be the module instance
1924 * @property string $eventtype The event type
1925 * @property int $timestart The start time as a timestamp
1926 * @property int $timeduration The duration of the event in seconds
1927 * @property int $visible 1 if the event is visible
1928 * @property int $uuid ?
1929 * @property int $sequence ?
1930 * @property int $timemodified The time last modified as a timestamp
1931 */
1932class calendar_event {
1933
08b4a4e1 1934 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
76d9df3f 1935 protected $properties = null;
08b4a4e1 1936
76d9df3f 1937 /**
08b4a4e1 1938 * @var string The converted event discription with file paths resolved. This gets populated when someone requests description for the first time */
76d9df3f 1939 protected $_description = null;
08b4a4e1
RW
1940
1941 /** @var array The options to use with this description editor */
76d9df3f
SH
1942 protected $editoroptions = array(
1943 'subdirs'=>false,
1944 'forcehttps'=>false,
2b35ed1a 1945 'maxfiles'=>-1,
76d9df3f
SH
1946 'maxbytes'=>null,
1947 'trusttext'=>false);
08b4a4e1
RW
1948
1949 /** @var object The context to use with the description editor */
76d9df3f
SH
1950 protected $editorcontext = null;
1951
1952 /**
1953 * Instantiates a new event and optionally populates its properties with the
1954 * data provided
1955 *
1956 * @param stdClass $data Optional. An object containing the properties to for
1957 * an event
1958 */
1959 public function __construct($data=null) {
c203a277 1960 global $CFG, $USER;
76d9df3f
SH
1961
1962 // First convert to object if it is not already (should either be object or assoc array)
1963 if (!is_object($data)) {
1964 $data = (object)$data;
1965 }
1966
1967 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
1968
1969 $data->eventrepeats = 0;
1970
1971 if (empty($data->id)) {
1972 $data->id = null;
1973 }
1974
8a7326ed 1975 if (!empty($data->subscriptionid)) {
e73b527c 1976 $data->subscription = calendar_get_subscription($data->subscriptionid);
8a7326ed
AA
1977 }
1978
c203a277
SH
1979 // Default to a user event
1980 if (empty($data->eventtype)) {
1981 $data->eventtype = 'user';
1982 }
1983
1984 // Default to the current user
1985 if (empty($data->userid)) {
1986 $data->userid = $USER->id;
1987 }
1988
76d9df3f
SH
1989 if (!empty($data->timeduration) && is_array($data->timeduration)) {
1990 $data->timeduration = make_timestamp($data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'], $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
1991 }
1992 if (!empty($data->description) && is_array($data->description)) {
1993 $data->format = $data->description['format'];
1994 $data->description = $data->description['text'];
1995 } else if (empty($data->description)) {
1996 $data->description = '';
20e5da7d 1997 $data->format = editors_get_preferred_format();
76d9df3f 1998 }
c203a277
SH
1999 // Ensure form is defaulted correctly
2000 if (empty($data->format)) {
2001 $data->format = editors_get_preferred_format();
2002 }
76d9df3f 2003
f4700b91
RW
2004 if (empty($data->context)) {
2005 $data->context = $this->calculate_context($data);
2006 }
76d9df3f
SH
2007 $this->properties = $data;
2008 }
2009
2010 /**
2011 * Magic property method
2012 *
2013 * Attempts to call a set_$key method if one exists otherwise falls back
2014 * to simply set the property
2015 *
08b4a4e1
RW
2016 * @param string $key property name
2017 * @param mixed $value value of the property
76d9df3f
SH
2018 */
2019 public function __set($key, $value) {
2020 if (method_exists($this, 'set_'.$key)) {
2021 $this->{'set_'.$key}($value);
2022 }
2023 $this->properties->{$key} = $value;
2024 }
2025
2026 /**
2027 * Magic get method
2028 *
2029 * Attempts to call a get_$key method to return the property and ralls over
2030 * to return the raw property
2031 *
08b4a4e1
RW
2032 * @param string $key property name
2033 * @return mixed property value
76d9df3f
SH
2034 */
2035 public function __get($key) {
2036 if (method_exists($this, 'get_'.$key)) {
2037 return $this->{'get_'.$key}();
2038 }
c203a277
SH
2039 if (!isset($this->properties->{$key})) {
2040 throw new coding_exception('Undefined property requested');
2041 }
76d9df3f
SH
2042 return $this->properties->{$key};
2043 }
2044
2045 /**
2046 * Stupid PHP needs an isset magic method if you use the get magic method and
2047 * still want empty calls to work.... blah ~!
2048 *
08b4a4e1
RW
2049 * @param string $key $key property name
2050 * @return bool|mixed property value, false if property is not exist
76d9df3f
SH
2051 */
2052 public function __isset($key) {
2053 return !empty($this->properties->{$key});
2054 }
2055
f4700b91
RW
2056 /**
2057 * Calculate the context value needed for calendar_event.
2058 * Event's type can be determine by the available value store in $data
2059 * It is important to check for the existence of course/courseid to determine
2060 * the course event.
2061 * Default value is set to CONTEXT_USER
2062 *
08b4a4e1
RW
2063 * @param stdClass $data information about event
2064 * @return stdClass The context object.
f4700b91
RW
2065 */
2066 protected function calculate_context(stdClass $data) {
025d82e0 2067 global $USER, $DB;
f4700b91 2068
f4700b91
RW
2069 $context = null;
2070 if (isset($data->courseid) && $data->courseid > 0) {
6ca657a7 2071 $context = context_course::instance($data->courseid);
f4700b91 2072 } else if (isset($data->course) && $data->course > 0) {
6ca657a7 2073 $context = context_course::instance($data->course);
f4700b91
RW
2074 } else if (isset($data->groupid) && $data->groupid > 0) {
2075 $group = $DB->get_record('groups', array('id'=>$data->groupid));
6ca657a7 2076 $context = context_course::instance($group->courseid);
f4700b91 2077 } else if (isset($data->userid) && $data->userid > 0 && $data->userid == $USER->id) {
6ca657a7 2078 $context = context_user::instance($data->userid);
f4700b91
RW
2079 } else if (isset($data->userid) && $data->userid > 0 && $data->userid != $USER->id &&
2080 isset($data->instance) && $data->instance > 0) {
18d63ffb 2081 $cm = get_coursemodule_from_instance($data->modulename, $data->instance, 0, false, MUST_EXIST);
6ca657a7 2082 $context = context_course::instance($cm->course);
f4700b91 2083 } else {
e30390a0 2084 $context = context_user::instance($data->userid);
f4700b91
RW
2085 }
2086
2087 return $context;
2088 }
2089
76d9df3f
SH
2090 /**
2091 * Returns an array of editoroptions for this event: Called by __get
2092 * Please use $blah = $event->editoroptions;
08b4a4e1
RW
2093 *
2094 * @return array event editor options
76d9df3f
SH
2095 */
2096 protected function get_editoroptions() {
2097 return $this->editoroptions;
2098 }
2099
2100 /**
2101 * Returns an event description: Called by __get
2102 * Please use $blah = $event->description;
2103 *
08b4a4e1 2104 * @return string event description
76d9df3f
SH
2105 */
2106 protected function get_description() {
f4700b91 2107 global $CFG;
99d19c13
PS
2108
2109 require_once($CFG->libdir . '/filelib.php');
2110
76d9df3f
SH
2111 if ($this->_description === null) {
2112 // Check if we have already resolved the context for this event
2113 if ($this->editorcontext === null) {
2114 // Switch on the event type to decide upon the appropriate context
2115 // to use for this event
f4700b91
RW
2116 $this->editorcontext = $this->properties->context;
2117 if ($this->properties->eventtype != 'user' && $this->properties->eventtype != 'course'
2118 && $this->properties->eventtype != 'site' && $this->properties->eventtype != 'group') {
2119 return clean_text($this->properties->description, $this->properties->format);
76d9df3f
SH
2120 }
2121 }
2122
2123 // Work out the item id for the editor, if this is a repeated event then the files will
2124 // be associated with the original
2125 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2126 $itemid = $this->properties->repeatid;
2127 } else {
2128 $itemid = $this->properties->id;
2129 }
2130
2131 // Convert file paths in the description so that things display correctly
64f93798 2132 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php', $this->editorcontext->id, 'calendar', 'event_description', $itemid);
76d9df3f
SH
2133 // Clean the text so no nasties get through
2134 $this->_description = clean_text($this->_description, $this->properties->format);
2135 }
2136 // Finally return the description
2137 return $this->_description;
2138 }
2139
2140 /**
2141 * Return the number of repeat events there are in this events series
aa6c1ced 2142 *
08b4a4e1 2143 * @return int number of event repeated
76d9df3f
SH
2144 */
2145 public function count_repeats() {
2146 global $DB;
2147 if (!empty($this->properties->repeatid)) {
2148 $this->properties->eventrepeats = $DB->count_records('event', array('repeatid'=>$this->properties->repeatid));
2149 // We don't want to count ourselves
2150 $this->properties->eventrepeats--;
2151 }
2152 return $this->properties->eventrepeats;
2153 }
2154
2155 /**
2156 * Update or create an event within the database
2157 *
2158 * Pass in a object containing the event properties and this function will
2159 * insert it into the database and deal with any associated files
2160 *
2161 * @see add_event()
2162 * @see update_event()
2163 *
08b4a4e1
RW
2164 * @param stdClass $data object of event
2165 * @param bool $checkcapability if moodle should check calendar managing capability or not
2166 * @return bool event updated
76d9df3f 2167 */
1d5bd3d2 2168 public function update($data, $checkcapability=true) {
9cb5d05f 2169 global $DB, $USER;
76d9df3f 2170
438e4add
SH
2171 foreach ($data as $key=>$value) {
2172 $this->properties->$key = $value;
2173 }
2174
76d9df3f
SH
2175 $this->properties->timemodified = time();
2176 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
2177
9cb5d05f
AA
2178 // Prepare event data.
2179 $eventargs = array(
2180 'context' => $this->properties->context,
2181 'objectid' => $this->properties->id,
2182 'other' => array(
2183 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
2184 'timestart' => $this->properties->timestart,
2185 'name' => $this->properties->name
2186 )
2187 );
2188
76d9df3f
SH
2189 if (empty($this->properties->id) || $this->properties->id < 1) {
2190
1d5bd3d2
DC
2191 if ($checkcapability) {
2192 if (!calendar_add_event_allowed($this->properties)) {
2193 print_error('nopermissiontoupdatecalendar');
2194 }
76d9df3f
SH
2195 }
2196
2197 if ($usingeditor) {
2198 switch ($this->properties->eventtype) {
2199 case 'user':
76d9df3f 2200 $this->properties->courseid = 0;
f19d57e5 2201 $this->properties->course = 0;
76d9df3f
SH
2202 $this->properties->groupid = 0;
2203 $this->properties->userid = $USER->id;
2204 break;
2205 case 'site':
76d9df3f 2206 $this->properties->courseid = SITEID;
f19d57e5 2207 $this->properties->course = SITEID;
76d9df3f
SH
2208 $this->properties->groupid = 0;
2209 $this->properties->userid = $USER->id;
2210 break;
2211 case 'course':
76d9df3f
SH
2212 $this->properties->groupid = 0;
2213 $this->properties->userid = $USER->id;
2214 break;
2215 case 'group':
76d9df3f
SH
2216 $this->properties->userid = $USER->id;
2217 break;
2218 default:
2219 // Ewww we should NEVER get here, but just incase we do lets
2220 // fail gracefully
2221 $usingeditor = false;
2222 break;
2223 }
2224
f19d57e5
FM
2225 // If we are actually using the editor, we recalculate the context because some default values
2226 // were set when calculate_context() was called from the constructor.
2227 if ($usingeditor) {
2228 $this->properties->context = $this->calculate_context($this->properties);
2229 $this->editorcontext = $this->properties->context;
2230 }
2231
76d9df3f
SH
2232 $editor = $this->properties->description;
2233 $this->properties->format = $this->properties->description['format'];
2234 $this->properties->description = $this->properties->description['text'];
2235 }
2236
2237 // Insert the event into the database
2238 $this->properties->id = $DB->insert_record('event', $this->properties);
2239
2240 if ($usingeditor) {
2241 $this->properties->description = file_save_draft_area_files(
2242 $editor['itemid'],
2243 $this->editorcontext->id,
64f93798
PS
2244 'calendar',
2245 'event_description',
76d9df3f
SH
2246 $this->properties->id,
2247 $this->editoroptions,
2248 $editor['text'],
2249 $this->editoroptions['forcehttps']);
76d9df3f
SH
2250 $DB->set_field('event', 'description', $this->properties->description, array('id'=>$this->properties->id));
2251 }
aa6c1ced 2252
76d9df3f 2253 // Log the event entry.
9cb5d05f
AA
2254 $eventargs['objectid'] = $this->properties->id;
2255 $eventargs['context'] = $this->properties->context;
2256 $event = \core\event\calendar_event_created::create($eventargs);
2257 $event->trigger();
76d9df3f
SH
2258
2259 $repeatedids = array();
2260
2261 if (!empty($this->properties->repeat)) {
2262 $this->properties->repeatid = $this->properties->id;
2263 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id'=>$this->properties->id));
2264
2265 $eventcopy = clone($this->properties);
2266 unset($eventcopy->id);
2267
2268 for($i = 1; $i < $eventcopy->repeats; $i++) {
2269
2270 $eventcopy->timestart = ($eventcopy->timestart+WEEKSECS) + dst_offset_on($eventcopy->timestart) - dst_offset_on($eventcopy->timestart+WEEKSECS);
2271
2272 // Get the event id for the log record.
2273 $eventcopyid = $DB->insert_record('event', $eventcopy);
2274
2275 // If the context has been set delete all associated files
2276 if ($usingeditor) {
2277 $fs = get_file_storage();
64f93798 2278 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
76d9df3f
SH
2279 foreach ($files as $file) {
2280 $fs->create_file_from_storedfile(array('itemid'=>$eventcopyid), $file);
2281 }
2282 }
2283
2284 $repeatedids[] = $eventcopyid;
9cb5d05f
AA
2285
2286 // Trigger an event.
2287 $eventargs['objectid'] = $eventcopyid;
2288 $eventargs['other']['timestart'] = $eventcopy->timestart;
2289 $event = \core\event\calendar_event_created::create($eventargs);
2290 $event->trigger();
76d9df3f
SH
2291 }
2292 }
2293
2294 // Hook for tracking added events
2295 self::calendar_event_hook('add_event', array($this->properties, $repeatedids));
2296 return true;
2297 } else {
2298
1d5bd3d2
DC
2299 if ($checkcapability) {
2300 if(!calendar_edit_event_allowed($this->properties)) {
2301 print_error('nopermissiontoupdatecalendar');
2302 }
76d9df3f
SH
2303 }
2304
2305 if ($usingeditor) {
2306 if ($this->editorcontext !== null) {
2307 $this->properties->description = file_save_draft_area_files(
2308 $this->properties->description['itemid'],
2309 $this->editorcontext->id,
64f93798
PS
2310 'calendar',
2311 'event_description',
76d9df3f
SH
2312 $this->properties->id,
2313 $this->editoroptions,
2314 $this->properties->description['text'],
2315 $this->editoroptions['forcehttps']);
2316 } else {
2317 $this->properties->format = $this->properties->description['format'];
2318 $this->properties->description = $this->properties->description['text'];
2319 }
2320 }
2321
2322 $event = $DB->get_record('event', array('id'=>$this->properties->id));
2323
2324 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
2325
2326 if ($updaterepeated) {
2327 // Update all
2328 if ($this->properties->timestart != $event->timestart) {
2329 $timestartoffset = $this->properties->timestart - $event->timestart;
2330 $sql = "UPDATE {event}
2331 SET name = ?,
2332 description = ?,
2333 timestart = timestart + ?,
2334 timeduration = ?,
2335 timemodified = ?
2336 WHERE repeatid = ?";
2337 $params = array($this->properties->name, $this->properties->description, $timestartoffset, $this->properties->timeduration, time(), $event->repeatid);
2338 } else {
2339 $sql = "UPDATE {event} SET name = ?, description = ?, timeduration = ?, timemodified = ? WHERE repeatid = ?";
2340 $params = array($this->properties->name, $this->properties->description, $this->properties->timeduration, time(), $event->repeatid);
2341 }
2342 $DB->execute($sql, $params);
2343
9cb5d05f
AA
2344 // Trigger an update event for each of the calendar event.
2345 $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', 'id,timestart');
2346 foreach ($events as $event) {
2347 $eventargs['objectid'] = $event->id;
2348 $eventargs['other']['timestart'] = $event->timestart;
2349 $event = \core\event\calendar_event_updated::create($eventargs);
2350 $event->trigger();
2351 }
76d9df3f
SH
2352 } else {
2353 $DB->update_record('event', $this->properties);
ddaff608
SH
2354 $event = calendar_event::load($this->properties->id);
2355 $this->properties = $event->properties();
9cb5d05f
AA
2356
2357 // Trigger an update event.
2358 $event = \core\event\calendar_event_updated::create($eventargs);
2359 $event->trigger();
76d9df3f
SH
2360 }
2361
2362 // Hook for tracking event updates
2363 self::calendar_event_hook('update_event', array($this->properties, $updaterepeated));
2364 return true;
2365 }
2366 }
2367
2368 /**
2369 * Deletes an event and if selected an repeated events in the same series
2370 *
2371 * This function deletes an event, any associated events if $deleterepeated=true,
2372 * and cleans up any files associated with the events.
2373 *
2374 * @see delete_event()
2375 *
08b4a4e1
RW
2376 * @param bool $deleterepeated delete event repeatedly
2377 * @return bool succession of deleting event
76d9df3f
SH
2378 */
2379 public function delete($deleterepeated=false) {
f4700b91 2380 global $DB;
76d9df3f
SH
2381
2382 // If $this->properties->id is not set then something is wrong
2383 if (empty($this->properties->id)) {
2384 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
2385 return false;
2386 }
9cb5d05f 2387 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
76d9df3f
SH
2388 // Delete the event
2389 $DB->delete_records('event', array('id'=>$this->properties->id));
2390
9cb5d05f
AA
2391 // Trigger an event for the delete action.
2392 $eventargs = array(
2393 'context' => $this->properties->context,
2394 'objectid' => $this->properties->id,
2395 'other' => array(
2396 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
2397 'timestart' => $this->properties->timestart,
2398 'name' => $this->properties->name
2399 ));
2400 $event = \core\event\calendar_event_deleted::create($eventargs);
2401 $event->add_record_snapshot('event', $calevent);
2402 $event->trigger();
2403
ff284fac
AA
2404 // If we are deleting parent of a repeated event series, promote the next event in the series as parent
2405 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
2406 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC", array($this->properties->id), IGNORE_MULTIPLE);
2407 if (!empty($newparent)) {
2408 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?", array($newparent, $this->properties->id));
5ff114ad
AA
2409 // Get all records where the repeatid is the same as the event being removed
2410 $events = $DB->get_records('event', array('repeatid' => $newparent));
9cb5d05f 2411 // For each of the returned events trigger the event_update hook and an update event.
5ff114ad 2412 foreach ($events as $event) {
9cb5d05f
AA
2413 // Trigger an event for the update.
2414 $eventargs['objectid'] = $event->id;
2415 $eventargs['other']['timestart'] = $event->timestart;
2416 $event = \core\event\calendar_event_updated::create($eventargs);
2417 $event->trigger();
2418
5ff114ad
AA
2419 self::calendar_event_hook('update_event', array($event, false));
2420 }
ff284fac
AA
2421 }
2422 }
2423
76d9df3f
SH
2424 // If the editor context hasn't already been set then set it now
2425 if ($this->editorcontext === null) {
f4700b91 2426 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2427 }
2428
2429 // If the context has been set delete all associated files
2430 if ($this->editorcontext !== null) {
2431 $fs = get_file_storage();
64f93798 2432 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
76d9df3f
SH
2433 foreach ($files as $file) {
2434 $file->delete();
2435 }
2436 }
2437
2438 // Fire the event deleted hook
2439 self::calendar_event_hook('delete_event', array($this->properties->id, $deleterepeated));
2440
2441 // If we need to delete repeated events then we will fetch them all and delete one by one
2442 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
2443 // Get all records where the repeatid is the same as the event being removed
2444 $events = $DB->get_records('event', array('repeatid'=>$this->properties->repeatid));
2445 // For each of the returned events populate a calendar_event object and call delete
2446 // make sure the arg passed is false as we are already deleting all repeats
2447 foreach ($events as $event) {
2448 $event = new calendar_event($event);
2449 $event->delete(false);
2450 }
2451 }
2452
2453 return true;
2454 }
2455
2456 /**
2457 * Fetch all event properties
2458 *
2459 * This function returns all of the events properties as an object and optionally
2460 * can prepare an editor for the description field at the same time. This is
2461 * designed to work when the properties are going to be used to set the default
2462 * values of a moodle forms form.
2463 *
2464 * @param bool $prepareeditor If set to true a editor is prepared for use with
2465 * the mforms editor element. (for description)
2466 * @return stdClass Object containing event properties
2467 */
2468 public function properties($prepareeditor=false) {
2469 global $USER, $CFG, $DB;
2470
2471 // First take a copy of the properties. We don't want to actually change the
2472 // properties or we'd forever be converting back and forwards between an
2473 // editor formatted description and not
2474 $properties = clone($this->properties);
2475 // Clean the description here
2476 $properties->description = clean_text($properties->description, $properties->format);
2477
2478 // If set to true we need to prepare the properties for use with an editor
2479 // and prepare the file area
2480 if ($prepareeditor) {
2481
2482 // We may or may not have a property id. If we do then we need to work
2483 // out the context so we can copy the existing files to the draft area
2484 if (!empty($properties->id)) {
2485
2486 if ($properties->eventtype === 'site') {
2487 // Site context
f4700b91 2488 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2489 } else if ($properties->eventtype === 'user') {
2490 // User context
f4700b91 2491 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2492 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
2493 // First check the course is valid
2494 $course = $DB->get_record('course', array('id'=>$properties->courseid));
2495 if (!$course) {
2496 print_error('invalidcourse');
2497 }
2498 // Course context
f4700b91 2499 $this->editorcontext = $this->properties->context;
76d9df3f
SH
2500 // We have a course and are within the course context so we had
2501 // better use the courses max bytes value
2502 $this->editoroptions['maxbytes'] = $course->maxbytes;
2503 } else {
2504 // If we get here we have a custom event type as used by some
2505 // modules. In this case the event will have been added by
2506 // code and we won't need the editor
2507 $this->editoroptions['maxbytes'] = 0;
2508 $this->editoroptions['maxfiles'] = 0;
2509 }
2510
2511 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
2512 $contextid = false;
2513 } else {
2514 // Get the context id that is what we really want
2515 $contextid = $this->editorcontext->id;
2516 }
2517 } else {
2518
2519 // If we get here then this is a new event in which case we don't need a
2520 // context as there is no existing files to copy to the draft area.
2521 $contextid = null;
2522 }
2523
2524 // If the contextid === false we don't support files so no preparing
2525 // a draft area
2526 if ($contextid !== false) {
2527 // Just encase it has already been submitted
2528 $draftiddescription = file_get_submitted_draft_itemid('description');
2529 // Prepare the draft area, this copies existing files to the draft area as well
64f93798 2530 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar', 'event_description', $properties->id, $this->editoroptions, $properties->description);
76d9df3f
SH
2531 } else {
2532 $draftiddescription = 0;
2533 }
aa6c1ced 2534
76d9df3f
SH
2535 // Structure the description field as the editor requires
2536 $properties->description = array('text'=>$properties->description, 'format'=>$properties->format, 'itemid'=>$draftiddescription);
2537 }
2538
2539 // Finally return the properties
2540 return $properties;
2541 }
2542
2543 /**
2544 * Toggles the visibility of an event
2545 *
2546 * @param null|bool $force If it is left null the events visibility is flipped,
2547 * If it is false the event is made hidden, if it is true it
2548 * is made visible.
08b4a4e1 2549 * @return bool if event is successfully updated, toggle will be visible
76d9df3f
SH
2550 */
2551 public function toggle_visibility($force=null) {
2552 global $CFG, $DB;
2553
2554 // Set visible to the default if it is not already set
2555 if (empty($this->properties->visible)) {
2556 $this->properties->visible = 1;
2557 }
2558
2559 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
2560 // Make this event visible
2561 $this->properties->visible = 1;
2562 // Fire the hook
2563 self::calendar_event_hook('show_event', array($this->properties));
2564 } else {
2565 // Make this event hidden
2566 $this->properties->visible = 0;
2567 // Fire the hook
2568 self::calendar_event_hook('hide_event', array($this->properties));
2569 }
2570
2571 // Update the database to reflect this change
2572 return $DB->set_field('event', 'visible', $this->properties->visible, array('id'=>$this->properties->id));
2573 }
2574
2575 /**
2576 * Attempts to call the hook for the specified action should a calendar type
2577 * by set $CFG->calendar, and the appopriate function defined
2578 *
76d9df3f
SH
2579 * @param string $action One of `update_event`, `add_event`, `delete_event`, `show_event`, `hide_event`
2580 * @param array $args The args to pass to the hook, usually the event is the first element
08b4a4e1 2581 * @return bool attempts to call event hook
76d9df3f
SH
2582 */
2583 public static function calendar_event_hook($action, array $args) {
2584 global $CFG;
2585 static $extcalendarinc;
2586 if ($extcalendarinc === null) {
d2b46849
BJ
2587 if (!empty($CFG->calendar)) {
2588 if (is_readable($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php')) {
2589 include_once($CFG->dirroot .'/calendar/'. $CFG->calendar .'/lib.php');
2590 $extcalendarinc = true;
2591 } else {
2592 debugging("Calendar lib file missing or not readable at /calendar/{$CFG->calendar}/lib.php.",
2593 DEBUG_DEVELOPER);
2594 $extcalendarinc = false;
2595 }
76d9df3f
SH
2596 } else {
2597 $extcalendarinc = false;
2598 }
2599 }
2600 if($extcalendarinc === false) {
2601 return false;
2602 }
438e4add 2603 $hook = $CFG->calendar .'_'.$action;
76d9df3f
SH
2604 if (function_exists($hook)) {
2605 call_user_func_array($hook, $args);
2606 return true;
2607 }
2608 return false;
2609 }
2610
2611 /**
2612 * Returns a calendar_event object when provided with an event id
2613 *
2614 * This function makes use of MUST_EXIST, if the event id passed in is invalid
2615 * it will result in an exception being thrown
2616 *
08b4a4e1
RW
2617 * @param int|object $param event object or event id
2618 * @return calendar_event|false status for loading calendar_event
76d9df3f 2619 */
fd699564 2620 public static function load($param) {
76d9df3f 2621 global $DB;
fd699564
SH
2622 if (is_object($param)) {
2623 $event = new calendar_event($param);
2624 } else {
2625 $event = $DB->get_record('event', array('id'=>(int)$param), '*', MUST_EXIST);
2626 $event = new calendar_event($event);
2627 }
76d9df3f
SH
2628 return $event;
2629 }
2630
2631 /**
2632 * Creates a new event and returns a calendar_event object
2633 *
0f1e1313
AA
2634 * @param stdClass|array $properties An object containing event properties
2635 * @param bool $checkcapability Check caps or not
2636 * @throws coding_exception
2637 *
2638 * @return calendar_event|bool The event object or false if it failed
76d9df3f 2639 */
0f1e1313 2640 public static function create($properties, $checkcapability = true) {
76d9df3f
SH
2641 if (is_array($properties)) {
2642 $properties = (object)$properties;
2643 }
2644 if (!is_object($properties)) {
2645 throw new coding_exception('When creating an event properties should be either an object or an assoc array');
2646 }
f4700b91 2647 $event = new calendar_event($properties);
0f1e1313 2648 if ($event->update($properties, $checkcapability)) {
76d9df3f
SH
2649 return $event;
2650 } else {
2651 return false;
2652 }
2653 }
2654}
36dc3b71
SH
2655
2656/**
2657 * Calendar information class
2658 *
2659 * This class is used simply to organise the information pertaining to a calendar
2660 * and is used primarily to make information easily available.
08b4a4e1
RW
2661 *
2662 * @package core_calendar
2663 * @category calendar
2664 * @copyright 2010 Sam Hemelryk
2665 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36dc3b71
SH
2666 */
2667class calendar_information {
08b4a4e1 2668
da304137
MN
2669 /**
2670 * @var int The timestamp
2671 *
2672 * Rather than setting the day, month and year we will set a timestamp which will be able
2673 * to be used by multiple calendars.
2674 */
2675 public $time;
36dc3b71 2676
08b4a4e1 2677 /** @var int A course id */
36dc3b71 2678 public $courseid = null;
08b4a4e1
RW
2679
2680 /** @var array An array of courses */
36dc3b71 2681 public $courses = array();
08b4a4e1
RW
2682
2683 /** @var array An array of groups */
36dc3b71 2684 public $groups = array();
08b4a4e1
RW
2685
2686 /** @var array An array of users */
36dc3b71
SH
2687 public $users = array();
2688
2689 /**
2690 * Creates a new instance
2691 *
08b4a4e1
RW
2692 * @param int $day the number of the day
2693 * @param int $month the number of the month
2694 * @param int $year the number of the year
da304137
MN
2695 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
2696 * and $calyear to support multiple calendars
36dc3b71 2697 */
da304137
MN
2698 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
2699 // If a day, month and year were passed then convert it to a timestamp. If these were passed
2700 // then we can assume the day, month and year are passed as Gregorian, as no where in core
2701 // should we be passing these values rather than the time. This is done for BC.
2702 if (!empty($day) || !empty($month) || !empty($year)) {
2703 $date = usergetdate(time());
2704 if (empty($day)) {
2705 $day = $date['mday'];
2706 }
2707 if (empty($month)) {
2708 $month = $date['mon'];
2709 }
2710 if (empty($year)) {
2711 $year = $date['year'];
2712 }
2713 if (checkdate($month, $day, $year)) {
2714 $this->time = make_timestamp($year, $month, $day);
2715 } else {
2716 $this->time = time();
2717 }
2718 } else if (!empty($time)) {
2719 $this->time = $time;
2720 } else {
2721 $this->time = time();
d8d8bdd9 2722 }
36dc3b71
SH
2723 }
2724
797cedc7 2725 /**
08b4a4e1 2726 * Initialize calendar information
797cedc7 2727 *
08b4a4e1 2728 * @param stdClass $course object
797cedc7 2729 * @param array $coursestoload An array of courses [$course->id => $course]
08b4a4e1 2730 * @param bool $ignorefilters options to use filter
797cedc7
SH
2731 */
2732 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
2733 $this->courseid = $course->id;
2734 $this->course = $course;
2735 list($courses, $group, $user) = calendar_set_filters($coursestoload, $ignorefilters);
2736 $this->courses = $courses;
2737 $this->groups = $group;
2738 $this->users = $user;
2739 }
2740
36dc3b71
SH
2741 /**
2742 * Ensures the date for the calendar is correct and either sets it to now
2743 * or throws a moodle_exception if not
2744 *
08b4a4e1
RW
2745 * @param bool $defaultonow use current time
2746 * @throws moodle_exception
2747 * @return bool validation of checkdate
36dc3b71
SH
2748 */
2749 public function checkdate($defaultonow = true) {
2750 if (!checkdate($this->month, $this->day, $this->year)) {
2751 if ($defaultonow) {
2752 $now = usergetdate(time());
2753 $this->day = intval($now['mday']);
2754 $this->month = intval($now['mon']);
2755 $this->year = intval($now['year']);
2756 return true;
2757 } else {
2758 throw new moodle_exception('invaliddate');
2759 }
2760 }
2761 return true;
2762 }
da304137 2763
36dc3b71
SH
2764 /**
2765 * Gets todays timestamp for the calendar
08b4a4e1
RW
2766 *
2767 * @return int today timestamp
36dc3b71
SH
2768 */
2769 public function timestamp_today() {
da304137 2770 return $this->time;
36dc3b71
SH
2771 }
2772 /**
2773 * Gets tomorrows timestamp for the calendar
08b4a4e1
RW
2774 *
2775 * @return int tomorrow timestamp
36dc3b71
SH
2776 */
2777 public function timestamp_tomorrow() {
da304137 2778 return $this->time + DAYSECS;
36dc3b71
SH
2779 }
2780 /**
e30390a0 2781 * Adds the pretend blocks for the calendar
36dc3b71
SH
2782 *
2783 * @param core_calendar_renderer $renderer
08b4a4e1
RW
2784 * @param bool $showfilters display filters, false is set as default
2785 * @param string|null $view preference view options (eg: day, month, upcoming)
36dc3b71
SH
2786 */
2787 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
2788 if ($showfilters) {
2789 $filters = new block_contents();
da304137 2790 $filters->content = $renderer->fake_block_filters($this->courseid, 0, 0, 0, $view, $this->courses);
36dc3b71
SH
2791 $filters->footer = '';
2792 $filters->title = get_string('eventskey', 'calendar');
2793 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
2794 }
2795 $block = new block_contents;
2796 $block->content = $renderer->fake_block_threemonths($this);
2797 $block->footer = '';
2798 $block->title = get_string('monthlyview', 'calendar');
2799 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
2800 }
1d5bd3d2 2801}
b5a52acd
JH
2802
2803/**
e30390a0
SH
2804 * Returns option list for the poll interval setting.
2805 *
2806 * @return array An array of poll interval options. Interval => description.
b5a52acd
JH
2807 */
2808function calendar_get_pollinterval_choices() {
2809 return array(
e30390a0 2810 '0' => new lang_string('never', 'calendar'),
0f1e1313
AA
2811 HOURSECS => new lang_string('hourly', 'calendar'),
2812 DAYSECS => new lang_string('daily', 'calendar'),
2813 WEEKSECS => new lang_string('weekly', 'calendar'),
e30390a0 2814 '2628000' => new lang_string('monthly', 'calendar'),
0f1e1313 2815 YEARSECS => new lang_string('annually', 'calendar')
e30390a0 2816 );
b5a52acd
JH
2817}
2818
2819/**
e30390a0
SH
2820 * Returns option list of available options for the calendar event type, given the current user and course.
2821 *
4c349ad7 2822 * @param int $courseid The id of the course
e30390a0 2823 * @return array An array containing the event types the user can create.
b5a52acd
JH
2824 */
2825function calendar_get_eventtype_choices($courseid) {
2826 $choices = array();
2827 $allowed = new stdClass;
2828 calendar_get_allowed_types($allowed, $courseid);
2829
2830 if ($allowed->user) {
35ad5fc6 2831 $choices['user'] = get_string('userevents', 'calendar');
b5a52acd
JH
2832 }
2833 if ($allowed->site) {
6bf410ed 2834 $choices['site'] = get_string('siteevents', 'calendar');
b5a52acd
JH
2835 }
2836 if (!empty($allowed->courses)) {
35ad5fc6 2837 $choices['course'] = get_string('courseevents', 'calendar');
b5a52acd
JH
2838 }
2839 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2840 $choices['group'] = get_string('group');
2841 }
2842
2843 return array($choices, $allowed->groups);
2844}
2845
b5a52acd
JH
2846/**
2847 * Add an iCalendar subscription to the database.
e30390a0
SH
2848 *
2849 * @param stdClass $sub The subscription object (e.g. from the form)
2850 * @return int The insert ID, if any.
b5a52acd
JH
2851 */
2852function calendar_add_subscription($sub) {
35ad5fc6 2853 global $DB, $USER, $SITE;
e30390a0 2854
35ad5fc6
AA
2855 if ($sub->eventtype === 'site') {
2856 $sub->courseid = $SITE->id;
2857 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
b5a52acd 2858 $sub->courseid = $sub->course;
35ad5fc6
AA
2859 } else {
2860 // User events.
2861 $sub->courseid = 0;
b5a52acd
JH
2862 }
2863 $sub->userid = $USER->id;
2864
e30390a0 2865 // File subscriptions never update.
b5a52acd
JH
2866 if (empty($sub->url)) {
2867 $sub->pollinterval = 0;
2868 }
2869
2870 if (!empty($sub->name)) {
2871 if (empty($sub->id)) {
2872 $id = $DB->insert_record('event_subscriptions', $sub);
e73b527c 2873 // we cannot cache the data here because $sub is not complete.
b5a52acd
JH
2874 return $id;
2875 } else {
e73b527c 2876 // Why are we doing an update here?
ab37339d 2877 calendar_update_subscription($sub);
b5a52acd
JH
2878 return $sub->id;
2879 }
2880 } else {
2881 print_error('errorbadsubscription', 'importcalendar');
2882 }
2883}
2884
2885/**
2886 * Add an iCalendar event to the Moodle calendar.
e30390a0 2887 *
0f1e1313 2888 * @param stdClass $event The RFC-2445 iCalendar event
e30390a0
SH
2889 * @param int $courseid The course ID
2890 * @param int $subscriptionid The iCalendar subscription ID
accc3ced 2891 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
e73b527c 2892 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
0f1e1313 2893 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
b5a52acd 2894 */
accc3ced 2895function calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone='UTC') {
0f1e1313 2896 global $DB;
b5a52acd 2897
e30390a0 2898 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
b5a52acd
JH
2899 if (empty($event->properties['SUMMARY'])) {
2900 return 0;
2901 }
2902
2903 $name = $event->properties['SUMMARY'][0]->value;
2904 $name = str_replace('\n', '<br />', $name);
2905 $name = str_replace('\\', '', $name);
2906 $name = preg_replace('/\s+/', ' ', $name);
e30390a0
SH
2907
2908 $eventrecord = new stdClass;
4c349ad7 2909 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
b5a52acd
JH
2910
2911 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2912 $description = '';
2913 } else {
2914 $description = $event->properties['DESCRIPTION'][0]->value;
2915 $description = str_replace('\n', '<br />', $description);
2916 $description = str_replace('\\', '', $description);
2917 $description = preg_replace('/\s+/', ' ', $description);
2918 }
4c349ad7 2919 $eventrecord->description = clean_param($description, PARAM_NOTAGS);
b5a52acd 2920
e30390a0 2921 // Probably a repeating event with RRULE etc. TODO: skip for now.
b5a52acd
JH
2922 if (empty($event->properties['DTSTART'][0]->value)) {
2923 return 0;
2924 }
2925
0f1e1313
AA
2926 $defaulttz = date_default_timezone_get();
2927 $tz = isset($event->properties['DTSTART'][0]->parameters['TZID']) ? $event->properties['DTSTART'][0]->parameters['TZID'] :
accc3ced 2928 $timezone;
0f1e1313 2929 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
b5a52acd
JH
2930 if (empty($event->properties['DTEND'])) {
2931 $eventrecord->timeduration = 3600; // one hour if no end time specified
2932 } else {
0f1e1313 2933 $endtz = isset($event->properties['DTEND'][0]->parameters['TZID']) ? $event->properties['DTEND'][0]->parameters['TZID'] :
accc3ced 2934 $timezone;
0f1e1313 2935 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
b5a52acd 2936 }
accc3ced
SB
2937
2938 // Check to see if it should be treated as an all day event.
2939 if ($eventrecord->timeduration == DAYSECS) {
2940 // Check to see if the event started at Midnight on the imported calendar.
2941 date_default_timezone_set($timezone);
2942 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
2943 // This event should be an all day event.
2944 $eventrecord->timeduration = 0;
2945 }
2946 date_default_timezone_set($defaulttz);
2947 }
2948
b5a52acd
JH
2949 $eventrecord->uuid = $event->properties['UID'][0]->value;
2950 $eventrecord->timemodified = time();
2951
e30390a0 2952 // Add the iCal subscription details if required.
e73b527c
AA
2953 // We should never do anything with an event without a subscription reference.
2954 $sub = calendar_get_subscription($subscriptionid);
2955 $eventrecord->subscriptionid = $subscriptionid;
2956 $eventrecord->userid = $sub->userid;
2957 $eventrecord->groupid = $sub->groupid;
2958 $eventrecord->courseid = $sub->courseid;
2959 $eventrecord->eventtype = $sub->eventtype;
b5a52acd
JH
2960
2961 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid))) {
2962 $eventrecord->id = $updaterecord->id;
0f1e1313 2963 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
b5a52acd 2964 } else {
0f1e1313
AA
2965 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
2966 }
2967 if ($createdevent = calendar_event::create($eventrecord, false)) {
2968 if (!empty($event->properties['RRULE'])) {
2969 // Repeating events.
2970 date_default_timezone_set($tz); // Change time zone to parse all events.
2971 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
2972 $rrule->parse_rrule();
2973 $rrule->create_events($createdevent);
2974 date_default_timezone_set($defaulttz); // Change time zone back to what it was.
2975 }
2976 return $return;
2977 } else {
2978 return 0;
b5a52acd
JH
2979 }
2980}
2981
2982/**
e30390a0
SH
2983 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2984 *
2985 * @param int $subscriptionid The ID of the subscription we are acting upon.
2986 * @param int $pollinterval The poll interval to use.
2987 * @param int $action The action to be performed. One of update or remove.
e73b527c 2988 * @throws dml_exception if invalid subscriptionid is provided
e30390a0 2989 * @return string A log of the import progress, including errors
b5a52acd 2990 */
e30390a0 2991function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
b5a52acd 2992
e30390a0 2993 // Fetch the subscription from the database making sure it exists.
e73b527c 2994 $sub = calendar_get_subscription($subscriptionid);
b5a52acd 2995
e30390a0 2996 // Update or remove the subscription, based on action.
b5a52acd 2997 switch ($action) {
ee74a2a1 2998 case CALENDAR_SUBSCRIPTION_UPDATE:
e30390a0
SH
2999 // Skip updating file subscriptions.
3000 if (empty($sub->url)) {
3001 break;
3002 }
3003 $sub->pollinterval = $pollinterval;
ab37339d 3004 calendar_update_subscription($sub);
e73b527c 3005
e30390a0
SH
3006 // Update the events.
3007 return "<p>".get_string('subscriptionupdated', 'calendar', $sub->name)."</p>" . calendar_update_subscription_events($subscriptionid);
b5a52acd 3008
ee74a2a1 3009 case CALENDAR_SUBSCRIPTION_REMOVE:
f40c37d0 3010 calendar_delete_subscription($subscriptionid);
e30390a0
SH
3011 return get_string('subscriptionremoved', 'calendar', $sub->name);
3012 break;
b5a52acd 3013
e30390a0
SH
3014 default:
3015 break;
b5a52acd
JH
3016 }
3017 return '';
3018}
3019
f40c37d0
RT
3020/**
3021 * Delete subscription and all related events.
3022 *
3023 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
3024 */
3025function calendar_delete_subscription($subscription) {
3026 global $DB;
3027
3028 if (is_object($subscription)) {
3029 $subscription = $subscription->id;
3030 }
3031 // Delete subscription and related events.
3032 $DB->delete_records('event', array('subscriptionid' => $subscription));
3033 $DB->delete_records('event_subscriptions', array('id' => $subscription));
36546841 3034 cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription));
f40c37d0 3035}
b5a52acd
JH
3036/**
3037 * From a URL, fetch the calendar and return an iCalendar object.
e30390a0
SH
3038 *
3039 * @param string $url The iCalendar URL
3040 * @return stdClass The iCalendar object
b5a52acd
JH
3041 */
3042function calendar_get_icalendar($url) {
e30390a0
SH
3043 global $CFG;
3044
3045 require_once($CFG->libdir.'/filelib.php');
3046
3047 $curl = new curl();
20bdf997 3048 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
e30390a0 3049 $calendar = $curl->get($url);
20bdf997
AA
3050 // Http code validation should actually be the job of curl class.
3051 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
e30390a0
SH
3052 throw new moodle_exception('errorinvalidicalurl', 'calendar');
3053 }
3054
b5a52acd
JH
3055 $ical = new iCalendar();
3056 $ical->unserialize($calendar);
3057 return $ical;
3058}
3059
3060/**
3061 * Import events from an iCalendar object into a course calendar.
e30390a0
SH
3062 *
3063 * @param stdClass $ical The iCalendar object.
3064 * @param int $courseid The course ID for the calendar.
3065 * @param int $subscriptionid The subscription ID.
3066 * @return string A log of the import progress, including errors.
b5a52acd 3067 */
e30390a0 3068function calendar_import_icalendar_events($ical, $courseid, $subscriptionid = null) {
b5a52acd
JH
3069 global $DB;
3070 $return = '';
3071 $eventcount = 0;
3072 $updatecount = 0;
3073
e30390a0 3074 // Large calendars take a while...
3ef7279f 3075 core_php_time_limit::raise(300);
b5a52acd 3076
e30390a0 3077 // Mark all events in a subscription with a zero timestamp.
b5a52acd 3078 if (!empty($subscriptionid)) {
e30390a0 3079 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
b5a52acd
JH
3080 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3081 }
accc3ced
SB
3082 // Grab the timezone from the iCalendar file to be used later.
3083 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3084 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3085 } else {
3086 $timezone = 'UTC';
3087 }
4c349ad7 3088 foreach ($ical->components['VEVENT'] as $event) {
accc3ced 3089 $res = calendar_add_icalendar_event($event, $courseid, $subscriptionid, $timezone);
b5a52acd
JH
3090 switch ($res) {
3091 case CALENDAR_IMPORT_EVENT_UPDATED:
3092 $updatecount++;
3093 break;
3094 case CALENDAR_IMPORT_EVENT_INSERTED:
3095 $eventcount++;
3096 break;
3097 case 0:
4c349ad7 3098 $return .= '<p>'.get_string('erroraddingevent', 'calendar').': '.(empty($event->properties['SUMMARY'])?'('.get_string('notitle', 'calendar').')':$event->properties['SUMMARY'][0]->value)." </p>\n";
b5a52acd
JH
3099 break;
3100 }
3101 }
e30390a0
SH
3102 $return .= "<p> ".get_string('eventsimported', 'calendar', $eventcount)."</p>";
3103 $return .= "<p> ".get_string('eventsupdated', 'calendar', $updatecount)."</p>";
b5a52acd 3104
e30390a0 3105 // Delete remaining zero-marked events since they're not in remote calendar.
b5a52acd
JH
3106 if (!empty($subscriptionid)) {
3107 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3108 if (!empty($deletecount)) {
e30390a0 3109 $sql = "DELETE FROM {event} WHERE timemodified = :time AND subscriptionid = :id";
b5a52acd 3110 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
4c349ad7 3111 $return .= "<p> ".get_string('eventsdeleted', 'calendar').": {$deletecount} </p>\n";
b5a52acd
JH
3112 }
3113 }
3114
3115 return $return;
3116}
3117
3118/**
3119 * Fetch a calendar subscription and update the events in the calendar.
e30390a0
SH
3120 *
3121 * @param int $subscriptionid The course ID for the calendar.
3122 * @return string A log of the import progress, including errors.
b5a52acd
JH
3123 */
3124function calendar_update_subscription_events($subscriptionid) {
3125 global $DB;
b5a52acd 3126
e73b527c 3127 $sub = calendar_get_subscription($subscriptionid);
e30390a0 3128 // Don't update a file subscription. TODO: Update from a new uploaded file.
b5a52acd
JH
3129 if (empty($sub->url)) {
3130 return 'File subscription not updated.';
3131 }
3132 $ical = calendar_get_icalendar($sub->url);
3133 $return = calendar_import_icalendar_events($ical, $sub->courseid, $subscriptionid);
3134 $sub->lastupdated = time();
ab37339d 3135 calendar_update_subscription($sub);
b5a52acd
JH
3136 return $return;
3137}
3138
1f7981e0
AA
3139/**
3140 * Update a calendar subscription. Also updates the associated cache.
3141 *
3142 * @param stdClass|array $subscription Subscription record.
3143 * @throws coding_exception If something goes wrong
3144 * @since Moodle 2.5
3145 */
3146function calendar_update_subscription($subscription) {
3147 global $DB;
3148
3149 if (is_array($subscription)) {
3150 $subscription = (object)$subscription;
3151 }
3152 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3153 throw new coding_exception('Cannot update a subscription without a valid id');
3154 }
3155
3156 $DB->update_record('event_subscriptions', $subscription);
3157 // Update cache.
3158 $cache = cache::make('core', 'calendar_subscriptions');
3159 $cache->set($subscription->id, $subscription);
3160}
3161
7a216229
AA
3162/**
3163 * Checks to see if the user can edit a given subscription feed.
3164 *
3165 * @param mixed $subscriptionorid Subscription object or id
3166 * @return bool true if current user can edit the subscription else false
3167 */
3168function calendar_can_edit_subscription($subscriptionorid) {
3169 global $DB;
3170
3171 if (is_array($subscriptionorid)) {
3172 $subscription = (object)$subscriptionorid;
3173 } else if (is_object($subscriptionorid)) {
3174 $subscription = $subscriptionorid;
3175 } else {
e73b527c 3176 $subscription = calendar_get_subscription($subscriptionorid);
7a216229
AA
3177 }
3178 $allowed = new stdClass;
3179 $courseid = $subscription->courseid;
3180 $groupid = $subscription->groupid;
3181 calendar_get_allowed_types($allowed, $courseid);
3182 switch ($subscription->eventtype) {
3183 case 'user':
3184 return $allowed->user;
3185 case 'course':
3186 if (isset($allowed->courses[$courseid])) {
3187 return $allowed->courses[$courseid];
3188 } else {
3189 return false;
3190 }
3191 case 'site':
3192 return $allowed->site;
3193 case 'group':
3194 if (isset($allowed->groups[$groupid])) {
3195 return $allowed->groups[$groupid];
3196 } else {
3197 return false;
3198 }
3199 default:
3200 return false;
3201 }
3202}
3203
b5a52acd
JH
3204/**
3205 * Update calendar subscriptions.
e30390a0
SH
3206 *
3207 * @return bool
b5a52acd
JH
3208 */
3209function calendar_cron() {
e30390a0
SH
3210 global $CFG, $DB;
3211
3212 // In order to execute this we need bennu.
3213 require_once($CFG->libdir.'/bennu/bennu.inc.php');
3214
24a3115c 3215 mtrace('Updating calendar subscriptions:');
658b9372 3216 cron_trace_time_and_memory();
e30390a0 3217
b5a52acd 3218 $time = time();
e30390a0 3219 $subscriptions = $DB->get_records_sql('SELECT * FROM {event_subscriptions} WHERE pollinterval > 0 AND lastupdated + pollinterval < ?', array($time));
4c349ad7 3220 foreach ($subscriptions as $sub) {
24a3115c 3221 mtrace("Updating calendar subscription {$sub->name} in course {$sub->courseid}");
e30390a0
SH
3222 try {
3223 $log = calendar_update_subscription_events($sub->id);
b8ad1728 3224 mtrace(trim(strip_tags($log)));
e30390a0 3225 } catch (moodle_exception $ex) {
b8ad1728 3226 mtrace('Error updating calendar subscription: ' . $ex->getMessage());
e30390a0 3227 }
b5a52acd 3228 }
e30390a0 3229
24a3115c 3230 mtrace('Finished updating calendar subscriptions.');
b5a52acd 3231
e30390a0 3232 return true;
24a3115c 3233}