Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

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