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