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