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