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