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