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