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