MDL-58768 Calendar: Added user param to calendar_set_filters
[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
7d0a866c
AN
30require_once($CFG->libdir . '/coursecatlib.php');
31
08b4a4e1
RW
32/**
33 * These are read by the administration component to provide default values
34 */
35
36/**
37 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
38 */
bb4a2e85 39define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
08b4a4e1
RW
40
41/**
42 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
43 */
bb4a2e85 44define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
08b4a4e1
RW
45
46/**
47 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
48 */
49define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);
50
bb4a2e85 51// This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
52// Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
08b4a4e1
RW
53
54/**
55 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
56 */
57define('CALENDAR_DEFAULT_WEEKEND', 65);
58
59/**
60 * CALENDAR_URL - path to calendar's folder
61 */
76d9df3f 62define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
08b4a4e1
RW
63
64/**
65 * CALENDAR_TF_24 - Calendar time in 24 hours format
66 */
76d9df3f 67define('CALENDAR_TF_24', '%H:%M');
08b4a4e1
RW
68
69/**
70 * CALENDAR_TF_12 - Calendar time in 12 hours format
71 */
76d9df3f 72define('CALENDAR_TF_12', '%I:%M %p');
bb4a2e85 73
08b4a4e1
RW
74/**
75 * CALENDAR_EVENT_GLOBAL - Global calendar event types
76 */
797cedc7 77define('CALENDAR_EVENT_GLOBAL', 1);
08b4a4e1
RW
78
79/**
80 * CALENDAR_EVENT_COURSE - Course calendar event types
81 */
797cedc7 82define('CALENDAR_EVENT_COURSE', 2);
08b4a4e1
RW
83
84/**
85 * CALENDAR_EVENT_GROUP - group calendar event types
86 */
797cedc7 87define('CALENDAR_EVENT_GROUP', 4);
08b4a4e1
RW
88
89/**
90 * CALENDAR_EVENT_USER - user calendar event types
91 */
797cedc7
SH
92define('CALENDAR_EVENT_USER', 8);
93
05f184bb
AN
94/**
95 * CALENDAR_EVENT_COURSECAT - Course category calendar event types
96 */
97define('CALENDAR_EVENT_COURSECAT', 16);
7423f116 98
b5a52acd
JH
99/**
100 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
101 */
102define('CALENDAR_IMPORT_FROM_FILE', 0);
103
104/**
105 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
106 */
107define('CALENDAR_IMPORT_FROM_URL', 1);
108
109/**
110 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
111 */
112define('CALENDAR_IMPORT_EVENT_UPDATED', 1);
113
114/**
115 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
116 */
117define('CALENDAR_IMPORT_EVENT_INSERTED', 2);
118
ee74a2a1
AA
119/**
120 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
121 */
122define('CALENDAR_SUBSCRIPTION_UPDATE', 1);
123
124/**
125 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
126 */
127define('CALENDAR_SUBSCRIPTION_REMOVE', 2);
128
ca75ec4f
JP
129/**
130 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
131 */
a776415d 132define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
ca75ec4f 133
5ca71c2d
CB
134/**
135 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
136 */
137define('CALENDAR_EVENT_TYPE_STANDARD', 0);
138
139/**
140 * CALENDAR_EVENT_TYPE_ACTION - Action events.
141 */
142define('CALENDAR_EVENT_TYPE_ACTION', 1);
143
e1cd93ce
MN
144/**
145 * Manage calendar events.
146 *
147 * This class provides the required functionality in order to manage calendar events.
148 * It was introduced as part of Moodle 2.0 and was created in order to provide a
149 * better framework for dealing with calendar events in particular regard to file
150 * handling through the new file API.
151 *
152 * @package core_calendar
153 * @category calendar
154 * @copyright 2009 Sam Hemelryk
155 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
156 *
157 * @property int $id The id within the event table
158 * @property string $name The name of the event
159 * @property string $description The description of the event
160 * @property int $format The format of the description FORMAT_?
161 * @property int $courseid The course the event is associated with (0 if none)
162 * @property int $groupid The group the event is associated with (0 if none)
163 * @property int $userid The user the event is associated with (0 if none)
164 * @property int $repeatid If this is a repeated event this will be set to the
165 * id of the original
166 * @property string $modulename If added by a module this will be the module name
167 * @property int $instance If added by a module this will be the module instance
168 * @property string $eventtype The event type
169 * @property int $timestart The start time as a timestamp
170 * @property int $timeduration The duration of the event in seconds
171 * @property int $visible 1 if the event is visible
172 * @property int $uuid ?
173 * @property int $sequence ?
174 * @property int $timemodified The time last modified as a timestamp
175 */
176class calendar_event {
177
178 /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
179 protected $properties = null;
180
181 /** @var string The converted event discription with file paths resolved.
182 * This gets populated when someone requests description for the first time */
183 protected $_description = null;
184
185 /** @var array The options to use with this description editor */
186 protected $editoroptions = array(
187 'subdirs' => false,
188 'forcehttps' => false,
189 'maxfiles' => -1,
190 'maxbytes' => null,
191 'trusttext' => false);
192
193 /** @var object The context to use with the description editor */
194 protected $editorcontext = null;
195
196 /**
197 * Instantiates a new event and optionally populates its properties with the data provided.
198 *
199 * @param \stdClass $data Optional. An object containing the properties to for
200 * an event
201 */
202 public function __construct($data = null) {
203 global $CFG, $USER;
204
205 // First convert to object if it is not already (should either be object or assoc array).
206 if (!is_object($data)) {
207 $data = (object) $data;
208 }
209
210 $this->editoroptions['maxbytes'] = $CFG->maxbytes;
211
212 $data->eventrepeats = 0;
213
214 if (empty($data->id)) {
215 $data->id = null;
216 }
217
218 if (!empty($data->subscriptionid)) {
23a29de7 219 $data->subscription = calendar_get_subscription($data->subscriptionid);
e1cd93ce
MN
220 }
221
222 // Default to a user event.
223 if (empty($data->eventtype)) {
224 $data->eventtype = 'user';
225 }
226
227 // Default to the current user.
228 if (empty($data->userid)) {
229 $data->userid = $USER->id;
230 }
231
232 if (!empty($data->timeduration) && is_array($data->timeduration)) {
233 $data->timeduration = make_timestamp(
234 $data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'],
235 $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
236 }
237
238 if (!empty($data->description) && is_array($data->description)) {
239 $data->format = $data->description['format'];
240 $data->description = $data->description['text'];
241 } else if (empty($data->description)) {
242 $data->description = '';
243 $data->format = editors_get_preferred_format();
244 }
245
246 // Ensure form is defaulted correctly.
247 if (empty($data->format)) {
248 $data->format = editors_get_preferred_format();
249 }
250
251 $this->properties = $data;
e1cd93ce
MN
252 }
253
254 /**
255 * Magic set method.
256 *
257 * Attempts to call a set_$key method if one exists otherwise falls back
258 * to simply set the property.
259 *
260 * @param string $key property name
261 * @param mixed $value value of the property
262 */
263 public function __set($key, $value) {
264 if (method_exists($this, 'set_'.$key)) {
265 $this->{'set_'.$key}($value);
266 }
267 $this->properties->{$key} = $value;
268 }
269
270 /**
271 * Magic get method.
272 *
273 * Attempts to call a get_$key method to return the property and ralls over
274 * to return the raw property.
275 *
276 * @param string $key property name
277 * @return mixed property value
278 * @throws \coding_exception
279 */
280 public function __get($key) {
281 if (method_exists($this, 'get_'.$key)) {
282 return $this->{'get_'.$key}();
283 }
2a8e41b9 284 if (!property_exists($this->properties, $key)) {
e1cd93ce
MN
285 throw new \coding_exception('Undefined property requested');
286 }
287 return $this->properties->{$key};
288 }
289
290 /**
291 * Magic isset method.
292 *
293 * PHP needs an isset magic method if you use the get magic method and
294 * still want empty calls to work.
295 *
296 * @param string $key $key property name
297 * @return bool|mixed property value, false if property is not exist
298 */
299 public function __isset($key) {
300 return !empty($this->properties->{$key});
301 }
302
303 /**
304 * Calculate the context value needed for an event.
305 *
306 * Event's type can be determine by the available value store in $data
307 * It is important to check for the existence of course/courseid to determine
308 * the course event.
309 * Default value is set to CONTEXT_USER
310 *
311 * @return \stdClass The context object.
312 */
313 protected function calculate_context() {
314 global $USER, $DB;
315
316 $context = null;
303d649a
AN
317 if (isset($this->properties->categoryid) && $this->properties->categoryid > 0) {
318 $context = \context_coursecat::instance($this->properties->categoryid);
319 } else if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
e1cd93ce
MN
320 $context = \context_course::instance($this->properties->courseid);
321 } else if (isset($this->properties->course) && $this->properties->course > 0) {
322 $context = \context_course::instance($this->properties->course);
323 } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
324 $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
325 $context = \context_course::instance($group->courseid);
326 } else if (isset($this->properties->userid) && $this->properties->userid > 0
327 && $this->properties->userid == $USER->id) {
328 $context = \context_user::instance($this->properties->userid);
329 } else if (isset($this->properties->userid) && $this->properties->userid > 0
330 && $this->properties->userid != $USER->id &&
331 isset($this->properties->instance) && $this->properties->instance > 0) {
332 $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
333 false, MUST_EXIST);
334 $context = \context_course::instance($cm->course);
335 } else {
336 $context = \context_user::instance($this->properties->userid);
337 }
338
339 return $context;
340 }
341
08a79155
RW
342 /**
343 * Returns the context for this event. The context is calculated
344 * the first time is is requested and then stored in a member
345 * variable to be returned each subsequent time.
346 *
347 * This is a magical getter function that will be called when
348 * ever the context property is accessed, e.g. $event->context.
349 *
350 * @return context
351 */
352 protected function get_context() {
353 if (!isset($this->properties->context)) {
354 $this->properties->context = $this->calculate_context();
355 }
356
357 return $this->properties->context;
358 }
359
e1cd93ce
MN
360 /**
361 * Returns an array of editoroptions for this event.
362 *
363 * @return array event editor options
364 */
365 protected function get_editoroptions() {
366 return $this->editoroptions;
367 }
368
369 /**
370 * Returns an event description: Called by __get
371 * Please use $blah = $event->description;
372 *
373 * @return string event description
374 */
375 protected function get_description() {
376 global $CFG;
377
378 require_once($CFG->libdir . '/filelib.php');
379
380 if ($this->_description === null) {
381 // Check if we have already resolved the context for this event.
382 if ($this->editorcontext === null) {
383 // Switch on the event type to decide upon the appropriate context to use for this event.
08a79155 384 $this->editorcontext = $this->get_context();
05f184bb 385 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
e1cd93ce
MN
386 return clean_text($this->properties->description, $this->properties->format);
387 }
388 }
389
390 // Work out the item id for the editor, if this is a repeated event
391 // then the files will be associated with the original.
392 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
393 $itemid = $this->properties->repeatid;
394 } else {
395 $itemid = $this->properties->id;
396 }
397
398 // Convert file paths in the description so that things display correctly.
399 $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
400 $this->editorcontext->id, 'calendar', 'event_description', $itemid);
401 // Clean the text so no nasties get through.
402 $this->_description = clean_text($this->_description, $this->properties->format);
403 }
404
405 // Finally return the description.
406 return $this->_description;
407 }
408
409 /**
410 * Return the number of repeat events there are in this events series.
411 *
412 * @return int number of event repeated
413 */
414 public function count_repeats() {
415 global $DB;
416 if (!empty($this->properties->repeatid)) {
417 $this->properties->eventrepeats = $DB->count_records('event',
418 array('repeatid' => $this->properties->repeatid));
419 // We don't want to count ourselves.
420 $this->properties->eventrepeats--;
421 }
422 return $this->properties->eventrepeats;
423 }
424
425 /**
426 * Update or create an event within the database
427 *
428 * Pass in a object containing the event properties and this function will
429 * insert it into the database and deal with any associated files
430 *
431 * @see self::create()
432 * @see self::update()
433 *
434 * @param \stdClass $data object of event
435 * @param bool $checkcapability if moodle should check calendar managing capability or not
436 * @return bool event updated
437 */
438 public function update($data, $checkcapability=true) {
439 global $DB, $USER;
440
441 foreach ($data as $key => $value) {
442 $this->properties->$key = $value;
443 }
444
445 $this->properties->timemodified = time();
446 $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));
447
448 // Prepare event data.
449 $eventargs = array(
08a79155 450 'context' => $this->get_context(),
e1cd93ce
MN
451 'objectid' => $this->properties->id,
452 'other' => array(
453 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
454 'timestart' => $this->properties->timestart,
455 'name' => $this->properties->name
456 )
457 );
458
459 if (empty($this->properties->id) || $this->properties->id < 1) {
e1cd93ce 460 if ($checkcapability) {
23a29de7 461 if (!calendar_add_event_allowed($this->properties)) {
e1cd93ce
MN
462 print_error('nopermissiontoupdatecalendar');
463 }
464 }
465
466 if ($usingeditor) {
467 switch ($this->properties->eventtype) {
468 case 'user':
469 $this->properties->courseid = 0;
470 $this->properties->course = 0;
471 $this->properties->groupid = 0;
472 $this->properties->userid = $USER->id;
473 break;
474 case 'site':
475 $this->properties->courseid = SITEID;
476 $this->properties->course = SITEID;
477 $this->properties->groupid = 0;
478 $this->properties->userid = $USER->id;
479 break;
480 case 'course':
481 $this->properties->groupid = 0;
482 $this->properties->userid = $USER->id;
483 break;
05f184bb
AN
484 case 'category':
485 $this->properties->groupid = 0;
486 $this->properties->category = 0;
487 $this->properties->userid = $USER->id;
488 break;
e1cd93ce
MN
489 case 'group':
490 $this->properties->userid = $USER->id;
491 break;
492 default:
493 // We should NEVER get here, but just incase we do lets fail gracefully.
494 $usingeditor = false;
495 break;
496 }
497
498 // If we are actually using the editor, we recalculate the context because some default values
499 // were set when calculate_context() was called from the constructor.
500 if ($usingeditor) {
501 $this->properties->context = $this->calculate_context();
08a79155 502 $this->editorcontext = $this->get_context();
e1cd93ce
MN
503 }
504
505 $editor = $this->properties->description;
506 $this->properties->format = $this->properties->description['format'];
507 $this->properties->description = $this->properties->description['text'];
508 }
509
510 // Insert the event into the database.
511 $this->properties->id = $DB->insert_record('event', $this->properties);
512
513 if ($usingeditor) {
514 $this->properties->description = file_save_draft_area_files(
515 $editor['itemid'],
516 $this->editorcontext->id,
517 'calendar',
518 'event_description',
519 $this->properties->id,
520 $this->editoroptions,
521 $editor['text'],
522 $this->editoroptions['forcehttps']);
523 $DB->set_field('event', 'description', $this->properties->description,
524 array('id' => $this->properties->id));
525 }
526
527 // Log the event entry.
528 $eventargs['objectid'] = $this->properties->id;
08a79155 529 $eventargs['context'] = $this->get_context();
e1cd93ce
MN
530 $event = \core\event\calendar_event_created::create($eventargs);
531 $event->trigger();
532
533 $repeatedids = array();
534
535 if (!empty($this->properties->repeat)) {
536 $this->properties->repeatid = $this->properties->id;
537 $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));
538
539 $eventcopy = clone($this->properties);
540 unset($eventcopy->id);
541
542 $timestart = new \DateTime('@' . $eventcopy->timestart);
543 $timestart->setTimezone(\core_date::get_user_timezone_object());
544
545 for ($i = 1; $i < $eventcopy->repeats; $i++) {
546
547 $timestart->add(new \DateInterval('P7D'));
548 $eventcopy->timestart = $timestart->getTimestamp();
549
550 // Get the event id for the log record.
551 $eventcopyid = $DB->insert_record('event', $eventcopy);
552
553 // If the context has been set delete all associated files.
554 if ($usingeditor) {
555 $fs = get_file_storage();
556 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
557 $this->properties->id);
558 foreach ($files as $file) {
559 $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
560 }
561 }
562
563 $repeatedids[] = $eventcopyid;
564
565 // Trigger an event.
566 $eventargs['objectid'] = $eventcopyid;
567 $eventargs['other']['timestart'] = $eventcopy->timestart;
568 $event = \core\event\calendar_event_created::create($eventargs);
569 $event->trigger();
570 }
571 }
572
573 return true;
574 } else {
575
576 if ($checkcapability) {
23a29de7 577 if (!calendar_edit_event_allowed($this->properties)) {
e1cd93ce
MN
578 print_error('nopermissiontoupdatecalendar');
579 }
580 }
581
582 if ($usingeditor) {
583 if ($this->editorcontext !== null) {
584 $this->properties->description = file_save_draft_area_files(
585 $this->properties->description['itemid'],
586 $this->editorcontext->id,
587 'calendar',
588 'event_description',
589 $this->properties->id,
590 $this->editoroptions,
591 $this->properties->description['text'],
592 $this->editoroptions['forcehttps']);
593 } else {
594 $this->properties->format = $this->properties->description['format'];
595 $this->properties->description = $this->properties->description['text'];
596 }
597 }
598
599 $event = $DB->get_record('event', array('id' => $this->properties->id));
600
601 $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));
602
603 if ($updaterepeated) {
604 // Update all.
605 if ($this->properties->timestart != $event->timestart) {
606 $timestartoffset = $this->properties->timestart - $event->timestart;
607 $sql = "UPDATE {event}
608 SET name = ?,
609 description = ?,
610 timestart = timestart + ?,
611 timeduration = ?,
6428642a
SL
612 timemodified = ?,
613 groupid = ?,
614 courseid = ?
e1cd93ce 615 WHERE repeatid = ?";
19fa690c
JD
616 // Note: Group and course id may not be set. If not, keep their current values.
617 $params = [
618 $this->properties->name,
619 $this->properties->description,
620 $timestartoffset,
621 $this->properties->timeduration,
622 time(),
623 isset($this->properties->groupid) ? $this->properties->groupid : $event->groupid,
624 isset($this->properties->courseid) ? $this->properties->courseid : $event->courseid,
625 $event->repeatid
626 ];
e1cd93ce 627 } else {
6428642a
SL
628 $sql = "UPDATE {event}
629 SET name = ?,
630 description = ?,
631 timeduration = ?,
632 timemodified = ?,
633 groupid = ?,
634 courseid = ?
635 WHERE repeatid = ?";
19fa690c
JD
636 // Note: Group and course id may not be set. If not, keep their current values.
637 $params = [
638 $this->properties->name,
639 $this->properties->description,
640 $this->properties->timeduration,
641 time(),
642 isset($this->properties->groupid) ? $this->properties->groupid : $event->groupid,
643 isset($this->properties->courseid) ? $this->properties->courseid : $event->courseid,
644 $event->repeatid
645 ];
e1cd93ce
MN
646 }
647 $DB->execute($sql, $params);
648
649 // Trigger an update event for each of the calendar event.
650 $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', '*');
651 foreach ($events as $calendarevent) {
652 $eventargs['objectid'] = $calendarevent->id;
653 $eventargs['other']['timestart'] = $calendarevent->timestart;
654 $event = \core\event\calendar_event_updated::create($eventargs);
655 $event->add_record_snapshot('event', $calendarevent);
656 $event->trigger();
657 }
658 } else {
659 $DB->update_record('event', $this->properties);
660 $event = self::load($this->properties->id);
661 $this->properties = $event->properties();
662
663 // Trigger an update event.
664 $event = \core\event\calendar_event_updated::create($eventargs);
665 $event->add_record_snapshot('event', $this->properties);
666 $event->trigger();
667 }
668
669 return true;
670 }
671 }
672
673 /**
674 * Deletes an event and if selected an repeated events in the same series
675 *
676 * This function deletes an event, any associated events if $deleterepeated=true,
677 * and cleans up any files associated with the events.
678 *
679 * @see self::delete()
680 *
681 * @param bool $deleterepeated delete event repeatedly
682 * @return bool succession of deleting event
683 */
684 public function delete($deleterepeated = false) {
685 global $DB;
686
687 // If $this->properties->id is not set then something is wrong.
688 if (empty($this->properties->id)) {
689 debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
690 return false;
691 }
692 $calevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
693 // Delete the event.
694 $DB->delete_records('event', array('id' => $this->properties->id));
695
696 // Trigger an event for the delete action.
697 $eventargs = array(
08a79155 698 'context' => $this->get_context(),
e1cd93ce
MN
699 'objectid' => $this->properties->id,
700 'other' => array(
701 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
702 'timestart' => $this->properties->timestart,
703 'name' => $this->properties->name
704 ));
705 $event = \core\event\calendar_event_deleted::create($eventargs);
706 $event->add_record_snapshot('event', $calevent);
707 $event->trigger();
708
709 // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
710 if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
711 $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
712 array($this->properties->id), IGNORE_MULTIPLE);
713 if (!empty($newparent)) {
714 $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
715 array($newparent, $this->properties->id));
716 // Get all records where the repeatid is the same as the event being removed.
717 $events = $DB->get_records('event', array('repeatid' => $newparent));
718 // For each of the returned events trigger an update event.
719 foreach ($events as $calendarevent) {
720 // Trigger an event for the update.
721 $eventargs['objectid'] = $calendarevent->id;
722 $eventargs['other']['timestart'] = $calendarevent->timestart;
723 $event = \core\event\calendar_event_updated::create($eventargs);
724 $event->add_record_snapshot('event', $calendarevent);
725 $event->trigger();
726 }
727 }
728 }
729
730 // If the editor context hasn't already been set then set it now.
731 if ($this->editorcontext === null) {
08a79155 732 $this->editorcontext = $this->get_context();
e1cd93ce
MN
733 }
734
735 // If the context has been set delete all associated files.
736 if ($this->editorcontext !== null) {
737 $fs = get_file_storage();
738 $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
739 foreach ($files as $file) {
740 $file->delete();
741 }
742 }
743
744 // If we need to delete repeated events then we will fetch them all and delete one by one.
745 if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
746 // Get all records where the repeatid is the same as the event being removed.
747 $events = $DB->get_records('event', array('repeatid' => $this->properties->repeatid));
748 // For each of the returned events populate an event object and call delete.
749 // make sure the arg passed is false as we are already deleting all repeats.
750 foreach ($events as $event) {
751 $event = new calendar_event($event);
752 $event->delete(false);
753 }
754 }
755
756 return true;
757 }
758
759 /**
760 * Fetch all event properties.
761 *
762 * This function returns all of the events properties as an object and optionally
763 * can prepare an editor for the description field at the same time. This is
764 * designed to work when the properties are going to be used to set the default
765 * values of a moodle forms form.
766 *
767 * @param bool $prepareeditor If set to true a editor is prepared for use with
768 * the mforms editor element. (for description)
769 * @return \stdClass Object containing event properties
770 */
771 public function properties($prepareeditor = false) {
772 global $DB;
773
774 // First take a copy of the properties. We don't want to actually change the
775 // properties or we'd forever be converting back and forwards between an
776 // editor formatted description and not.
777 $properties = clone($this->properties);
778 // Clean the description here.
779 $properties->description = clean_text($properties->description, $properties->format);
780
781 // If set to true we need to prepare the properties for use with an editor
782 // and prepare the file area.
783 if ($prepareeditor) {
784
785 // We may or may not have a property id. If we do then we need to work
786 // out the context so we can copy the existing files to the draft area.
787 if (!empty($properties->id)) {
788
789 if ($properties->eventtype === 'site') {
790 // Site context.
08a79155 791 $this->editorcontext = $this->get_context();
e1cd93ce
MN
792 } else if ($properties->eventtype === 'user') {
793 // User context.
08a79155 794 $this->editorcontext = $this->get_context();
e1cd93ce
MN
795 } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
796 // First check the course is valid.
797 $course = $DB->get_record('course', array('id' => $properties->courseid));
798 if (!$course) {
799 print_error('invalidcourse');
800 }
801 // Course context.
08a79155 802 $this->editorcontext = $this->get_context();
e1cd93ce
MN
803 // We have a course and are within the course context so we had
804 // better use the courses max bytes value.
805 $this->editoroptions['maxbytes'] = $course->maxbytes;
05f184bb
AN
806 } else if ($properties->eventtype === 'category') {
807 // First check the course is valid.
7d0a866c 808 \coursecat::get($properties->categoryid, MUST_EXIST, true);
05f184bb 809 // Course context.
08a79155 810 $this->editorcontext = $this->get_context();
e1cd93ce
MN
811 } else {
812 // If we get here we have a custom event type as used by some
813 // modules. In this case the event will have been added by
814 // code and we won't need the editor.
815 $this->editoroptions['maxbytes'] = 0;
816 $this->editoroptions['maxfiles'] = 0;
817 }
818
819 if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
820 $contextid = false;
821 } else {
822 // Get the context id that is what we really want.
823 $contextid = $this->editorcontext->id;
824 }
825 } else {
826
827 // If we get here then this is a new event in which case we don't need a
828 // context as there is no existing files to copy to the draft area.
829 $contextid = null;
830 }
831
832 // If the contextid === false we don't support files so no preparing
833 // a draft area.
834 if ($contextid !== false) {
835 // Just encase it has already been submitted.
836 $draftiddescription = file_get_submitted_draft_itemid('description');
837 // Prepare the draft area, this copies existing files to the draft area as well.
838 $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
839 'event_description', $properties->id, $this->editoroptions, $properties->description);
840 } else {
841 $draftiddescription = 0;
842 }
843
844 // Structure the description field as the editor requires.
845 $properties->description = array('text' => $properties->description, 'format' => $properties->format,
846 'itemid' => $draftiddescription);
847 }
848
849 // Finally return the properties.
850 return $properties;
851 }
852
853 /**
854 * Toggles the visibility of an event
855 *
856 * @param null|bool $force If it is left null the events visibility is flipped,
857 * If it is false the event is made hidden, if it is true it
858 * is made visible.
859 * @return bool if event is successfully updated, toggle will be visible
860 */
861 public function toggle_visibility($force = null) {
862 global $DB;
863
864 // Set visible to the default if it is not already set.
865 if (empty($this->properties->visible)) {
866 $this->properties->visible = 1;
867 }
868
869 if ($force === true || ($force !== false && $this->properties->visible == 0)) {
870 // Make this event visible.
871 $this->properties->visible = 1;
872 } else {
873 // Make this event hidden.
874 $this->properties->visible = 0;
875 }
876
877 // Update the database to reflect this change.
878 $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
879 $calendarevent = $DB->get_record('event', array('id' => $this->properties->id), '*', MUST_EXIST);
880
881 // Prepare event data.
882 $eventargs = array(
08a79155 883 'context' => $this->get_context(),
e1cd93ce
MN
884 'objectid' => $this->properties->id,
885 'other' => array(
886 'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
887 'timestart' => $this->properties->timestart,
888 'name' => $this->properties->name
889 )
890 );
891 $event = \core\event\calendar_event_updated::create($eventargs);
892 $event->add_record_snapshot('event', $calendarevent);
893 $event->trigger();
894
895 return $success;
896 }
897
898 /**
899 * Returns an event object when provided with an event id.
900 *
901 * This function makes use of MUST_EXIST, if the event id passed in is invalid
902 * it will result in an exception being thrown.
903 *
904 * @param int|object $param event object or event id
905 * @return calendar_event
906 */
907 public static function load($param) {
908 global $DB;
909 if (is_object($param)) {
910 $event = new calendar_event($param);
911 } else {
912 $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
913 $event = new calendar_event($event);
914 }
915 return $event;
916 }
917
918 /**
919 * Creates a new event and returns an event object
920 *
921 * @param \stdClass|array $properties An object containing event properties
922 * @param bool $checkcapability Check caps or not
923 * @throws \coding_exception
924 *
925 * @return calendar_event|bool The event object or false if it failed
926 */
927 public static function create($properties, $checkcapability = true) {
928 if (is_array($properties)) {
929 $properties = (object)$properties;
930 }
931 if (!is_object($properties)) {
932 throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
933 }
934 $event = new calendar_event($properties);
935 if ($event->update($properties, $checkcapability)) {
936 return $event;
937 } else {
938 return false;
939 }
940 }
941
942 /**
943 * Format the text using the external API.
944 *
945 * This function should we used when text formatting is required in external functions.
946 *
947 * @return array an array containing the text formatted and the text format
948 */
949 public function format_external_text() {
950
951 if ($this->editorcontext === null) {
952 // Switch on the event type to decide upon the appropriate context to use for this event.
08a79155 953 $this->editorcontext = $this->get_context();
e1cd93ce 954
05f184bb 955 if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
e1cd93ce
MN
956 // We don't have a context here, do a normal format_text.
957 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id);
958 }
959 }
960
961 // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
962 if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
963 $itemid = $this->properties->repeatid;
964 } else {
965 $itemid = $this->properties->id;
966 }
967
968 return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id,
969 'calendar', 'event_description', $itemid);
970 }
971}
972
36dc3b71
SH
973/**
974 * Calendar information class
975 *
976 * This class is used simply to organise the information pertaining to a calendar
977 * and is used primarily to make information easily available.
08b4a4e1
RW
978 *
979 * @package core_calendar
980 * @category calendar
981 * @copyright 2010 Sam Hemelryk
982 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
36dc3b71
SH
983 */
984class calendar_information {
08b4a4e1 985
da304137
MN
986 /**
987 * @var int The timestamp
988 *
989 * Rather than setting the day, month and year we will set a timestamp which will be able
990 * to be used by multiple calendars.
991 */
992 public $time;
36dc3b71 993
08b4a4e1 994 /** @var int A course id */
36dc3b71 995 public $courseid = null;
08b4a4e1 996
7d0a866c
AN
997 /** @var array An array of categories */
998 public $categories = array();
999
1000 /** @var int The current category */
1001 public $categoryid = null;
1002
08b4a4e1 1003 /** @var array An array of courses */
36dc3b71 1004 public $courses = array();
08b4a4e1
RW
1005
1006 /** @var array An array of groups */
36dc3b71 1007 public $groups = array();
08b4a4e1
RW
1008
1009 /** @var array An array of users */
36dc3b71
SH
1010 public $users = array();
1011
7b7bf31d
AN
1012 /** @var context The anticipated context that the calendar is viewed in */
1013 public $context = null;
1014
36dc3b71
SH
1015 /**
1016 * Creates a new instance
1017 *
08b4a4e1
RW
1018 * @param int $day the number of the day
1019 * @param int $month the number of the month
1020 * @param int $year the number of the year
da304137
MN
1021 * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
1022 * and $calyear to support multiple calendars
36dc3b71 1023 */
da304137
MN
1024 public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
1025 // If a day, month and year were passed then convert it to a timestamp. If these were passed
1026 // then we can assume the day, month and year are passed as Gregorian, as no where in core
1027 // should we be passing these values rather than the time. This is done for BC.
1028 if (!empty($day) || !empty($month) || !empty($year)) {
1029 $date = usergetdate(time());
1030 if (empty($day)) {
1031 $day = $date['mday'];
1032 }
1033 if (empty($month)) {
1034 $month = $date['mon'];
1035 }
1036 if (empty($year)) {
1037 $year = $date['year'];
1038 }
1039 if (checkdate($month, $day, $year)) {
6038d626 1040 $time = make_timestamp($year, $month, $day);
da304137 1041 } else {
6038d626 1042 $time = time();
da304137 1043 }
6038d626
AN
1044 }
1045
1046 $this->set_time($time);
1047 }
1048
7b7bf31d
AN
1049 /**
1050 * Creates and set up a instance.
1051 *
1052 * @param int $time the unixtimestamp representing the date we want to view.
1053 * @param int $courseid The ID of the course the user wishes to view.
1054 * @param int $categoryid The ID of the category the user wishes to view
1055 * If a courseid is specified, this value is ignored.
1056 * @return calendar_information
1057 */
1058 public static function create($time, int $courseid, int $categoryid = null) : calendar_information {
1059 $calendar = new static(0, 0, 0, $time);
1060 if ($courseid != SITEID && !empty($courseid)) {
1061 // Course ID must be valid and existing.
1062 $course = get_course($courseid);
1063 $calendar->context = context_course::instance($course->id);
1064
0188d5b5 1065 if (!$course->visible && !is_role_switched($course->id)) {
7b7bf31d
AN
1066 require_capability('moodle/course:viewhiddencourses', $calendar->context);
1067 }
1068
1069 $courses = [$course->id => $course];
5e8e87aa 1070 $category = (\coursecat::get($course->category, MUST_EXIST, true))->get_db_record();
7b7bf31d
AN
1071 } else if (!empty($categoryid)) {
1072 $course = get_site();
0f1e7ec9 1073 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
7b7bf31d
AN
1074
1075 // Filter available courses to those within this category or it's children.
1076 $ids = [$categoryid];
1077 $category = \coursecat::get($categoryid);
1078 $ids = array_merge($ids, array_keys($category->get_children()));
1079 $courses = array_filter($courses, function($course) use ($ids) {
1080 return array_search($course->category, $ids) !== false;
1081 });
1082 $category = $category->get_db_record();
1083
1084 $calendar->context = context_coursecat::instance($categoryid);
1085 } else {
1086 $course = get_site();
0f1e7ec9 1087 $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
7b7bf31d
AN
1088 $category = null;
1089
1090 $calendar->context = context_system::instance();
1091 }
1092
1093 $calendar->set_sources($course, $courses, $category);
1094
1095 return $calendar;
1096 }
1097
6038d626
AN
1098 /**
1099 * Set the time period of this instance.
1100 *
1101 * @param int $time the unixtimestamp representing the date we want to view.
1102 * @return $this
1103 */
1104 public function set_time($time = null) {
02d0c435 1105 if (empty($time)) {
da304137 1106 $this->time = time();
6038d626
AN
1107 } else {
1108 $this->time = $time;
d8d8bdd9 1109 }
6038d626
AN
1110
1111 return $this;
36dc3b71
SH
1112 }
1113
797cedc7 1114 /**
08b4a4e1 1115 * Initialize calendar information
797cedc7 1116 *
7d0a866c 1117 * @deprecated 3.4
08b4a4e1 1118 * @param stdClass $course object
797cedc7 1119 * @param array $coursestoload An array of courses [$course->id => $course]
08b4a4e1 1120 * @param bool $ignorefilters options to use filter
797cedc7
SH
1121 */
1122 public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
7d0a866c
AN
1123 debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
1124 DEBUG_DEVELOPER);
1125 $this->set_sources($course, $coursestoload);
1126 }
1127
1128 /**
1129 * Set the sources for events within the calendar.
1130 *
1131 * If no category is provided, then the category path for the current
1132 * course will be used.
1133 *
1134 * @param stdClass $course The current course being viewed.
c4172077 1135 * @param stdClass[] $courses The list of all courses currently accessible.
7d0a866c
AN
1136 * @param stdClass $category The current category to show.
1137 */
1138 public function set_sources(stdClass $course, array $courses, stdClass $category = null) {
57e8c9f7
AN
1139 global $USER;
1140
7d0a866c 1141 // A cousre must always be specified.
797cedc7 1142 $this->course = $course;
7d0a866c
AN
1143 $this->courseid = $course->id;
1144
1145 list($courseids, $group, $user) = calendar_set_filters($courses);
1146 $this->courses = $courseids;
797cedc7
SH
1147 $this->groups = $group;
1148 $this->users = $user;
7d0a866c
AN
1149
1150 // Do not show category events by default.
1151 $this->categoryid = null;
1152 $this->categories = null;
1153
57e8c9f7
AN
1154 // Determine the correct category information to show.
1155 // When called with a course, the category of that course is usually included too.
1156 // When a category was specifically requested, it should be requested with the site id.
1157 if (SITEID !== $this->courseid) {
1158 // A specific course was requested.
1159 // Fetch the category that this course is in, along with all parents.
1160 // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
5e8e87aa 1161 $category = \coursecat::get($course->category, MUST_EXIST, true);
7d0a866c
AN
1162 $this->categoryid = $category->id;
1163
1164 $this->categories = $category->get_parents();
1165 $this->categories[] = $category->id;
57e8c9f7
AN
1166 } else if (null !== $category && $category->id > 0) {
1167 // A specific category was requested.
1168 // Fetch all parents of this category, along with all children too.
1169 $category = \coursecat::get($category->id);
1170 $this->categoryid = $category->id;
1171
1172 // Build the category list.
1173 // This includes the current category.
c4172077
MG
1174 $this->categories = $category->get_parents();
1175 $this->categories[] = $category->id;
1176 $this->categories = array_merge($this->categories, $category->get_all_children_ids());
57e8c9f7
AN
1177 } else if (SITEID === $this->courseid) {
1178 // The site was requested.
1179 // Fetch all categories where this user has any enrolment, and all categories that this user can manage.
1180
1181 // Grab the list of categories that this user has courses in.
1182 $coursecategories = array_flip(array_map(function($course) {
1183 return $course->category;
1184 }, $courses));
1185
c4172077
MG
1186 $calcatcache = cache::make('core', 'calendar_categories');
1187 $this->categories = $calcatcache->get('site');
1188 if ($this->categories === false) {
1189 // Use the category id as the key in the following array. That way we do not have to remove duplicates.
1190 $categories = [];
1191 foreach (\coursecat::get_all() as $category) {
1192 if (isset($coursecategories[$category->id]) ||
1193 has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
1194 // If the user has access to a course in this category or can manage the category,
1195 // then they can see all parent categories too.
1196 $categories[$category->id] = true;
1197 foreach ($category->get_parents() as $catid) {
1198 $categories[$catid] = true;
57e8c9f7
AN
1199 }
1200 }
7d0a866c 1201 }
c4172077
MG
1202 $this->categories = array_keys($categories);
1203 $calcatcache->set('site', $this->categories);
7d0a866c 1204 }
7d0a866c 1205 }
797cedc7
SH
1206 }
1207
36dc3b71
SH
1208 /**
1209 * Ensures the date for the calendar is correct and either sets it to now
1210 * or throws a moodle_exception if not
1211 *
08b4a4e1
RW
1212 * @param bool $defaultonow use current time
1213 * @throws moodle_exception
1214 * @return bool validation of checkdate
36dc3b71
SH
1215 */
1216 public function checkdate($defaultonow = true) {
1217 if (!checkdate($this->month, $this->day, $this->year)) {
1218 if ($defaultonow) {
1219 $now = usergetdate(time());
1220 $this->day = intval($now['mday']);
1221 $this->month = intval($now['mon']);
1222 $this->year = intval($now['year']);
1223 return true;
1224 } else {
1225 throw new moodle_exception('invaliddate');
1226 }
1227 }
1228 return true;
1229 }
da304137 1230
36dc3b71
SH
1231 /**
1232 * Gets todays timestamp for the calendar
08b4a4e1
RW
1233 *
1234 * @return int today timestamp
36dc3b71
SH
1235 */
1236 public function timestamp_today() {
da304137 1237 return $this->time;
36dc3b71
SH
1238 }
1239 /**
1240 * Gets tomorrows timestamp for the calendar
08b4a4e1
RW
1241 *
1242 * @return int tomorrow timestamp
36dc3b71
SH
1243 */
1244 public function timestamp_tomorrow() {
a0ef87de 1245 return strtotime('+1 day', $this->time);
36dc3b71
SH
1246 }
1247 /**
e30390a0 1248 * Adds the pretend blocks for the calendar
36dc3b71
SH
1249 *
1250 * @param core_calendar_renderer $renderer
08b4a4e1
RW
1251 * @param bool $showfilters display filters, false is set as default
1252 * @param string|null $view preference view options (eg: day, month, upcoming)
36dc3b71
SH
1253 */
1254 public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1255 if ($showfilters) {
1256 $filters = new block_contents();
fc60d319 1257 $filters->content = $renderer->event_filter();
36dc3b71
SH
1258 $filters->footer = '';
1259 $filters->title = get_string('eventskey', 'calendar');
1260 $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
1261 }
1262 $block = new block_contents;
1263 $block->content = $renderer->fake_block_threemonths($this);
1264 $block->footer = '';
1265 $block->title = get_string('monthlyview', 'calendar');
1266 $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
1267 }
1d5bd3d2 1268}
b5a52acd 1269
10515e15
MN
1270/**
1271 * Get calendar events.
1272 *
1273 * @param int $tstart Start time of time range for events
1274 * @param int $tend End time of time range for events
1275 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
1276 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
1277 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
1278 * @param boolean $withduration whether only events starting within time range selected
1279 * or events in progress/already started selected as well
1280 * @param boolean $ignorehidden whether to select only visible events or all events
93623513 1281 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
10515e15
MN
1282 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
1283 */
93623513
AN
1284function calendar_get_events($tstart, $tend, $users, $groups, $courses,
1285 $withduration = true, $ignorehidden = true, $categories = []) {
10515e15 1286 global $DB;
10515e15 1287
eeb27f03
CB
1288 $whereclause = '';
1289 $params = array();
10515e15 1290 // Quick test.
93623513 1291 if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
10515e15
MN
1292 return array();
1293 }
1294
10515e15 1295 if ((is_array($users) && !empty($users)) or is_numeric($users)) {
eeb27f03
CB
1296 // Events from a number of users
1297 if(!empty($whereclause)) $whereclause .= ' OR';
10515e15 1298 list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
93623513 1299 $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
10515e15 1300 $params = array_merge($params, $inparamsusers);
eeb27f03
CB
1301 } else if($users === true) {
1302 // Events from ALL users
1303 if(!empty($whereclause)) $whereclause .= ' OR';
93623513 1304 $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
eeb27f03
CB
1305 } else if($users === false) {
1306 // No user at all, do nothing
10515e15
MN
1307 }
1308
10515e15 1309 if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
eeb27f03
CB
1310 // Events from a number of groups
1311 if(!empty($whereclause)) $whereclause .= ' OR';
10515e15 1312 list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
eeb27f03 1313 $whereclause .= " e.groupid $insqlgroups ";
10515e15 1314 $params = array_merge($params, $inparamsgroups);
eeb27f03
CB
1315 } else if($groups === true) {
1316 // Events from ALL groups
1317 if(!empty($whereclause)) $whereclause .= ' OR ';
1318 $whereclause .= ' e.groupid != 0';
10515e15 1319 }
eeb27f03 1320 // boolean false (no groups at all): we don't need to do anything
10515e15 1321
10515e15 1322 if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
eeb27f03 1323 if(!empty($whereclause)) $whereclause .= ' OR';
10515e15 1324 list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
eeb27f03 1325 $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
10515e15
MN
1326 $params = array_merge($params, $inparamscourses);
1327 } else if ($courses === true) {
eeb27f03
CB
1328 // Events from ALL courses
1329 if(!empty($whereclause)) $whereclause .= ' OR';
1330 $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
10515e15
MN
1331 }
1332
93623513 1333 if ((is_array($categories) && !empty($categories)) || is_numeric($categories)) {
d097bfdd
AN
1334 if (!empty($whereclause)) {
1335 $whereclause .= ' OR';
1336 }
93623513
AN
1337 list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED);
1338 $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
1339 $params = array_merge($params, $inparamscategories);
1340 } else if ($categories === true) {
1341 // Events from ALL categories.
d097bfdd
AN
1342 if (!empty($whereclause)) {
1343 $whereclause .= ' OR';
1344 }
93623513
AN
1345 $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
1346 }
1347
10515e15
MN
1348 // Security check: if, by now, we have NOTHING in $whereclause, then it means
1349 // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
1350 // events no matter what. Allowing the code to proceed might return a completely
1351 // valid query with only time constraints, thus selecting ALL events in that time frame!
eeb27f03 1352 if(empty($whereclause)) {
10515e15
MN
1353 return array();
1354 }
1355
eeb27f03
CB
1356 if($withduration) {
1357 $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
10515e15 1358 }
eeb27f03
CB
1359 else {
1360 $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
10515e15 1361 }
eeb27f03
CB
1362 if(!empty($whereclause)) {
1363 // We have additional constraints
1364 $whereclause = $timeclause.' AND ('.$whereclause.')';
10515e15 1365 }
eeb27f03
CB
1366 else {
1367 // Just basic time filtering
1368 $whereclause = $timeclause;
10515e15
MN
1369 }
1370
eeb27f03
CB
1371 if ($ignorehidden) {
1372 $whereclause .= ' AND e.visible = 1';
10515e15
MN
1373 }
1374
10515e15 1375 $sql = "SELECT e.*
eeb27f03
CB
1376 FROM {event} e
1377 LEFT JOIN {modules} m ON e.modulename = m.name
1378 -- Non visible modules will have a value of 0.
1379 WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
1380 ORDER BY e.timestart";
10515e15
MN
1381 $events = $DB->get_records_sql($sql, $params);
1382
1383 if ($events === false) {
1384 $events = array();
1385 }
10515e15
MN
1386 return $events;
1387}
1388
1389/**
1390 * Return the days of the week.
1391 *
1392 * @return array array of days
1393 */
1394function calendar_get_days() {
23a29de7
MN
1395 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1396 return $calendartype->get_weekdays();
10515e15
MN
1397}
1398
1399/**
1400 * Get the subscription from a given id.
1401 *
1402 * @since Moodle 2.5
1403 * @param int $id id of the subscription
1404 * @return stdClass Subscription record from DB
1405 * @throws moodle_exception for an invalid id
1406 */
1407function calendar_get_subscription($id) {
23a29de7
MN
1408 global $DB;
1409
1410 $cache = \cache::make('core', 'calendar_subscriptions');
1411 $subscription = $cache->get($id);
1412 if (empty($subscription)) {
1413 $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
1414 $cache->set($id, $subscription);
1415 }
1416
1417 return $subscription;
10515e15
MN
1418}
1419
1420/**
1421 * Gets the first day of the week.
1422 *
1423 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
1424 *
1425 * @return int
1426 */
1427function calendar_get_starting_weekday() {
23a29de7
MN
1428 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1429 return $calendartype->get_starting_weekday();
10515e15
MN
1430}
1431
10515e15
MN
1432/**
1433 * Get a HTML link to a course.
1434 *
5900513f 1435 * @param int|stdClass $course the course id or course object
10515e15
MN
1436 * @return string a link to the course (as HTML); empty if the course id is invalid
1437 */
5900513f
MG
1438function calendar_get_courselink($course) {
1439 if (!$course) {
23a29de7
MN
1440 return '';
1441 }
1442
5900513f
MG
1443 if (!is_object($course)) {
1444 $course = calendar_get_course_cached($coursecache, $course);
1445 }
1446 $context = \context_course::instance($course->id);
1447 $fullname = format_string($course->fullname, true, array('context' => $context));
1448 $url = new \moodle_url('/course/view.php', array('id' => $course->id));
23a29de7
MN
1449 $link = \html_writer::link($url, $fullname);
1450
1451 return $link;
10515e15
MN
1452}
1453
1454/**
1455 * Get current module cache.
1456 *
47a71017 1457 * Only use this method if you do not know courseid. Otherwise use:
5900513f
MG
1458 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
1459 *
23a29de7 1460 * @param array $modulecache in memory module cache
10515e15
MN
1461 * @param string $modulename name of the module
1462 * @param int $instance module instance number
1463 * @return stdClass|bool $module information
1464 */
23a29de7
MN
1465function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
1466 if (!isset($modulecache[$modulename . '_' . $instance])) {
1467 $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
10515e15 1468 }
23a29de7
MN
1469
1470 return $modulecache[$modulename . '_' . $instance];
10515e15
MN
1471}
1472
1473/**
1474 * Get current course cache.
1475 *
1476 * @param array $coursecache list of course cache
1477 * @param int $courseid id of the course
1478 * @return stdClass $coursecache[$courseid] return the specific course cache
1479 */
1480function calendar_get_course_cached(&$coursecache, $courseid) {
23a29de7
MN
1481 if (!isset($coursecache[$courseid])) {
1482 $coursecache[$courseid] = get_course($courseid);
1483 }
1484 return $coursecache[$courseid];
10515e15
MN
1485}
1486
1487/**
1488 * Get group from groupid for calendar display
1489 *
1490 * @param int $groupid
1491 * @return stdClass group object with fields 'id', 'name' and 'courseid'
1492 */
1493function calendar_get_group_cached($groupid) {
23a29de7
MN
1494 static $groupscache = array();
1495 if (!isset($groupscache[$groupid])) {
1496 $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
1497 }
1498 return $groupscache[$groupid];
10515e15
MN
1499}
1500
1501/**
1502 * Add calendar event metadata
1503 *
1504 * @param stdClass $event event info
1505 * @return stdClass $event metadata
1506 */
1507function calendar_add_event_metadata($event) {
23a29de7
MN
1508 global $CFG, $OUTPUT;
1509
1510 // Support multilang in event->name.
1511 $event->name = format_string($event->name, true);
1512
1513 if (!empty($event->modulename)) { // Activity event.
1514 // The module name is set. I will assume that it has to be displayed, and
1515 // also that it is an automatically-generated event. And of course that the
5900513f
MG
1516 // instace id and modulename are set correctly.
1517 $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
1518 if (!array_key_exists($event->instance, $instances)) {
23a29de7
MN
1519 return;
1520 }
5900513f 1521 $module = $instances[$event->instance];
23a29de7 1522
5900513f 1523 $modulename = $module->get_module_type_name(false);
23a29de7
MN
1524 if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
1525 // Will be used as alt text if the event icon.
1526 $eventtype = get_string($event->eventtype, $event->modulename);
1527 } else {
1528 $eventtype = '';
1529 }
23a29de7 1530
5900513f
MG
1531 $event->icon = '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
1532 '" title="' . s($modulename) . '" class="icon" />';
1533 $event->referer = html_writer::link($module->url, $event->name);
1534 $event->courselink = calendar_get_courselink($module->get_course());
23a29de7
MN
1535 $event->cmid = $module->id;
1536 } else if ($event->courseid == SITEID) { // Site event.
1537 $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
1538 get_string('globalevent', 'calendar') . '" class="icon" />';
1539 $event->cssclass = 'calendar_event_global';
1540 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
1541 $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
1542 get_string('courseevent', 'calendar') . '" class="icon" />';
1543 $event->courselink = calendar_get_courselink($event->courseid);
1544 $event->cssclass = 'calendar_event_course';
1545 } else if ($event->groupid) { // Group event.
1546 if ($group = calendar_get_group_cached($event->groupid)) {
1547 $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
1548 } else {
1549 $groupname = '';
1550 }
1551 $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
1552 'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
1553 $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
1554 $event->cssclass = 'calendar_event_group';
1555 } else if ($event->userid) { // User event.
1556 $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
1557 get_string('userevent', 'calendar') . '" class="icon" />';
1558 $event->cssclass = 'calendar_event_user';
1559 }
1560
1561 return $event;
10515e15
MN
1562}
1563
1564/**
1565 * Get calendar events by id.
1566 *
1567 * @since Moodle 2.5
1568 * @param array $eventids list of event ids
1569 * @return array Array of event entries, empty array if nothing found
1570 */
1571function calendar_get_events_by_id($eventids) {
23a29de7
MN
1572 global $DB;
1573
1574 if (!is_array($eventids) || empty($eventids)) {
1575 return array();
1576 }
1577
1578 list($wheresql, $params) = $DB->get_in_or_equal($eventids);
1579 $wheresql = "id $wheresql";
1580
1581 return $DB->get_records_select('event', $wheresql, $params);
10515e15
MN
1582}
1583
1584/**
1585 * Get control options for calendar.
1586 *
1587 * @param string $type of calendar
1588 * @param array $data calendar information
1589 * @return string $content return available control for the calender in html
1590 */
1591function calendar_top_controls($type, $data) {
23a29de7
MN
1592 global $PAGE, $OUTPUT;
1593
1594 // Get the calendar type we are using.
1595 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1596
1597 $content = '';
1598
1599 // Ensure course id passed if relevant.
1600 $courseid = '';
1601 if (!empty($data['id'])) {
1602 $courseid = '&amp;course=' . $data['id'];
1603 }
1604
1605 // If we are passing a month and year then we need to convert this to a timestamp to
1606 // support multiple calendars. No where in core should these be passed, this logic
1607 // here is for third party plugins that may use this function.
1608 if (!empty($data['m']) && !empty($date['y'])) {
1609 if (!isset($data['d'])) {
1610 $data['d'] = 1;
1611 }
1612 if (!checkdate($data['m'], $data['d'], $data['y'])) {
1613 $time = time();
1614 } else {
1615 $time = make_timestamp($data['y'], $data['m'], $data['d']);
1616 }
1617 } else if (!empty($data['time'])) {
1618 $time = $data['time'];
1619 } else {
1620 $time = time();
1621 }
1622
1623 // Get the date for the calendar type.
1624 $date = $calendartype->timestamp_to_date_array($time);
1625
1626 $urlbase = $PAGE->url;
1627
1628 // We need to get the previous and next months in certain cases.
1629 if ($type == 'frontpage' || $type == 'course' || $type == 'month') {
1630 $prevmonth = calendar_sub_month($date['mon'], $date['year']);
1631 $prevmonthtime = $calendartype->convert_to_gregorian($prevmonth[1], $prevmonth[0], 1);
1632 $prevmonthtime = make_timestamp($prevmonthtime['year'], $prevmonthtime['month'], $prevmonthtime['day'],
1633 $prevmonthtime['hour'], $prevmonthtime['minute']);
1634
1635 $nextmonth = calendar_add_month($date['mon'], $date['year']);
1636 $nextmonthtime = $calendartype->convert_to_gregorian($nextmonth[1], $nextmonth[0], 1);
1637 $nextmonthtime = make_timestamp($nextmonthtime['year'], $nextmonthtime['month'], $nextmonthtime['day'],
1638 $nextmonthtime['hour'], $nextmonthtime['minute']);
1639 }
1640
1641 switch ($type) {
1642 case 'frontpage':
1643 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1644 true, $prevmonthtime);
1645 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false, true,
1646 $nextmonthtime);
1647 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1648 false, false, false, $time);
1649
1650 if (!empty($data['id'])) {
1651 $calendarlink->param('course', $data['id']);
1652 }
1653
1654 $right = $nextlink;
1655
1656 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1657 $content .= $prevlink . '<span class="hide"> | </span>';
1658 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1659 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1660 ), array('class' => 'current'));
1661 $content .= '<span class="hide"> | </span>' . $right;
1662 $content .= "<span class=\"clearer\"><!-- --></span>\n";
1663 $content .= \html_writer::end_tag('div');
1664
1665 break;
1666 case 'course':
1667 $prevlink = calendar_get_link_previous(get_string('monthprev', 'access'), $urlbase, false, false, false,
1668 true, $prevmonthtime);
1669 $nextlink = calendar_get_link_next(get_string('monthnext', 'access'), $urlbase, false, false, false,
1670 true, $nextmonthtime);
1671 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1672 false, false, false, $time);
1673
1674 if (!empty($data['id'])) {
1675 $calendarlink->param('course', $data['id']);
1676 }
1677
1678 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1679 $content .= $prevlink . '<span class="hide"> | </span>';
1680 $content .= \html_writer::tag('span', \html_writer::link($calendarlink,
1681 userdate($time, get_string('strftimemonthyear')), array('title' => get_string('monththis', 'calendar'))
1682 ), array('class' => 'current'));
1683 $content .= '<span class="hide"> | </span>' . $nextlink;
1684 $content .= "<span class=\"clearer\"><!-- --></span>";
1685 $content .= \html_writer::end_tag('div');
1686 break;
1687 case 'upcoming':
1688 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'upcoming')),
1689 false, false, false, $time);
1690 if (!empty($data['id'])) {
1691 $calendarlink->param('course', $data['id']);
1692 }
1693 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1694 $content .= \html_writer::tag('div', $calendarlink, array('class' => 'centered'));
1695 break;
1696 case 'display':
1697 $calendarlink = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', array('view' => 'month')),
1698 false, false, false, $time);
1699 if (!empty($data['id'])) {
1700 $calendarlink->param('course', $data['id']);
1701 }
1702 $calendarlink = \html_writer::link($calendarlink, userdate($time, get_string('strftimemonthyear')));
1703 $content .= \html_writer::tag('h3', $calendarlink);
1704 break;
1705 case 'month':
1706 $prevlink = calendar_get_link_previous(userdate($prevmonthtime, get_string('strftimemonthyear')),
1707 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $prevmonthtime);
1708 $nextlink = calendar_get_link_next(userdate($nextmonthtime, get_string('strftimemonthyear')),
1709 'view.php?view=month' . $courseid . '&amp;', false, false, false, false, $nextmonthtime);
1710
1711 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1712 $content .= $prevlink . '<span class="hide"> | </span>';
1713 $content .= $OUTPUT->heading(userdate($time, get_string('strftimemonthyear')), 2, 'current');
1714 $content .= '<span class="hide"> | </span>' . $nextlink;
1715 $content .= '<span class="clearer"><!-- --></span>';
1716 $content .= \html_writer::end_tag('div')."\n";
1717 break;
1718 case 'day':
1719 $days = calendar_get_days();
1720
1721 $prevtimestamp = strtotime('-1 day', $time);
1722 $nexttimestamp = strtotime('+1 day', $time);
1723
1724 $prevdate = $calendartype->timestamp_to_date_array($prevtimestamp);
1725 $nextdate = $calendartype->timestamp_to_date_array($nexttimestamp);
1726
1727 $prevname = $days[$prevdate['wday']]['fullname'];
1728 $nextname = $days[$nextdate['wday']]['fullname'];
1729 $prevlink = calendar_get_link_previous($prevname, 'view.php?view=day' . $courseid . '&amp;', false, false,
1730 false, false, $prevtimestamp);
1731 $nextlink = calendar_get_link_next($nextname, 'view.php?view=day' . $courseid . '&amp;', false, false, false,
1732 false, $nexttimestamp);
1733
1734 $content .= \html_writer::start_tag('div', array('class' => 'calendar-controls'));
1735 $content .= $prevlink;
1736 $content .= '<span class="hide"> | </span><span class="current">' .userdate($time,
1737 get_string('strftimedaydate')) . '</span>';
1738 $content .= '<span class="hide"> | </span>' . $nextlink;
1739 $content .= "<span class=\"clearer\"><!-- --></span>";
1740 $content .= \html_writer::end_tag('div') . "\n";
1741
1742 break;
1743 }
1744
1745 return $content;
10515e15
MN
1746}
1747
10515e15
MN
1748/**
1749 * Return the representation day.
1750 *
1751 * @param int $tstamp Timestamp in GMT
1752 * @param int|bool $now current Unix timestamp
1753 * @param bool $usecommonwords
1754 * @return string the formatted date/time
1755 */
1756function calendar_day_representation($tstamp, $now = false, $usecommonwords = true) {
23a29de7
MN
1757 static $shortformat;
1758
1759 if (empty($shortformat)) {
1760 $shortformat = get_string('strftimedayshort');
1761 }
1762
1763 if ($now === false) {
1764 $now = time();
1765 }
1766
1767 // To have it in one place, if a change is needed.
1768 $formal = userdate($tstamp, $shortformat);
1769
1770 $datestamp = usergetdate($tstamp);
1771 $datenow = usergetdate($now);
1772
1773 if ($usecommonwords == false) {
1774 // We don't want words, just a date.
1775 return $formal;
1776 } else if ($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday']) {
1777 return get_string('today', 'calendar');
1778 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] - 1 ) ||
1779 ($datestamp['year'] == $datenow['year'] - 1 && $datestamp['mday'] == 31 && $datestamp['mon'] == 12
1780 && $datenow['yday'] == 1)) {
1781 return get_string('yesterday', 'calendar');
1782 } else if (($datestamp['year'] == $datenow['year'] && $datestamp['yday'] == $datenow['yday'] + 1 ) ||
1783 ($datestamp['year'] == $datenow['year'] + 1 && $datenow['mday'] == 31 && $datenow['mon'] == 12
1784 && $datestamp['yday'] == 1)) {
1785 return get_string('tomorrow', 'calendar');
1786 } else {
1787 return $formal;
1788 }
10515e15
MN
1789}
1790
1791/**
1792 * return the formatted representation time.
1793 *
1794
1795 * @param int $time the timestamp in UTC, as obtained from the database
1796 * @return string the formatted date/time
1797 */
1798function calendar_time_representation($time) {
23a29de7
MN
1799 static $langtimeformat = null;
1800
1801 if ($langtimeformat === null) {
1802 $langtimeformat = get_string('strftimetime');
1803 }
1804
1805 $timeformat = get_user_preferences('calendar_timeformat');
1806 if (empty($timeformat)) {
1807 $timeformat = get_config(null, 'calendar_site_timeformat');
1808 }
1809
099bca6d
MG
1810 // Allow language customization of selected time format.
1811 if ($timeformat === CALENDAR_TF_12) {
1812 $timeformat = get_string('strftimetime12', 'langconfig');
1813 } else if ($timeformat === CALENDAR_TF_24) {
1814 $timeformat = get_string('strftimetime24', 'langconfig');
1815 }
1816
23a29de7 1817 return userdate($time, empty($timeformat) ? $langtimeformat : $timeformat);
10515e15
MN
1818}
1819
1820/**
1821 * Adds day, month, year arguments to a URL and returns a moodle_url object.
1822 *
1823 * @param string|moodle_url $linkbase
1824 * @param int $d The number of the day.
1825 * @param int $m The number of the month.
1826 * @param int $y The number of the year.
1827 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1828 * $m and $y are kept for backwards compatibility.
1829 * @return moodle_url|null $linkbase
1830 */
1831function calendar_get_link_href($linkbase, $d, $m, $y, $time = 0) {
23a29de7
MN
1832 if (empty($linkbase)) {
1833 return null;
1834 }
1835
1836 if (!($linkbase instanceof \moodle_url)) {
1837 $linkbase = new \moodle_url($linkbase);
1838 }
1839
def443a0 1840 $linkbase->param('time', calendar_get_timestamp($d, $m, $y, $time));
23a29de7
MN
1841
1842 return $linkbase;
10515e15
MN
1843}
1844
1845/**
1846 * Build and return a previous month HTML link, with an arrow.
1847 *
1848 * @param string $text The text label.
1849 * @param string|moodle_url $linkbase The URL stub.
1850 * @param int $d The number of the date.
1851 * @param int $m The number of the month.
1852 * @param int $y year The number of the year.
1853 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1854 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1855 * $m and $y are kept for backwards compatibility.
1856 * @return string HTML string.
1857 */
1858function calendar_get_link_previous($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
23a29de7
MN
1859 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1860
1861 if (empty($href)) {
1862 return $text;
1863 }
1864
b16dca43
AN
1865 $attrs = [
1866 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
aefb2950 1867 'data-drop-zone' => 'nav-link',
b16dca43
AN
1868 ];
1869
1870 return link_arrow_left($text, $href->out(false), $accesshide, 'previous', $attrs);
10515e15
MN
1871}
1872
1873/**
1874 * Build and return a next month HTML link, with an arrow.
1875 *
1876 * @param string $text The text label.
1877 * @param string|moodle_url $linkbase The URL stub.
1878 * @param int $d the number of the Day
1879 * @param int $m The number of the month.
1880 * @param int $y The number of the year.
1881 * @param bool $accesshide Default visible, or hide from all except screenreaders.
1882 * @param int $time the unixtime, used for multiple calendar support. The values $d,
1883 * $m and $y are kept for backwards compatibility.
1884 * @return string HTML string.
1885 */
1886function calendar_get_link_next($text, $linkbase, $d, $m, $y, $accesshide = false, $time = 0) {
23a29de7
MN
1887 $href = calendar_get_link_href(new \moodle_url($linkbase), $d, $m, $y, $time);
1888
1889 if (empty($href)) {
1890 return $text;
1891 }
1892
b16dca43
AN
1893 $attrs = [
1894 'data-time' => calendar_get_timestamp($d, $m, $y, $time),
aefb2950 1895 'data-drop-zone' => 'nav-link',
b16dca43
AN
1896 ];
1897
1898 return link_arrow_right($text, $href->out(false), $accesshide, 'next', $attrs);
10515e15
MN
1899}
1900
1901/**
1902 * Return the number of days in month.
1903 *
1904 * @param int $month the number of the month.
1905 * @param int $year the number of the year
1906 * @return int
1907 */
1908function calendar_days_in_month($month, $year) {
23a29de7
MN
1909 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1910 return $calendartype->get_num_days_in_month($year, $month);
10515e15
MN
1911}
1912
1913/**
1914 * Get the next following month.
1915 *
1916 * @param int $month the number of the month.
1917 * @param int $year the number of the year.
1918 * @return array the following month
1919 */
1920function calendar_add_month($month, $year) {
23a29de7
MN
1921 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1922 return $calendartype->get_next_month($year, $month);
10515e15
MN
1923}
1924
1925/**
1926 * Get the previous month.
1927 *
1928 * @param int $month the number of the month.
1929 * @param int $year the number of the year.
1930 * @return array previous month
1931 */
1932function calendar_sub_month($month, $year) {
23a29de7
MN
1933 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1934 return $calendartype->get_prev_month($year, $month);
10515e15
MN
1935}
1936
1937/**
1938 * Get per-day basis events
1939 *
1940 * @param array $events list of events
1941 * @param int $month the number of the month
1942 * @param int $year the number of the year
1943 * @param array $eventsbyday event on specific day
1944 * @param array $durationbyday duration of the event in days
1945 * @param array $typesbyday event type (eg: global, course, user, or group)
1946 * @param array $courses list of courses
1947 * @return void
1948 */
1949function calendar_events_by_day($events, $month, $year, &$eventsbyday, &$durationbyday, &$typesbyday, &$courses) {
23a29de7
MN
1950 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1951
1952 $eventsbyday = array();
1953 $typesbyday = array();
1954 $durationbyday = array();
1955
1956 if ($events === false) {
1957 return;
1958 }
1959
1960 foreach ($events as $event) {
1961 $startdate = $calendartype->timestamp_to_date_array($event->timestart);
1962 if ($event->timeduration) {
1963 $enddate = $calendartype->timestamp_to_date_array($event->timestart + $event->timeduration - 1);
1964 } else {
1965 $enddate = $startdate;
1966 }
1967
1968 // Simple arithmetic: $year * 13 + $month is a distinct integer for each distinct ($year, $month) pair.
1969 if (!($startdate['year'] * 13 + $startdate['mon'] <= $year * 13 + $month) &&
1970 ($enddate['year'] * 13 + $enddate['mon'] >= $year * 13 + $month)) {
1971 continue;
1972 }
1973
1974 $eventdaystart = intval($startdate['mday']);
1975
1976 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
1977 // Give the event to its day.
1978 $eventsbyday[$eventdaystart][] = $event->id;
1979
1980 // Mark the day as having such an event.
1981 if ($event->courseid == SITEID && $event->groupid == 0) {
1982 $typesbyday[$eventdaystart]['startglobal'] = true;
1983 // Set event class for global event.
1984 $events[$event->id]->class = 'calendar_event_global';
1985 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
1986 $typesbyday[$eventdaystart]['startcourse'] = true;
1987 // Set event class for course event.
1988 $events[$event->id]->class = 'calendar_event_course';
1989 } else if ($event->groupid) {
1990 $typesbyday[$eventdaystart]['startgroup'] = true;
1991 // Set event class for group event.
1992 $events[$event->id]->class = 'calendar_event_group';
1993 } else if ($event->userid) {
1994 $typesbyday[$eventdaystart]['startuser'] = true;
1995 // Set event class for user event.
1996 $events[$event->id]->class = 'calendar_event_user';
1997 }
1998 }
1999
2000 if ($event->timeduration == 0) {
2001 // Proceed with the next.
2002 continue;
2003 }
2004
2005 // The event starts on $month $year or before.
2006 if ($startdate['mon'] == $month && $startdate['year'] == $year) {
2007 $lowerbound = intval($startdate['mday']);
2008 } else {
2009 $lowerbound = 0;
2010 }
2011
2012 // Also, it ends on $month $year or later.
2013 if ($enddate['mon'] == $month && $enddate['year'] == $year) {
2014 $upperbound = intval($enddate['mday']);
2015 } else {
2016 $upperbound = calendar_days_in_month($month, $year);
2017 }
2018
2019 // Mark all days between $lowerbound and $upperbound (inclusive) as duration.
2020 for ($i = $lowerbound + 1; $i <= $upperbound; ++$i) {
2021 $durationbyday[$i][] = $event->id;
2022 if ($event->courseid == SITEID && $event->groupid == 0) {
2023 $typesbyday[$i]['durationglobal'] = true;
2024 } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) {
2025 $typesbyday[$i]['durationcourse'] = true;
2026 } else if ($event->groupid) {
2027 $typesbyday[$i]['durationgroup'] = true;
2028 } else if ($event->userid) {
2029 $typesbyday[$i]['durationuser'] = true;
2030 }
2031 }
2032
2033 }
2034 return;
10515e15
MN
2035}
2036
2037/**
2038 * Returns the courses to load events for.
2039 *
2040 * @param array $courseeventsfrom An array of courses to load calendar events for
2041 * @param bool $ignorefilters specify the use of filters, false is set as default
d8c6c21c 2042 * @param stdClass $user The user object. This defaults to the global $USER object.
10515e15
MN
2043 * @return array An array of courses, groups, and user to load calendar events for based upon filters
2044 */
d8c6c21c
SR
2045function calendar_set_filters(array $courseeventsfrom, $ignorefilters = false, stdClass $user = null) {
2046 global $CFG, $USER;
2047
2048 if (is_null($user)) {
2049 $user = $USER;
23a29de7
MN
2050 }
2051
2052 $courses = array();
d8c6c21c 2053 $userid = false;
23a29de7
MN
2054 $group = false;
2055
2056 // Get the capabilities that allow seeing group events from all groups.
2057 $allgroupscaps = array('moodle/site:accessallgroups', 'moodle/calendar:manageentries');
2058
d8c6c21c 2059 $isvaliduser = !empty($user->id);
23a29de7 2060
d8c6c21c 2061 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_COURSE, $user)) {
23a29de7
MN
2062 $courses = array_keys($courseeventsfrom);
2063 }
d8c6c21c 2064 if ($ignorefilters || calendar_show_event_type(CALENDAR_EVENT_GLOBAL, $user)) {
23a29de7
MN
2065 $courses[] = SITEID;
2066 }
2067 $courses = array_unique($courses);
2068 sort($courses);
2069
2070 if (!empty($courses) && in_array(SITEID, $courses)) {
2071 // Sort courses for consistent colour highlighting.
2072 // Effectively ignoring SITEID as setting as last course id.
2073 $key = array_search(SITEID, $courses);
2074 unset($courses[$key]);
2075 $courses[] = SITEID;
2076 }
2077
d8c6c21c
SR
2078 if ($ignorefilters || ($isvaliduser && calendar_show_event_type(CALENDAR_EVENT_USER, $user))) {
2079 $userid = $user->id;
23a29de7
MN
2080 }
2081
d8c6c21c 2082 if (!empty($courseeventsfrom) && (calendar_show_event_type(CALENDAR_EVENT_GROUP, $user) || $ignorefilters)) {
23a29de7
MN
2083
2084 if (count($courseeventsfrom) == 1) {
2085 $course = reset($courseeventsfrom);
2086 if (has_any_capability($allgroupscaps, \context_course::instance($course->id))) {
2087 $coursegroups = groups_get_all_groups($course->id, 0, 0, 'g.id');
2088 $group = array_keys($coursegroups);
2089 }
2090 }
2091 if ($group === false) {
2092 if (!empty($CFG->calendar_adminseesall) && has_any_capability($allgroupscaps, \context_system::instance())) {
2093 $group = true;
d8c6c21c 2094 } else if ($isvaliduser) {
23a29de7
MN
2095 $groupids = array();
2096 foreach ($courseeventsfrom as $courseid => $course) {
2097 // If the user is an editing teacher in there.
d8c6c21c 2098 if (!empty($user->groupmember[$course->id])) {
23a29de7 2099 // We've already cached the users groups for this course so we can just use that.
d8c6c21c 2100 $groupids = array_merge($groupids, $user->groupmember[$course->id]);
23a29de7
MN
2101 } else if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2102 // If this course has groups, show events from all of those related to the current user.
d8c6c21c 2103 $coursegroups = groups_get_user_groups($course->id, $user->id);
23a29de7
MN
2104 $groupids = array_merge($groupids, $coursegroups['0']);
2105 }
2106 }
2107 if (!empty($groupids)) {
2108 $group = $groupids;
2109 }
2110 }
2111 }
2112 }
2113 if (empty($courses)) {
2114 $courses = false;
2115 }
2116
d8c6c21c 2117 return array($courses, $group, $userid);
10515e15
MN
2118}
2119
af25b8fc
DW
2120/**
2121 * Return the capability for viewing a calendar event.
2122 *
2123 * @param calendar_event $event event object
2124 * @return boolean
2125 */
2126function calendar_view_event_allowed(calendar_event $event) {
2127 global $USER;
2128
2129 // Anyone can see site events.
2130 if ($event->courseid && $event->courseid == SITEID) {
2131 return true;
2132 }
2133
2134 // If a user can manage events at the site level they can see any event.
2135 $sitecontext = \context_system::instance();
2136 // If user has manageentries at site level, return true.
2137 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2138 return true;
2139 }
2140
2141 if (!empty($event->groupid)) {
2142 // If it is a group event we need to be able to manage events in the course, or be in the group.
30890c29
DW
2143 if (has_capability('moodle/calendar:manageentries', $event->context) ||
2144 has_capability('moodle/calendar:managegroupentries', $event->context)) {
af25b8fc
DW
2145 return true;
2146 }
2147
2148 $mycourses = enrol_get_my_courses('id');
2149 return isset($mycourses[$event->courseid]) && groups_is_member($event->groupid);
2150 } else if ($event->modulename) {
2151 // If this is a module event we need to be able to see the module.
30890c29
DW
2152 $coursemodules = [];
2153 $courseid = 0;
2154 // Override events do not have the courseid set.
2155 if ($event->courseid) {
2156 $courseid = $event->courseid;
2157 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2158 } else {
2159 $cmraw = get_coursemodule_from_instance($event->modulename, $event->instance, 0, false, MUST_EXIST);
2160 $courseid = $cmraw->course;
2161 $coursemodules = get_fast_modinfo($cmraw->course)->instances;
2162 }
af25b8fc
DW
2163 $hasmodule = isset($coursemodules[$event->modulename]);
2164 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2165
2166 // If modinfo doesn't know about the module, return false to be safe.
2167 if (!$hasmodule || !$hasinstance) {
2168 return false;
2169 }
2170
2171 // Must be able to see the course and the module - MDL-59304.
2172 $cm = $coursemodules[$event->modulename][$event->instance];
2173 if (!$cm->uservisible) {
2174 return false;
2175 }
2176 $mycourses = enrol_get_my_courses('id');
30890c29 2177 return isset($mycourses[$courseid]);
af25b8fc
DW
2178 } else if ($event->categoryid) {
2179 // If this is a category we need to be able to see the category.
2180 $cat = \coursecat::get($event->categoryid, IGNORE_MISSING);
2181 if (!$cat) {
2182 return false;
2183 }
2184 return true;
2185 } else if (!empty($event->courseid)) {
2186 // If it is a course event we need to be able to manage events in the course, or be in the course.
2187 if (has_capability('moodle/calendar:manageentries', $event->context)) {
2188 return true;
2189 }
2190 $mycourses = enrol_get_my_courses('id');
2191 return isset($mycourses[$event->courseid]);
2192 } else if ($event->userid) {
2193 if ($event->userid != $USER->id) {
2194 // No-one can ever see another users events.
2195 return false;
2196 }
2197 return true;
2198 } else {
2199 throw new moodle_exception('unknown event type');
2200 }
2201
2202 return false;
2203}
10515e15
MN
2204
2205/**
2206 * Return the capability for editing calendar event.
2207 *
2208 * @param calendar_event $event event object
909d0858 2209 * @param bool $manualedit is the event being edited manually by the user
10515e15
MN
2210 * @return bool capability to edit event
2211 */
909d0858 2212function calendar_edit_event_allowed($event, $manualedit = false) {
23a29de7
MN
2213 global $USER, $DB;
2214
2215 // Must be logged in.
2216 if (!isloggedin()) {
2217 return false;
2218 }
2219
2220 // Can not be using guest account.
2221 if (isguestuser()) {
2222 return false;
2223 }
2224
909d0858 2225 if ($manualedit && !empty($event->modulename)) {
39fe5929
RW
2226 $hascallback = component_callback_exists(
2227 'mod_' . $event->modulename,
2228 'core_calendar_event_timestart_updated'
2229 );
2230
2231 if (!$hascallback) {
2232 // If the activity hasn't implemented the correct callback
2233 // to handle changes to it's events then don't allow any
2234 // manual changes to them.
2235 return false;
2236 }
2237
2238 $coursemodules = get_fast_modinfo($event->courseid)->instances;
2239 $hasmodule = isset($coursemodules[$event->modulename]);
2240 $hasinstance = isset($coursemodules[$event->modulename][$event->instance]);
2241
2242 // If modinfo doesn't know about the module, return false to be safe.
2243 if (!$hasmodule || !$hasinstance) {
2244 return false;
2245 }
2246
2247 $coursemodule = $coursemodules[$event->modulename][$event->instance];
2248 $context = context_module::instance($coursemodule->id);
2249 // This is the capability that allows a user to modify the activity
2250 // settings. Since the activity generated this event we need to check
2251 // that the current user has the same capability before allowing them
2252 // to update the event because the changes to the event will be
2253 // reflected within the activity.
2254 return has_capability('moodle/course:manageactivities', $context);
909d0858
RW
2255 }
2256
23a29de7
MN
2257 // You cannot edit URL based calendar subscription events presently.
2258 if (!empty($event->subscriptionid)) {
2259 if (!empty($event->subscription->url)) {
2260 // This event can be updated externally, so it cannot be edited.
2261 return false;
2262 }
2263 }
2264
2265 $sitecontext = \context_system::instance();
2266
2267 // If user has manageentries at site level, return true.
2268 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2269 return true;
2270 }
2271
2272 // If groupid is set, it's definitely a group event.
2273 if (!empty($event->groupid)) {
2274 // Allow users to add/edit group events if -
2275 // 1) They have manageentries for the course OR
2276 // 2) They have managegroupentries AND are in the group.
2277 $group = $DB->get_record('groups', array('id' => $event->groupid));
2278 return $group && (
86679cb1
AN
2279 has_capability('moodle/calendar:manageentries', $event->context) ||
2280 (has_capability('moodle/calendar:managegroupentries', $event->context)
23a29de7
MN
2281 && groups_is_member($event->groupid)));
2282 } else if (!empty($event->courseid)) {
303d649a 2283 // If groupid is not set, but course is set, it's definitely a course event.
86679cb1 2284 return has_capability('moodle/calendar:manageentries', $event->context);
303d649a
AN
2285 } else if (!empty($event->categoryid)) {
2286 // If groupid is not set, but category is set, it's definitely a category event.
86679cb1 2287 return has_capability('moodle/calendar:manageentries', $event->context);
23a29de7
MN
2288 } else if (!empty($event->userid) && $event->userid == $USER->id) {
2289 // If course is not set, but userid id set, it's a user event.
86679cb1 2290 return (has_capability('moodle/calendar:manageownentries', $event->context));
23a29de7 2291 } else if (!empty($event->userid)) {
86679cb1 2292 return (has_capability('moodle/calendar:manageentries', $event->context));
23a29de7
MN
2293 }
2294
2295 return false;
10515e15
MN
2296}
2297
dadd6f9f
SL
2298/**
2299 * Return the capability for deleting a calendar event.
2300 *
2301 * @param calendar_event $event The event object
2302 * @return bool Whether the user has permission to delete the event or not.
2303 */
2304function calendar_delete_event_allowed($event) {
2305 // Only allow delete if you have capabilities and it is not an module event.
2306 return (calendar_edit_event_allowed($event) && empty($event->modulename));
2307}
2308
10515e15
MN
2309/**
2310 * Returns the default courses to display on the calendar when there isn't a specific
2311 * course to display.
2312 *
a5327e44 2313 * @param int $courseid (optional) If passed, an additional course can be returned for admins (the current course).
01ed53df 2314 * @param string $fields Comma separated list of course fields to return.
bd870573 2315 * @param bool $canmanage If true, this will return the list of courses the user can create events in, rather
ed6d81c9
DW
2316 * than the list of courses they see events from (an admin can always add events in a course
2317 * calendar, even if they are not enrolled in the course).
bd870573
SR
2318 * @param int $userid (optional) The user which this function returns the default courses for.
2319 * By default the current user.
10515e15
MN
2320 * @return array $courses Array of courses to display
2321 */
bd870573
SR
2322function calendar_get_default_courses($courseid = null, $fields = '*', $canmanage = false, int $userid = null) {
2323 global $CFG, $USER;
23a29de7 2324
bd870573
SR
2325 if (!$userid) {
2326 if (!isloggedin()) {
2327 return array();
2328 }
2329 $userid = $USER->id;
23a29de7
MN
2330 }
2331
bd870573
SR
2332 if ((!empty($CFG->calendar_adminseesall) || $canmanage) &&
2333 has_capability('moodle/calendar:manageentries', context_system::instance(), $userid)) {
ed6d81c9 2334
01ed53df
DW
2335 // Add a c. prefix to every field as expected by get_courses function.
2336 $fieldlist = explode(',', $fields);
2337
2338 $prefixedfields = array_map(function($value) {
2339 return 'c.' . trim($value);
2340 }, $fieldlist);
2341 $courses = get_courses('all', 'c.shortname', implode(',', $prefixedfields));
a5327e44 2342 } else {
bd870573 2343 $courses = enrol_get_users_courses($userid, true, $fields);
23a29de7
MN
2344 }
2345
a5327e44 2346 if ($courseid && $courseid != SITEID) {
bd870573 2347 if (empty($courses[$courseid]) && has_capability('moodle/calendar:manageentries', context_system::instance(), $userid)) {
a5327e44
DW
2348 // Allow a site admin to see calendars from courses he is not enrolled in.
2349 // This will come from $COURSE.
2350 $courses[$courseid] = get_course($courseid);
2351 }
2352 }
23a29de7
MN
2353
2354 return $courses;
10515e15
MN
2355}
2356
2357/**
2358 * Get event format time.
2359 *
2360 * @param calendar_event $event event object
2361 * @param int $now current time in gmt
2362 * @param array $linkparams list of params for event link
2363 * @param bool $usecommonwords the words as formatted date/time.
2364 * @param int $showtime determine the show time GMT timestamp
2365 * @return string $eventtime link/string for event time
2366 */
2367function calendar_format_event_time($event, $now, $linkparams = null, $usecommonwords = true, $showtime = 0) {
23a29de7
MN
2368 $starttime = $event->timestart;
2369 $endtime = $event->timestart + $event->timeduration;
2370
2371 if (empty($linkparams) || !is_array($linkparams)) {
2372 $linkparams = array();
2373 }
2374
2375 $linkparams['view'] = 'day';
2376
2377 // OK, now to get a meaningful display.
2378 // Check if there is a duration for this event.
2379 if ($event->timeduration) {
2380 // Get the midnight of the day the event will start.
2381 $usermidnightstart = usergetmidnight($starttime);
2382 // Get the midnight of the day the event will end.
2383 $usermidnightend = usergetmidnight($endtime);
2384 // Check if we will still be on the same day.
2385 if ($usermidnightstart == $usermidnightend) {
2386 // Check if we are running all day.
2387 if ($event->timeduration == DAYSECS) {
2388 $time = get_string('allday', 'calendar');
2389 } else { // Specify the time we will be running this from.
2390 $datestart = calendar_time_representation($starttime);
2391 $dateend = calendar_time_representation($endtime);
2392 $time = $datestart . ' <strong>&raquo;</strong> ' . $dateend;
2393 }
2394
2395 // Set printable representation.
2396 if (!$showtime) {
2397 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2398 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2399 $eventtime = \html_writer::link($url, $day) . ', ' . $time;
2400 } else {
2401 $eventtime = $time;
2402 }
2403 } else { // It must spans two or more days.
2404 $daystart = calendar_day_representation($event->timestart, $now, $usecommonwords) . ', ';
2405 if ($showtime == $usermidnightstart) {
2406 $daystart = '';
2407 }
2408 $timestart = calendar_time_representation($event->timestart);
2409 $dayend = calendar_day_representation($event->timestart + $event->timeduration, $now, $usecommonwords) . ', ';
2410 if ($showtime == $usermidnightend) {
2411 $dayend = '';
2412 }
2413 $timeend = calendar_time_representation($event->timestart + $event->timeduration);
2414
2415 // Set printable representation.
2416 if ($now >= $usermidnightstart && $now < strtotime('+1 day', $usermidnightstart)) {
2417 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2418 $eventtime = $timestart . ' <strong>&raquo;</strong> ' . \html_writer::link($url, $dayend) . $timeend;
2419 } else {
2420 // The event is in the future, print start and end links.
2421 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2422 $eventtime = \html_writer::link($url, $daystart) . $timestart . ' <strong>&raquo;</strong> ';
2423
2424 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $endtime);
2425 $eventtime .= \html_writer::link($url, $dayend) . $timeend;
2426 }
2427 }
2428 } else { // There is no time duration.
2429 $time = calendar_time_representation($event->timestart);
2430 // Set printable representation.
2431 if (!$showtime) {
2432 $day = calendar_day_representation($event->timestart, $now, $usecommonwords);
2433 $url = calendar_get_link_href(new \moodle_url(CALENDAR_URL . 'view.php', $linkparams), 0, 0, 0, $starttime);
2434 $eventtime = \html_writer::link($url, $day) . ', ' . trim($time);
2435 } else {
2436 $eventtime = $time;
2437 }
2438 }
2439
2440 // Check if It has expired.
2441 if ($event->timestart + $event->timeduration < $now) {
2442 $eventtime = '<span class="dimmed_text">' . str_replace(' href=', ' class="dimmed" href=', $eventtime) . '</span>';
2443 }
2444
2445 return $eventtime;
10515e15
MN
2446}
2447
2448/**
2449 * Checks to see if the requested type of event should be shown for the given user.
2450 *
2451 * @param int $type The type to check the display for (default is to display all)
2452 * @param stdClass|int|null $user The user to check for - by default the current user
2453 * @return bool True if the tyep should be displayed false otherwise
2454 */
2455function calendar_show_event_type($type, $user = null) {
23a29de7
MN
2456 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP + CALENDAR_EVENT_USER;
2457
2458 if (get_user_preferences('calendar_persistflt', 0, $user) === 0) {
2459 global $SESSION;
2460 if (!isset($SESSION->calendarshoweventtype)) {
2461 $SESSION->calendarshoweventtype = $default;
2462 }
2463 return $SESSION->calendarshoweventtype & $type;
2464 } else {
2465 return get_user_preferences('calendar_savedflt', $default, $user) & $type;
2466 }
10515e15
MN
2467}
2468
2469/**
2470 * Sets the display of the event type given $display.
2471 *
2472 * If $display = true the event type will be shown.
2473 * If $display = false the event type will NOT be shown.
2474 * If $display = null the current value will be toggled and saved.
2475 *
2476 * @param int $type object of CALENDAR_EVENT_XXX
2477 * @param bool $display option to display event type
2478 * @param stdClass|int $user moodle user object or id, null means current user
2479 */
2480function calendar_set_event_type_display($type, $display = null, $user = null) {
23a29de7 2481 $persist = get_user_preferences('calendar_persistflt', 0, $user);
05f184bb
AN
2482 $default = CALENDAR_EVENT_GLOBAL + CALENDAR_EVENT_COURSE + CALENDAR_EVENT_GROUP
2483 + CALENDAR_EVENT_USER + CALENDAR_EVENT_COURSECAT;
23a29de7
MN
2484 if ($persist === 0) {
2485 global $SESSION;
2486 if (!isset($SESSION->calendarshoweventtype)) {
2487 $SESSION->calendarshoweventtype = $default;
2488 }
2489 $preference = $SESSION->calendarshoweventtype;
2490 } else {
2491 $preference = get_user_preferences('calendar_savedflt', $default, $user);
2492 }
2493 $current = $preference & $type;
2494 if ($display === null) {
2495 $display = !$current;
2496 }
2497 if ($display && !$current) {
2498 $preference += $type;
2499 } else if (!$display && $current) {
2500 $preference -= $type;
2501 }
2502 if ($persist === 0) {
2503 $SESSION->calendarshoweventtype = $preference;
2504 } else {
2505 if ($preference == $default) {
2506 unset_user_preference('calendar_savedflt', $user);
2507 } else {
2508 set_user_preference('calendar_savedflt', $preference, $user);
2509 }
2510 }
10515e15
MN
2511}
2512
2513/**
2514 * Get calendar's allowed types.
2515 *
2516 * @param stdClass $allowed list of allowed edit for event type
2517 * @param stdClass|int $course object of a course or course id
aa091225 2518 * @param array $groups array of groups for the given course
05f184bb 2519 * @param stdClass|int $category object of a category
10515e15 2520 */
05f184bb 2521function calendar_get_allowed_types(&$allowed, $course = null, $groups = null, $category = null) {
23a29de7
MN
2522 global $USER, $DB;
2523
2524 $allowed = new \stdClass();
2525 $allowed->user = has_capability('moodle/calendar:manageownentries', \context_system::instance());
2526 $allowed->groups = false;
2527 $allowed->courses = false;
05f184bb 2528 $allowed->categories = false;
23a29de7 2529 $allowed->site = has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID));
aa091225
RW
2530 $getgroupsfunc = function($course, $context, $user) use ($groups) {
2531 if ($course->groupmode != NOGROUPS || !$course->groupmodeforce) {
2532 if (has_capability('moodle/site:accessallgroups', $context)) {
2533 return is_null($groups) ? groups_get_all_groups($course->id) : $groups;
2534 } else {
2535 if (is_null($groups)) {
2536 return groups_get_all_groups($course->id, $user->id);
2537 } else {
2538 return array_filter($groups, function($group) use ($user) {
2539 return isset($group->members[$user->id]);
2540 });
2541 }
2542 }
2543 }
2544
2545 return false;
2546 };
23a29de7
MN
2547
2548 if (!empty($course)) {
2549 if (!is_object($course)) {
2dc93a37 2550 $course = $DB->get_record('course', array('id' => $course), 'id, groupmode, groupmodeforce', MUST_EXIST);
23a29de7
MN
2551 }
2552 if ($course->id != SITEID) {
2553 $coursecontext = \context_course::instance($course->id);
2554 $allowed->user = has_capability('moodle/calendar:manageownentries', $coursecontext);
2555
2556 if (has_capability('moodle/calendar:manageentries', $coursecontext)) {
2557 $allowed->courses = array($course->id => 1);
aa091225 2558 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
23a29de7 2559 } else if (has_capability('moodle/calendar:managegroupentries', $coursecontext)) {
aa091225
RW
2560 $allowed->groups = $getgroupsfunc($course, $coursecontext, $USER);
2561 }
2562 }
2563 }
05f184bb
AN
2564
2565 if (!empty($category)) {
2566 $catcontext = \context_coursecat::instance($category->id);
2567 if (has_capability('moodle/category:manage', $catcontext)) {
2568 $allowed->categories = [$category->id => 1];
2569 }
2570 }
aa091225
RW
2571}
2572
10515e15
MN
2573/**
2574 * See if user can add calendar entries at all used to print the "New Event" button.
2575 *
2576 * @param stdClass $course object of a course or course id
2577 * @return bool has the capability to add at least one event type
2578 */
2579function calendar_user_can_add_event($course) {
23a29de7
MN
2580 if (!isloggedin() || isguestuser()) {
2581 return false;
2582 }
2583
2584 calendar_get_allowed_types($allowed, $course);
2585
4e84059e 2586 return (bool)($allowed->user || $allowed->groups || $allowed->courses || $allowed->categories || $allowed->site);
10515e15
MN
2587}
2588
2589/**
2590 * Check wether the current user is permitted to add events.
2591 *
2592 * @param stdClass $event object of event
2593 * @return bool has the capability to add event
2594 */
2595function calendar_add_event_allowed($event) {
23a29de7
MN
2596 global $USER, $DB;
2597
2598 // Can not be using guest account.
2599 if (!isloggedin() or isguestuser()) {
2600 return false;
2601 }
2602
2603 $sitecontext = \context_system::instance();
2604
2605 // If user has manageentries at site level, always return true.
2606 if (has_capability('moodle/calendar:manageentries', $sitecontext)) {
2607 return true;
2608 }
2609
2610 switch ($event->eventtype) {
05f184bb
AN
2611 case 'category':
2612 return has_capability('moodle/category:manage', $event->context);
23a29de7
MN
2613 case 'course':
2614 return has_capability('moodle/calendar:manageentries', $event->context);
2615 case 'group':
2616 // Allow users to add/edit group events if -
2617 // 1) They have manageentries (= entries for whole course).
2618 // 2) They have managegroupentries AND are in the group.
2619 $group = $DB->get_record('groups', array('id' => $event->groupid));
2620 return $group && (
2621 has_capability('moodle/calendar:manageentries', $event->context) ||
2622 (has_capability('moodle/calendar:managegroupentries', $event->context)
2623 && groups_is_member($event->groupid)));
2624 case 'user':
2625 if ($event->userid == $USER->id) {
2626 return (has_capability('moodle/calendar:manageownentries', $event->context));
2627 }
2628 // There is intentionally no 'break'.
2629 case 'site':
2630 return has_capability('moodle/calendar:manageentries', $event->context);
2631 default:
2632 return has_capability('moodle/calendar:manageentries', $event->context);
2633 }
10515e15
MN
2634}
2635
2636/**
2637 * Returns option list for the poll interval setting.
2638 *
2639 * @return array An array of poll interval options. Interval => description.
2640 */
2641function calendar_get_pollinterval_choices() {
23a29de7
MN
2642 return array(
2643 '0' => new \lang_string('never', 'calendar'),
2644 HOURSECS => new \lang_string('hourly', 'calendar'),
2645 DAYSECS => new \lang_string('daily', 'calendar'),
2646 WEEKSECS => new \lang_string('weekly', 'calendar'),
2647 '2628000' => new \lang_string('monthly', 'calendar'),
2648 YEARSECS => new \lang_string('annually', 'calendar')
2649 );
10515e15
MN
2650}
2651
2652/**
2653 * Returns option list of available options for the calendar event type, given the current user and course.
2654 *
2655 * @param int $courseid The id of the course
2656 * @return array An array containing the event types the user can create.
2657 */
2658function calendar_get_eventtype_choices($courseid) {
23a29de7
MN
2659 $choices = array();
2660 $allowed = new \stdClass;
2661 calendar_get_allowed_types($allowed, $courseid);
2662
2663 if ($allowed->user) {
2664 $choices['user'] = get_string('userevents', 'calendar');
2665 }
2666 if ($allowed->site) {
2667 $choices['site'] = get_string('siteevents', 'calendar');
2668 }
2669 if (!empty($allowed->courses)) {
2670 $choices['course'] = get_string('courseevents', 'calendar');
2671 }
05f184bb
AN
2672 if (!empty($allowed->categories)) {
2673 $choices['category'] = get_string('categoryevents', 'calendar');
2674 }
23a29de7
MN
2675 if (!empty($allowed->groups) and is_array($allowed->groups)) {
2676 $choices['group'] = get_string('group');
2677 }
2678
2679 return array($choices, $allowed->groups);
10515e15
MN
2680}
2681
2682/**
2683 * Add an iCalendar subscription to the database.
2684 *
2685 * @param stdClass $sub The subscription object (e.g. from the form)
2686 * @return int The insert ID, if any.
2687 */
2688function calendar_add_subscription($sub) {
23a29de7
MN
2689 global $DB, $USER, $SITE;
2690
b9fd5164
AN
2691 // Undo the form definition work around to allow us to have two different
2692 // course selectors present depending on which event type the user selects.
2693 if (!empty($sub->groupcourseid)) {
2694 $sub->courseid = $sub->groupcourseid;
2695 unset($sub->groupcourseid);
2696 }
2697
2698 // Pull the group id back out of the value. The form saves the value
2699 // as "<courseid>-<groupid>" to allow the javascript to work correctly.
2700 if (!empty($sub->groupid)) {
2701 list($courseid, $groupid) = explode('-', $sub->groupid);
2702 $sub->courseid = $courseid;
2703 $sub->groupid = $groupid;
2704 }
2705
2706 // Default course id if none is set.
2707 if (empty($sub->courseid)) {
2708 if ($sub->eventtype === 'site') {
2709 $sub->courseid = SITEID;
2710 } else {
2711 $sub->courseid = 0;
2712 }
2713 }
2714
23a29de7
MN
2715 if ($sub->eventtype === 'site') {
2716 $sub->courseid = $SITE->id;
2717 } else if ($sub->eventtype === 'group' || $sub->eventtype === 'course') {
b9fd5164 2718 $sub->courseid = $sub->courseid;
05f184bb 2719 } else if ($sub->eventtype === 'category') {
b9fd5164 2720 $sub->categoryid = $sub->categoryid;
23a29de7
MN
2721 } else {
2722 // User events.
2723 $sub->courseid = 0;
2724 }
2725 $sub->userid = $USER->id;
2726
2727 // File subscriptions never update.
2728 if (empty($sub->url)) {
2729 $sub->pollinterval = 0;
2730 }
2731
2732 if (!empty($sub->name)) {
2733 if (empty($sub->id)) {
2734 $id = $DB->insert_record('event_subscriptions', $sub);
2735 // We cannot cache the data here because $sub is not complete.
2736 $sub->id = $id;
2737 // Trigger event, calendar subscription added.
2738 $eventparams = array('objectid' => $sub->id,
2739 'context' => calendar_get_calendar_context($sub),
b9fd5164
AN
2740 'other' => array(
2741 'eventtype' => $sub->eventtype,
2742 )
23a29de7 2743 );
b9fd5164
AN
2744 switch ($sub->eventtype) {
2745 case 'category':
2746 $eventparams['other']['categoryid'] = $sub->categoryid;
2747 break;
2748 case 'course':
2749 $eventparams['other']['courseid'] = $sub->courseid;
2750 break;
2751 case 'group':
2752 $eventparams['other']['courseid'] = $sub->courseid;
2753 $eventparams['other']['groupid'] = $sub->groupid;
2754 break;
2755 default:
2756 $eventparams['other']['courseid'] = $sub->courseid;
2757 }
2758
23a29de7
MN
2759 $event = \core\event\calendar_subscription_created::create($eventparams);
2760 $event->trigger();
2761 return $id;
2762 } else {
2763 // Why are we doing an update here?
2764 calendar_update_subscription($sub);
2765 return $sub->id;
2766 }
2767 } else {
2768 print_error('errorbadsubscription', 'importcalendar');
2769 }
10515e15
MN
2770}
2771
2772/**
2773 * Add an iCalendar event to the Moodle calendar.
2774 *
2775 * @param stdClass $event The RFC-2445 iCalendar event
b9fd5164 2776 * @param int $unused Deprecated
10515e15
MN
2777 * @param int $subscriptionid The iCalendar subscription ID
2778 * @param string $timezone The X-WR-TIMEZONE iCalendar property if provided
2779 * @throws dml_exception A DML specific exception is thrown for invalid subscriptionids.
2780 * @return int Code: CALENDAR_IMPORT_EVENT_UPDATED = updated, CALENDAR_IMPORT_EVENT_INSERTED = inserted, 0 = error
2781 */
b9fd5164 2782function calendar_add_icalendar_event($event, $unused = null, $subscriptionid, $timezone='UTC') {
23a29de7
MN
2783 global $DB;
2784
2785 // Probably an unsupported X-MICROSOFT-CDO-BUSYSTATUS event.
2786 if (empty($event->properties['SUMMARY'])) {
2787 return 0;
2788 }
2789
2790 $name = $event->properties['SUMMARY'][0]->value;
2791 $name = str_replace('\n', '<br />', $name);
2792 $name = str_replace('\\', '', $name);
2793 $name = preg_replace('/\s+/u', ' ', $name);
2794
2795 $eventrecord = new \stdClass;
2796 $eventrecord->name = clean_param($name, PARAM_NOTAGS);
2797
2798 if (empty($event->properties['DESCRIPTION'][0]->value)) {
2799 $description = '';
2800 } else {
2801 $description = $event->properties['DESCRIPTION'][0]->value;
2802 $description = clean_param($description, PARAM_NOTAGS);
2803 $description = str_replace('\n', '<br />', $description);
2804 $description = str_replace('\\', '', $description);
2805 $description = preg_replace('/\s+/u', ' ', $description);
2806 }
2807 $eventrecord->description = $description;
2808
2809 // Probably a repeating event with RRULE etc. TODO: skip for now.
2810 if (empty($event->properties['DTSTART'][0]->value)) {
2811 return 0;
2812 }
2813
2814 if (isset($event->properties['DTSTART'][0]->parameters['TZID'])) {
2815 $tz = $event->properties['DTSTART'][0]->parameters['TZID'];
2816 } else {
2817 $tz = $timezone;
2818 }
2819 $tz = \core_date::normalise_timezone($tz);
2820 $eventrecord->timestart = strtotime($event->properties['DTSTART'][0]->value . ' ' . $tz);
2821 if (empty($event->properties['DTEND'])) {
2822 $eventrecord->timeduration = 0; // No duration if no end time specified.
2823 } else {
2824 if (isset($event->properties['DTEND'][0]->parameters['TZID'])) {
2825 $endtz = $event->properties['DTEND'][0]->parameters['TZID'];
2826 } else {
2827 $endtz = $timezone;
2828 }
2829 $endtz = \core_date::normalise_timezone($endtz);
2830 $eventrecord->timeduration = strtotime($event->properties['DTEND'][0]->value . ' ' . $endtz) - $eventrecord->timestart;
2831 }
2832
2833 // Check to see if it should be treated as an all day event.
2834 if ($eventrecord->timeduration == DAYSECS) {
2835 // Check to see if the event started at Midnight on the imported calendar.
2836 date_default_timezone_set($timezone);
2837 if (date('H:i:s', $eventrecord->timestart) === "00:00:00") {
8aaba9e4
AA
2838 // This event should be an all day event. This is not correct, we don't do anything differently for all day events.
2839 // See MDL-56227.
23a29de7
MN
2840 $eventrecord->timeduration = 0;
2841 }
2842 \core_date::set_default_server_timezone();
2843 }
2844
ef4e04ee
MH
2845 $eventrecord->location = empty($event->properties['LOCATION'][0]->value) ? '' :
2846 str_replace('\\', '', $event->properties['LOCATION'][0]->value);
23a29de7
MN
2847 $eventrecord->uuid = $event->properties['UID'][0]->value;
2848 $eventrecord->timemodified = time();
2849
2850 // Add the iCal subscription details if required.
2851 // We should never do anything with an event without a subscription reference.
2852 $sub = calendar_get_subscription($subscriptionid);
2853 $eventrecord->subscriptionid = $subscriptionid;
2854 $eventrecord->userid = $sub->userid;
2855 $eventrecord->groupid = $sub->groupid;
2856 $eventrecord->courseid = $sub->courseid;
b9fd5164 2857 $eventrecord->categoryid = $sub->categoryid;
23a29de7
MN
2858 $eventrecord->eventtype = $sub->eventtype;
2859
2860 if ($updaterecord = $DB->get_record('event', array('uuid' => $eventrecord->uuid,
2861 'subscriptionid' => $eventrecord->subscriptionid))) {
2862 $eventrecord->id = $updaterecord->id;
2863 $return = CALENDAR_IMPORT_EVENT_UPDATED; // Update.
2864 } else {
2865 $return = CALENDAR_IMPORT_EVENT_INSERTED; // Insert.
2866 }
2867 if ($createdevent = \calendar_event::create($eventrecord, false)) {
2868 if (!empty($event->properties['RRULE'])) {
2869 // Repeating events.
2870 date_default_timezone_set($tz); // Change time zone to parse all events.
c9d775fc 2871 $rrule = new \core_calendar\rrule_manager($event->properties['RRULE'][0]->value);
23a29de7
MN
2872 $rrule->parse_rrule();
2873 $rrule->create_events($createdevent);
2874 \core_date::set_default_server_timezone(); // Change time zone back to what it was.
2875 }
2876 return $return;
2877 } else {
2878 return 0;
2879 }
10515e15
MN
2880}
2881
2882/**
2883 * Update a subscription from the form data in one of the rows in the existing subscriptions table.
2884 *
2885 * @param int $subscriptionid The ID of the subscription we are acting upon.
2886 * @param int $pollinterval The poll interval to use.
2887 * @param int $action The action to be performed. One of update or remove.
2888 * @throws dml_exception if invalid subscriptionid is provided
2889 * @return string A log of the import progress, including errors
2890 */
2891function calendar_process_subscription_row($subscriptionid, $pollinterval, $action) {
23a29de7
MN
2892 // Fetch the subscription from the database making sure it exists.
2893 $sub = calendar_get_subscription($subscriptionid);
2894
2895 // Update or remove the subscription, based on action.
2896 switch ($action) {
2897 case CALENDAR_SUBSCRIPTION_UPDATE:
2898 // Skip updating file subscriptions.
2899 if (empty($sub->url)) {
2900 break;
2901 }
2902 $sub->pollinterval = $pollinterval;
2903 calendar_update_subscription($sub);
2904
2905 // Update the events.
2906 return "<p>" . get_string('subscriptionupdated', 'calendar', $sub->name) . "</p>" .
2907 calendar_update_subscription_events($subscriptionid);
2908 case CALENDAR_SUBSCRIPTION_REMOVE:
2909 calendar_delete_subscription($subscriptionid);
2910 return get_string('subscriptionremoved', 'calendar', $sub->name);
2911 break;
2912 default:
2913 break;
2914 }
2915 return '';
10515e15
MN
2916}
2917
2918/**
2919 * Delete subscription and all related events.
2920 *
2921 * @param int|stdClass $subscription subscription or it's id, which needs to be deleted.
2922 */
2923function calendar_delete_subscription($subscription) {
23a29de7
MN
2924 global $DB;
2925
2926 if (!is_object($subscription)) {
2927 $subscription = $DB->get_record('event_subscriptions', array('id' => $subscription), '*', MUST_EXIST);
2928 }
2929
2930 // Delete subscription and related events.
2931 $DB->delete_records('event', array('subscriptionid' => $subscription->id));
2932 $DB->delete_records('event_subscriptions', array('id' => $subscription->id));
2933 \cache_helper::invalidate_by_definition('core', 'calendar_subscriptions', array(), array($subscription->id));
2934
2935 // Trigger event, calendar subscription deleted.
2936 $eventparams = array('objectid' => $subscription->id,
2937 'context' => calendar_get_calendar_context($subscription),
b9fd5164
AN
2938 'other' => array(
2939 'eventtype' => $subscription->eventtype,
2940 )
23a29de7 2941 );
b9fd5164
AN
2942 switch ($subscription->eventtype) {
2943 case 'category':
2944 $eventparams['other']['categoryid'] = $subscription->categoryid;
2945 break;
2946 case 'course':
2947 $eventparams['other']['courseid'] = $subscription->courseid;
2948 break;
2949 case 'group':
2950 $eventparams['other']['courseid'] = $subscription->courseid;
2951 $eventparams['other']['groupid'] = $subscription->groupid;
2952 break;
2953 default:
2954 $eventparams['other']['courseid'] = $subscription->courseid;
2955 }
23a29de7
MN
2956 $event = \core\event\calendar_subscription_deleted::create($eventparams);
2957 $event->trigger();
10515e15
MN
2958}
2959
2960/**
2961 * From a URL, fetch the calendar and return an iCalendar object.
2962 *
2963 * @param string $url The iCalendar URL
2964 * @return iCalendar The iCalendar object
2965 */
2966function calendar_get_icalendar($url) {
23a29de7
MN
2967 global $CFG;
2968
2969 require_once($CFG->libdir . '/filelib.php');
2970
2971 $curl = new \curl();
2972 $curl->setopt(array('CURLOPT_FOLLOWLOCATION' => 1, 'CURLOPT_MAXREDIRS' => 5));
2973 $calendar = $curl->get($url);
2974
2975 // Http code validation should actually be the job of curl class.
2976 if (!$calendar || $curl->info['http_code'] != 200 || !empty($curl->errorno)) {
2977 throw new \moodle_exception('errorinvalidicalurl', 'calendar');
2978 }
2979
2980 $ical = new \iCalendar();
2981 $ical->unserialize($calendar);
2982
2983 return $ical;
10515e15
MN
2984}
2985
2986/**
2987 * Import events from an iCalendar object into a course calendar.
2988 *
2989 * @param iCalendar $ical The iCalendar object.
2990 * @param int $courseid The course ID for the calendar.
2991 * @param int $subscriptionid The subscription ID.
2992 * @return string A log of the import progress, including errors.
2993 */
b9fd5164 2994function calendar_import_icalendar_events($ical, $unused = null, $subscriptionid = null) {
23a29de7
MN
2995 global $DB;
2996
2997 $return = '';
2998 $eventcount = 0;
2999 $updatecount = 0;
3000
3001 // Large calendars take a while...
3002 if (!CLI_SCRIPT) {
3003 \core_php_time_limit::raise(300);
3004 }
3005
3006 // Mark all events in a subscription with a zero timestamp.
3007 if (!empty($subscriptionid)) {
3008 $sql = "UPDATE {event} SET timemodified = :time WHERE subscriptionid = :id";
3009 $DB->execute($sql, array('time' => 0, 'id' => $subscriptionid));
3010 }
3011
3012 // Grab the timezone from the iCalendar file to be used later.
3013 if (isset($ical->properties['X-WR-TIMEZONE'][0]->value)) {
3014 $timezone = $ical->properties['X-WR-TIMEZONE'][0]->value;
3015 } else {
3016 $timezone = 'UTC';
3017 }
3018
3019 $return = '';
3020 foreach ($ical->components['VEVENT'] as $event) {
b9fd5164 3021 $res = calendar_add_icalendar_event($event, null, $subscriptionid, $timezone);
23a29de7
MN
3022 switch ($res) {
3023 case CALENDAR_IMPORT_EVENT_UPDATED:
3024 $updatecount++;
3025 break;
3026 case CALENDAR_IMPORT_EVENT_INSERTED:
3027 $eventcount++;
3028 break;
3029 case 0:
3030 $return .= '<p>' . get_string('erroraddingevent', 'calendar') . ': ';
3031 if (empty($event->properties['SUMMARY'])) {
3032 $return .= '(' . get_string('notitle', 'calendar') . ')';
3033 } else {
3034 $return .= $event->properties['SUMMARY'][0]->value;
3035 }
3036 $return .= "</p>\n";
3037 break;
3038 }
3039 }
3040
3041 $return .= "<p>" . get_string('eventsimported', 'calendar', $eventcount) . "</p> ";
3042 $return .= "<p>" . get_string('eventsupdated', 'calendar', $updatecount) . "</p>";
3043
3044 // Delete remaining zero-marked events since they're not in remote calendar.
3045 if (!empty($subscriptionid)) {
3046 $deletecount = $DB->count_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3047 if (!empty($deletecount)) {
3048 $DB->delete_records('event', array('timemodified' => 0, 'subscriptionid' => $subscriptionid));
3049 $return .= "<p> " . get_string('eventsdeleted', 'calendar') . ": {$deletecount} </p>\n";
3050 }
3051 }
3052
3053 return $return;
10515e15
MN
3054}
3055
3056/**
3057 * Fetch a calendar subscription and update the events in the calendar.
3058 *
3059 * @param int $subscriptionid The course ID for the calendar.
3060 * @return string A log of the import progress, including errors.
3061 */
3062function calendar_update_subscription_events($subscriptionid) {
23a29de7
MN
3063 $sub = calendar_get_subscription($subscriptionid);
3064
3065 // Don't update a file subscription.
3066 if (empty($sub->url)) {
3067 return 'File subscription not updated.';
3068 }
3069
3070 $ical = calendar_get_icalendar($sub->url);
b9fd5164 3071 $return = calendar_import_icalendar_events($ical, null, $subscriptionid);
23a29de7
MN
3072 $sub->lastupdated = time();
3073
3074 calendar_update_subscription($sub);
3075
3076 return $return;
10515e15
MN
3077}
3078
3079/**
3080 * Update a calendar subscription. Also updates the associated cache.
3081 *
3082 * @param stdClass|array $subscription Subscription record.
3083 * @throws coding_exception If something goes wrong
3084 * @since Moodle 2.5
3085 */
3086function calendar_update_subscription($subscription) {
23a29de7
MN
3087 global $DB;
3088
3089 if (is_array($subscription)) {
3090 $subscription = (object)$subscription;
3091 }
3092 if (empty($subscription->id) || !$DB->record_exists('event_subscriptions', array('id' => $subscription->id))) {
3093 throw new \coding_exception('Cannot update a subscription without a valid id');
3094 }
3095
3096 $DB->update_record('event_subscriptions', $subscription);
3097
3098 // Update cache.
3099 $cache = \cache::make('core', 'calendar_subscriptions');
3100 $cache->set($subscription->id, $subscription);
3101
3102 // Trigger event, calendar subscription updated.
3103 $eventparams = array('userid' => $subscription->userid,
3104 'objectid' => $subscription->id,
3105 'context' => calendar_get_calendar_context($subscription),
b9fd5164
AN
3106 'other' => array(
3107 'eventtype' => $subscription->eventtype,
3108 )
23a29de7 3109 );
b9fd5164
AN
3110 switch ($subscription->eventtype) {
3111 case 'category':
3112 $eventparams['other']['categoryid'] = $subscription->categoryid;
3113 break;
3114 case 'course':
3115 $eventparams['other']['courseid'] = $subscription->courseid;
3116 break;
3117 case 'group':
3118 $eventparams['other']['courseid'] = $subscription->courseid;
3119 $eventparams['other']['groupid'] = $subscription->groupid;
3120 break;
3121 default:
3122 $eventparams['other']['courseid'] = $subscription->courseid;
3123 }
23a29de7
MN
3124 $event = \core\event\calendar_subscription_updated::create($eventparams);
3125 $event->trigger();
10515e15
MN
3126}
3127
3128/**
3129 * Checks to see if the user can edit a given subscription feed.
3130 *
3131 * @param mixed $subscriptionorid Subscription object or id
3132 * @return bool true if current user can edit the subscription else false
3133 */
3134function calendar_can_edit_subscription($subscriptionorid) {
23a29de7
MN
3135 if (is_array($subscriptionorid)) {
3136 $subscription = (object)$subscriptionorid;
3137 } else if (is_object($subscriptionorid)) {
3138 $subscription = $subscriptionorid;
3139 } else {
3140 $subscription = calendar_get_subscription($subscriptionorid);
3141 }
3142
3143 $allowed = new \stdClass;
3144 $courseid = $subscription->courseid;
b9fd5164 3145 $categoryid = $subscription->categoryid;
23a29de7 3146 $groupid = $subscription->groupid;
b9fd5164 3147 $category = null;
23a29de7 3148
b9fd5164
AN
3149 if (!empty($categoryid)) {
3150 $category = \coursecat::get($categoryid);
3151 }
3152 calendar_get_allowed_types($allowed, $courseid, null, $category);
23a29de7
MN
3153 switch ($subscription->eventtype) {
3154 case 'user':
3155 return $allowed->user;
3156 case 'course':
3157 if (isset($allowed->courses[$courseid])) {
3158 return $allowed->courses[$courseid];
3159 } else {
3160 return false;
3161 }
b9fd5164
AN
3162 case 'category':
3163 if (isset($allowed->categories[$categoryid])) {
3164 return $allowed->categories[$categoryid];
3165 } else {
3166 return false;
3167 }
23a29de7
MN
3168 case 'site':
3169 return $allowed->site;
3170 case 'group':
3171 if (isset($allowed->groups[$groupid])) {
3172 return $allowed->groups[$groupid];
3173 } else {
3174 return false;
3175 }
3176 default:
3177 return false;
3178 }
10515e15
MN
3179}
3180
3181/**
3182 * Helper function to determine the context of a calendar subscription.
3183 * Subscriptions can be created in two contexts COURSE, or USER.
3184 *
3185 * @param stdClass $subscription
3186 * @return context instance
3187 */
3188function calendar_get_calendar_context($subscription) {
23a29de7
MN
3189 // Determine context based on calendar type.
3190 if ($subscription->eventtype === 'site') {
3191 $context = \context_course::instance(SITEID);
3192 } else if ($subscription->eventtype === 'group' || $subscription->eventtype === 'course') {
3193 $context = \context_course::instance($subscription->courseid);
3194 } else {
3195 $context = \context_user::instance($subscription->userid);
3196 }
3197 return $context;
10515e15
MN
3198}
3199
6e65554e
MG
3200/**
3201 * Implements callback user_preferences, whitelists preferences that users are allowed to update directly
3202 *
3203 * Used in {@see core_user::fill_preferences_cache()}, see also {@see useredit_update_user_preference()}
3204 *
3205 * @return array
3206 */
3207function core_calendar_user_preferences() {
3208 $preferences = [];
3209 $preferences['calendar_timeformat'] = array('type' => PARAM_NOTAGS, 'null' => NULL_NOT_ALLOWED, 'default' => '0',
3210 'choices' => array('0', CALENDAR_TF_12, CALENDAR_TF_24)
3211 );
3212 $preferences['calendar_startwday'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3213 'choices' => array(0, 1, 2, 3, 4, 5, 6));
3214 $preferences['calendar_maxevents'] = array('type' => PARAM_INT, 'choices' => range(1, 20));
3215 $preferences['calendar_lookahead'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 365,
3216 'choices' => array(365, 270, 180, 150, 120, 90, 60, 30, 21, 14, 7, 6, 5, 4, 3, 2, 1));
3217 $preferences['calendar_persistflt'] = array('type' => PARAM_INT, 'null' => NULL_NOT_ALLOWED, 'default' => 0,
3218 'choices' => array(0, 1));
3219 return $preferences;
663640f5 3220}
22753c8c
JP
3221
3222/**
3223 * Get legacy calendar events
3224 *
3225 * @param int $tstart Start time of time range for events
3226 * @param int $tend End time of time range for events
3227 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
3228 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
3229 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
3230 * @param boolean $withduration whether only events starting within time range selected
3231 * or events in progress/already started selected as well
3232 * @param boolean $ignorehidden whether to select only visible events or all events
10c17dcc 3233 * @param array $categories array of category ids and/or objects.
22753c8c
JP
3234 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
3235 */
0085b0ea
AN
3236function calendar_get_legacy_events($tstart, $tend, $users, $groups, $courses,
3237 $withduration = true, $ignorehidden = true, $categories = []) {
22753c8c
JP
3238 // Normalise the users, groups and courses parameters so that they are compliant with \core_calendar\local\api::get_events().
3239 // Existing functions that were using the old calendar_get_events() were passing a mixture of array, int, boolean for these
3240 // parameters, but with the new API method, only null and arrays are accepted.
0085b0ea 3241 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
22753c8c
JP
3242 // If parameter is true, return null.
3243 if ($param === true) {
3244 return null;
3245 }
3246
3247 // If parameter is false, return an empty array.
3248 if ($param === false) {
3249 return [];
3250 }
3251
3252 // If the parameter is a scalar value, enclose it in an array.
3253 if (!is_array($param)) {
3254 return [$param];
3255 }
3256
3257 // No normalisation required.
3258 return $param;
0085b0ea 3259 }, [$users, $groups, $courses, $categories]);
22753c8c
JP
3260
3261 $mapper = \core_calendar\local\event\container::get_event_mapper();
3262 $events = \core_calendar\local\api::get_events(
3263 $tstart,
3264 $tend,
3265 null,
3266 null,
3267 null,
3268 null,
3269 40,
3270 null,
3271 $userparam,
3272 $groupparam,
3273 $courseparam,
0085b0ea 3274 $categoryparam,
22753c8c
JP
3275 $withduration,
3276 $ignorehidden
3277 );
3278
3279 return array_reduce($events, function($carry, $event) use ($mapper) {
3280 return $carry + [$event->get_id() => $mapper->from_event_to_stdclass($event)];
3281 }, []);
3282}
aa091225 3283
64ff737a
AN
3284
3285/**
836aa3f6 3286 * Get the calendar view output.
64ff737a
AN
3287 *
3288 * @param \calendar_information $calendar The calendar being represented
fee025ec
AN
3289 * @param string $view The type of calendar to have displayed
3290 * @param bool $includenavigation Whether to include navigation
7884ecf2 3291 * @param bool $skipevents Whether to load the events or not
64ff737a
AN
3292 * @return array[array, string]
3293 */
7884ecf2 3294function calendar_get_view(\calendar_information $calendar, $view, $includenavigation = true, bool $skipevents = false) {
a4af4c96 3295 global $PAGE, $CFG;
64ff737a
AN
3296
3297 $renderer = $PAGE->get_renderer('core_calendar');
3298 $type = \core_calendar\type_factory::get_calendar_instance();
3299
3300 // Calculate the bounds of the month.
5a11e7f5
SL
3301 $calendardate = $type->timestamp_to_date_array($calendar->time);
3302
3303 $date = new \DateTime('now', core_date::get_user_timezone_object(99));
349d3796 3304 $eventlimit = 200;
64ff737a
AN
3305
3306 if ($view === 'day') {
5a11e7f5
SL
3307 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday']);
3308 $date->setTimestamp($tstart);
3309 $date->modify('+1 day');
522b84be 3310 } else if ($view === 'upcoming' || $view === 'upcoming_mini') {
5a11e7f5 3311 // Number of days in the future that will be used to fetch events.
a4af4c96
SL
3312 if (isset($CFG->calendar_lookahead)) {
3313 $defaultlookahead = intval($CFG->calendar_lookahead);
3314 } else {
3315 $defaultlookahead = CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD;
3316 }
ca14f182 3317 $lookahead = get_user_preferences('calendar_lookahead', $defaultlookahead);
5a11e7f5
SL
3318
3319 // Maximum number of events to be displayed on upcoming view.
ca14f182
SL
3320 $defaultmaxevents = CALENDAR_DEFAULT_UPCOMING_MAXEVENTS;
3321 if (isset($CFG->calendar_maxevents)) {
3322 $defaultmaxevents = intval($CFG->calendar_maxevents);
3323 }
349d3796 3324 $eventlimit = get_user_preferences('calendar_maxevents', $defaultmaxevents);
5a11e7f5
SL
3325
3326 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], $calendardate['mday'],
3327 $calendardate['hours']);
3328 $date->setTimestamp($tstart);
3329 $date->modify('+' . $lookahead . ' days');
64ff737a 3330 } else {
5a11e7f5
SL
3331 $tstart = $type->convert_to_timestamp($calendardate['year'], $calendardate['mon'], 1);
3332 $monthdays = $type->get_num_days_in_month($calendardate['year'], $calendardate['mon']);
3333 $date->setTimestamp($tstart);
3334 $date->modify('+' . $monthdays . ' days');
3335
6038d626 3336 if ($view === 'mini' || $view === 'minithree') {
c8b6e9ab
AN
3337 $template = 'core_calendar/calendar_mini';
3338 } else {
3339 $template = 'core_calendar/calendar_month';
3340 }
64ff737a
AN
3341 }
3342
5a11e7f5
SL
3343 // We need to extract 1 second to ensure that we don't get into the next day.
3344 $date->modify('-1 second');
3345 $tend = $date->getTimestamp();
3346
0085b0ea 3347 list($userparam, $groupparam, $courseparam, $categoryparam) = array_map(function($param) {
64ff737a
AN
3348 // If parameter is true, return null.
3349 if ($param === true) {
3350 return null;
3351 }
3352
3353 // If parameter is false, return an empty array.
3354 if ($param === false) {
3355 return [];
3356 }
3357
3358 // If the parameter is a scalar value, enclose it in an array.
3359 if (!is_array($param)) {
3360 return [$param];
3361 }
3362
3363 // No normalisation required.
3364 return $param;
0085b0ea 3365 }, [$calendar->users, $calendar->groups, $calendar->courses, $calendar->categories]);
64ff737a 3366
7884ecf2
RW
3367 if ($skipevents) {
3368 $events = [];
3369 } else {
3370 $events = \core_calendar\local\api::get_events(
3371 $tstart,
3372 $tend,
3373 null,
3374 null,
3375 null,
3376 null,
3377 $eventlimit,
3378 null,
3379 $userparam,
3380 $groupparam,
3381 $courseparam,
3382 $categoryparam,
3383 true,
3384 true,
3385 function ($event) {
3386 if ($proxy = $event->get_course_module()) {
3387 $cminfo = $proxy->get_proxied_instance();
3388 return $cminfo->uservisible;
3389 }
93623513 3390
7884ecf2
RW
3391 if ($proxy = $event->get_category()) {
3392 $category = $proxy->get_proxied_instance();
64ff737a 3393
7884ecf2
RW
3394 return $category->is_uservisible();
3395 }
64ff737a 3396
7884ecf2
RW
3397 return true;
3398 }
3399 );
3400 }
64ff737a
AN
3401
3402 $related = [
3403 'events' => $events,
3404 'cache' => new \core_calendar\external\events_related_objects_cache($events),
146d3713 3405 'type' => $type,
64ff737a
AN
3406 ];
3407
146d3713 3408 $data = [];
c6022207 3409 if ($view == "month" || $view == "mini" || $view == "minithree") {
146d3713 3410 $month = new \core_calendar\external\month_exporter($calendar, $type, $related);
c6022207 3411 $month->set_includenavigation($includenavigation);
7884ecf2 3412 $month->set_initialeventsloaded(!$skipevents);
60908b21 3413 $month->set_showcoursefilter($view == "month");
146d3713
SL
3414 $data = $month->export($renderer);
3415 } else if ($view == "day") {
3ea4f446 3416 $day = new \core_calendar\external\calendar_day_exporter($calendar, $related);
146d3713 3417 $data = $day->export($renderer);
3ea4f446 3418 $template = 'core_calendar/calendar_day';
522b84be 3419 } else if ($view == "upcoming" || $view == "upcoming_mini") {
2ca4dc8a
SL
3420 $upcoming = new \core_calendar\external\calendar_upcoming_exporter($calendar, $related);
3421 $data = $upcoming->export($renderer);
522b84be
SL
3422
3423 if ($view == "upcoming") {
3424 $template = 'core_calendar/calendar_upcoming';
3425 } else if ($view == "upcoming_mini") {
e3491a09 3426 $template = 'core_calendar/calendar_upcoming_mini';
522b84be 3427 }
146d3713 3428 }
64ff737a
AN
3429
3430 return [$data, $template];
3431}
3432
705eea84
SL
3433/**
3434 * Request and render event form fragment.
3435 *
3436 * @param array $args The fragment arguments.
3437 * @return string The rendered mform fragment.
3438 */
aa091225 3439function calendar_output_fragment_event_form($args) {
ea5f7707 3440 global $CFG, $OUTPUT, $USER;
dfc609e5 3441 require_once($CFG->libdir . '/grouplib.php');
aa091225 3442 $html = '';
ea5f7707 3443 $data = [];
aa091225 3444 $eventid = isset($args['eventid']) ? clean_param($args['eventid'], PARAM_INT) : null;
f6e8cc83 3445 $starttime = isset($args['starttime']) ? clean_param($args['starttime'], PARAM_INT) : null;
dfc609e5 3446 $courseid = (isset($args['courseid']) && $args['courseid'] != SITEID) ? clean_param($args['courseid'], PARAM_INT) : null;
d097bfdd 3447 $categoryid = isset($args['categoryid']) ? clean_param($args['categoryid'], PARAM_INT) : null;
aa091225
RW
3448 $event = null;
3449 $hasformdata = isset($args['formdata']) && !empty($args['formdata']);
ea5f7707
RW
3450 $context = \context_user::instance($USER->id);
3451 $editoroptions = \core_calendar\local\event\forms\create::build_editor_options($context);
dfc609e5 3452 $formoptions = ['editoroptions' => $editoroptions, 'courseid' => $courseid];
ea5f7707 3453 $draftitemid = 0;
aa091225
RW
3454
3455 if ($hasformdata) {
3456 parse_str(clean_param($args['formdata'], PARAM_TEXT), $data);
ea5f7707
RW
3457 if (isset($data['description']['itemid'])) {
3458 $draftitemid = $data['description']['itemid'];
3459 }
aa091225
RW
3460 }
3461
f6e8cc83
RW
3462 if ($starttime) {
3463 $formoptions['starttime'] = $starttime;
3464 }
3465
aa091225 3466 if (is_null($eventid)) {
dfc609e5
SL
3467 if (!empty($courseid)) {
3468 $groupcoursedata = groups_get_course_data($courseid);
3469 $formoptions['groups'] = [];
3470 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3471 $formoptions['groups'][$groupid] = $groupdata->name;
3472 }
3473 }
aa091225
RW
3474 $mform = new \core_calendar\local\event\forms\create(
3475 null,
3476 $formoptions,
3477 'post',
3478 '',
3479 null,
3480 true,
3481 $data
3482 );
05187c58
SL
3483
3484 // Let's check first which event types user can add.
dfc609e5 3485 $eventtypes = calendar_get_allowed_event_types($courseid);
05187c58
SL
3486
3487 // If the user is on course context and is allowed to add course events set the event type default to course.
dfc609e5 3488 if ($courseid != SITEID && !empty($eventtypes['course'])) {
29158c8b
SL
3489 $data['eventtype'] = 'course';
3490 $data['courseid'] = $courseid;
3491 $data['groupcourseid'] = $courseid;
dfc609e5 3492 } else if (!empty($categoryid) && !empty($eventtypes['category'])) {
d097bfdd
AN
3493 $data['eventtype'] = 'category';
3494 $data['categoryid'] = $categoryid;
dfc609e5
SL
3495 } else if (!empty($groupcoursedata) && !empty($eventtypes['group'])) {
3496 $data['groupcourseid'] = $courseid;
3497 $data['groups'] = $groupcoursedata->groups;
29158c8b
SL
3498 }
3499 $mform->set_data($data);
aa091225
RW
3500 } else {
3501 $event = calendar_event::load($eventid);
ea5f7707
RW
3502 $mapper = new \core_calendar\local\event\mappers\create_update_form_mapper();
3503 $eventdata = $mapper->from_legacy_event_to_data($event);
3504 $data = array_merge((array) $eventdata, $data);
aa091225
RW
3505 $event->count_repeats();
3506 $formoptions['event'] = $event;
dfc609e5
SL
3507
3508 if (!empty($event->courseid)) {
3509 $groupcoursedata = groups_get_course_data($event->courseid);
3510 $formoptions['groups'] = [];
3511 foreach ($groupcoursedata->groups as $groupid => $groupdata) {
3512 $formoptions['groups'][$groupid] = $groupdata->name;
3513 }
3514 }
3515
ea5f7707
RW
3516 $data['description']['text'] = file_prepare_draft_area(
3517 $draftitemid,
3518 $event->context->id,
3519 'calendar',
3520 'event_description',
3521 $event->id,
3522 null,
3523 $data['description']['text']
3524 );
3525 $data['description']['itemid'] = $draftitemid;
3526
aa091225
RW
3527 $mform = new \core_calendar\local\event\forms\update(
3528 null,
3529 $formoptions,
3530 'post',
3531 '',
3532 null,
3533 true,
3534 $data
3535 );
aa091225
RW
3536 $mform->set_data($data);
3537
3538 // Check to see if this event is part of a subscription or import.
3539 // If so display a warning on edit.
3540 if (isset($event->subscriptionid) && ($event->subscriptionid != null)) {
3541 $renderable = new \core\output\notification(
3542 get_string('eventsubscriptioneditwarning', 'calendar'),
3543 \core\output\notification::NOTIFY_INFO
3544 );
3545
3546 $html .= $OUTPUT->render($renderable);
3547 }
3548 }
3549
ea5f7707
RW
3550 if ($hasformdata) {
3551 $mform->is_validated();
3552 }
3553
aa091225
RW
3554 $html .= $mform->render();
3555 return $html;
3556}
def443a0
AN
3557
3558/**
3559 * Calculate the timestamp from the supplied Gregorian Year, Month, and Day.
3560 *
3561 * @param int $d The day
3562 * @param int $m The month
3563 * @param int $y The year
3564 * @param int $time The timestamp to use instead of a separate y/m/d.
3565 * @return int The timestamp
3566 */
3567function calendar_get_timestamp($d, $m, $y, $time = 0) {
3568 // If a day, month and year were passed then convert it to a timestamp. If these were passed
3569 // then we can assume the day, month and year are passed as Gregorian, as no where in core
3570 // should we be passing these values rather than the time.
3571 if (!empty($d) && !empty($m) && !empty($y)) {
3572 if (checkdate($m, $d, $y)) {
3573 $time = make_timestamp($y, $m, $d);
3574 } else {
3575 $time = time();
3576 }
3577 } else if (empty($time)) {
3578 $time = time();
3579 }
3580
3581 return $time;
3582}
6124ec19
SL
3583
3584/**
3585 * Get the calendar footer options.
3586 *
3587 * @param calendar_information $calendar The calendar information object.
3588 * @return array The data for template and template name.
3589 */
3590function calendar_get_footer_options($calendar) {
3591 global $CFG, $USER, $DB, $PAGE;
3592
3593 // Generate hash for iCal link.
3594 $rawhash = $USER->id . $DB->get_field('user', 'password', ['id' => $USER->id]) . $CFG->calendar_exportsalt;
3595 $authtoken = sha1($rawhash);
3596
3597 $renderer = $PAGE->get_renderer('core_calendar');
3598 $footer = new \core_calendar\external\footer_options_exporter($calendar, $USER->id, $authtoken);
3599 $data = $footer->export($renderer);
3600 $template = 'core_calendar/footer_options';
3601
3602 return [$data, $template];
3603}
c8b6e9ab
AN
3604
3605/**
3606 * Get the list of potential calendar filter types as a type => name
3607 * combination.
3608 *
3609 * @return array
3610 */
3611function calendar_get_filter_types() {
3612 $types = [
3613 'site',
05f184bb 3614 'category',
c8b6e9ab
AN
3615 'course',
3616 'group',
3617 'user',
3618 ];
3619
3620 return array_map(function($type) {
3621 return [
a7ed05e7 3622 'eventtype' => $type,
c8b6e9ab
AN
3623 'name' => get_string("eventtype{$type}", "calendar"),
3624 ];
3625 }, $types);
3626}
05f184bb
AN
3627
3628/**
3629 * Check whether the specified event type is valid.
3630 *
3631 * @param string $type
3632 * @return bool
3633 */
3634function calendar_is_valid_eventtype($type) {
3635 $validtypes = [
3636 'user',
3637 'group',
3638 'course',
3639 'category',
3640 'site',
3641 ];
3642 return in_array($type, $validtypes);
3643}
4be55b06
SL
3644
3645/**
3646 * Get event types the user can create event based on categories, courses and groups
3647 * the logged in user belongs to.
3648 *
3649 * @param int|null $courseid The course id.
3650 * @return array The array of allowed types.
3651 */
3652function calendar_get_allowed_event_types(int $courseid = null) {
3653 global $DB, $CFG, $USER;
3654
3655 $types = [
3656 'user' => false,
3657 'site' => false,
3658 'course' => false,
3659 'group' => false,
3660 'category' => false
3661 ];
3662
3663 if (!empty($courseid) && $courseid != SITEID) {
3664 $context = \context_course::instance($courseid);
3665 $groups = groups_get_all_groups($courseid);
3666
3667 $types['user'] = has_capability('moodle/calendar:manageownentries', $context);
3668
3669 if (has_capability('moodle/calendar:manageentries', $context) || !empty($CFG->calendar_adminseesall)) {
3670 $types['course'] = true;
3671
3672 $types['group'] = (!empty($groups) && has_capability('moodle/site:accessallgroups', $context))
3673 || array_filter($groups, function($group) use ($USER) {
3674 return groups_is_member($group->id);
3675 });
3676 } else if (has_capability('moodle/calendar:managegroupentries', $context)) {
3677 $types['group'] = (!empty($groups) && has_capability('moodle/site:accessallgroups', $context))
3678 || array_filter($groups, function($group) use ($USER) {
3679 return groups_is_member($group->id);
3680 });
3681 }
3682 }
3683
3684 if (has_capability('moodle/calendar:manageentries', \context_course::instance(SITEID))) {
3685 $types['site'] = true;
3686 }
3687
3688 if (has_capability('moodle/calendar:manageownentries', \context_system::instance())) {
3689 $types['user'] = true;
3690 }
3691 if (coursecat::has_manage_capability_on_any()) {
3692 $types['category'] = true;
3693 }
3694
3695 // We still don't know if the user can create group and course events, so iterate over the courses to find out
3696 // if the user has capabilities in one of the courses.
dfc609e5 3697 if ($types['course'] == false || $types['group'] == false) {
687112af
SL
3698 if ($CFG->calendar_adminseesall && has_capability('moodle/calendar:manageentries', context_system::instance())) {
3699 $sql = "SELECT c.id, " . context_helper::get_preload_record_columns_sql('ctx') . "
3700 FROM {course} c
3701 JOIN {context} ctx ON ctx.contextlevel = ? AND ctx.instanceid = c.id
3702 WHERE c.id IN (
3703 SELECT DISTINCT courseid FROM {groups}
3704 )";
3705 $courseswithgroups = $DB->get_recordset_sql($sql, [CONTEXT_COURSE]);
3706 foreach ($courseswithgroups as $course) {
3707 context_helper::preload_from_record($course);
3708 $context