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