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