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