lib.php 149 KB
Newer Older
1
<?php
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16

17
18
19
20
21
22
23
24
25
/**
 * Calendar extension
 *
 * @package    core_calendar
 * @copyright  2004 Greek School Network (http://www.sch.gr), Jon Papaioannou,
 *             Avgoustos Tsinakos
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 */

26
27
28
if (!defined('MOODLE_INTERNAL')) {
    die('Direct access to this script is forbidden.');    ///  It must be included from a Moodle page
}
29

30
31
32
33
34
35
36
/**
 *  These are read by the administration component to provide default values
 */

/**
 * CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD - default value of upcoming event preference
 */
defacer's avatar
   
defacer committed
37
define('CALENDAR_DEFAULT_UPCOMING_LOOKAHEAD', 21);
38
39
40
41

/**
 * CALENDAR_DEFAULT_UPCOMING_MAXEVENTS - default value to display the maximum number of upcoming event
 */
defacer's avatar
   
defacer committed
42
define('CALENDAR_DEFAULT_UPCOMING_MAXEVENTS', 10);
43
44
45
46
47
48

/**
 * CALENDAR_DEFAULT_STARTING_WEEKDAY - default value to display the starting weekday
 */
define('CALENDAR_DEFAULT_STARTING_WEEKDAY', 1);

defacer's avatar
   
defacer committed
49
50
// This is a packed bitfield: day X is "weekend" if $field & (1 << X) is true
// Default value = 65 = 64 + 1 = 2^6 + 2^0 = Saturday & Sunday
51
52
53
54
55
56
57
58
59

/**
 * CALENDAR_DEFAULT_WEEKEND - default value for weekend (Saturday & Sunday)
 */
define('CALENDAR_DEFAULT_WEEKEND', 65);

/**
 * CALENDAR_URL - path to calendar's folder
 */
60
define('CALENDAR_URL', $CFG->wwwroot.'/calendar/');
61
62
63
64

/**
 * CALENDAR_TF_24 - Calendar time in 24 hours format
 */
65
define('CALENDAR_TF_24', '%H:%M');
66
67
68
69

/**
 * CALENDAR_TF_12 - Calendar time in 12 hours format
 */
70
define('CALENDAR_TF_12', '%I:%M %p');
defacer's avatar
   
defacer committed
71

72
73
74
/**
 * CALENDAR_EVENT_GLOBAL - Global calendar event types
 */
75
define('CALENDAR_EVENT_GLOBAL', 1);
76
77
78
79

/**
 * CALENDAR_EVENT_COURSE - Course calendar event types
 */
80
define('CALENDAR_EVENT_COURSE', 2);
81
82
83
84

/**
 * CALENDAR_EVENT_GROUP - group calendar event types
 */
85
define('CALENDAR_EVENT_GROUP', 4);
86
87
88
89

/**
 * CALENDAR_EVENT_USER - user calendar event types
 */
90
91
define('CALENDAR_EVENT_USER', 8);

92
93
94
95
/**
 * CALENDAR_EVENT_COURSECAT - Course category calendar event types
 */
define('CALENDAR_EVENT_COURSECAT', 16);
96

97
98
99
100
101
102
103
104
105
106
/**
 * CALENDAR_IMPORT_FROM_FILE - import the calendar from a file
 */
define('CALENDAR_IMPORT_FROM_FILE', 0);

/**
 * CALENDAR_IMPORT_FROM_URL - import the calendar from a URL
 */
define('CALENDAR_IMPORT_FROM_URL',  1);

107
108
109
110
111
/**
 * CALENDAR_IMPORT_EVENT_UPDATED_SKIPPED - imported event was skipped
 */
define('CALENDAR_IMPORT_EVENT_SKIPPED',  -1);

112
113
114
115
116
117
118
119
120
121
/**
 * CALENDAR_IMPORT_EVENT_UPDATED - imported event was updated
 */
define('CALENDAR_IMPORT_EVENT_UPDATED',  1);

/**
 * CALENDAR_IMPORT_EVENT_INSERTED - imported event was added by insert
 */
define('CALENDAR_IMPORT_EVENT_INSERTED', 2);

122
123
124
125
126
127
128
129
130
131
/**
 * CALENDAR_SUBSCRIPTION_UPDATE - Used to represent update action for subscriptions in various forms.
 */
define('CALENDAR_SUBSCRIPTION_UPDATE', 1);

/**
 * CALENDAR_SUBSCRIPTION_REMOVE - Used to represent remove action for subscriptions in various forms.
 */
define('CALENDAR_SUBSCRIPTION_REMOVE', 2);

132
133
134
/**
 * CALENDAR_EVENT_USER_OVERRIDE_PRIORITY - Constant for the user override priority.
 */
135
define('CALENDAR_EVENT_USER_OVERRIDE_PRIORITY', 0);
136

137
138
139
140
141
142
143
144
145
146
/**
 * CALENDAR_EVENT_TYPE_STANDARD - Standard events.
 */
define('CALENDAR_EVENT_TYPE_STANDARD', 0);

/**
 * CALENDAR_EVENT_TYPE_ACTION - Action events.
 */
define('CALENDAR_EVENT_TYPE_ACTION', 1);

147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
/**
 * Manage calendar events.
 *
 * This class provides the required functionality in order to manage calendar events.
 * It was introduced as part of Moodle 2.0 and was created in order to provide a
 * better framework for dealing with calendar events in particular regard to file
 * handling through the new file API.
 *
 * @package    core_calendar
 * @category   calendar
 * @copyright  2009 Sam Hemelryk
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 *
 * @property int $id The id within the event table
 * @property string $name The name of the event
 * @property string $description The description of the event
 * @property int $format The format of the description FORMAT_?
 * @property int $courseid The course the event is associated with (0 if none)
 * @property int $groupid The group the event is associated with (0 if none)
 * @property int $userid The user the event is associated with (0 if none)
 * @property int $repeatid If this is a repeated event this will be set to the
 *                          id of the original
 * @property string $modulename If added by a module this will be the module name
 * @property int $instance If added by a module this will be the module instance
 * @property string $eventtype The event type
 * @property int $timestart The start time as a timestamp
 * @property int $timeduration The duration of the event in seconds
 * @property int $visible 1 if the event is visible
 * @property int $uuid ?
 * @property int $sequence ?
 * @property int $timemodified The time last modified as a timestamp
 */
class calendar_event {

    /** @var array An object containing the event properties can be accessed via the magic __get/set methods */
    protected $properties = null;

    /** @var string The converted event discription with file paths resolved.
     *              This gets populated when someone requests description for the first time */
    protected $_description = null;

    /** @var array The options to use with this description editor */
    protected $editoroptions = array(
        'subdirs' => false,
        'forcehttps' => false,
        'maxfiles' => -1,
        'maxbytes' => null,
        'trusttext' => false);

    /** @var object The context to use with the description editor */
    protected $editorcontext = null;

    /**
     * Instantiates a new event and optionally populates its properties with the data provided.
     *
     * @param \stdClass $data Optional. An object containing the properties to for
     *                  an event
     */
    public function __construct($data = null) {
        global $CFG, $USER;

        // First convert to object if it is not already (should either be object or assoc array).
        if (!is_object($data)) {
            $data = (object) $data;
        }

        $this->editoroptions['maxbytes'] = $CFG->maxbytes;

        $data->eventrepeats = 0;

        if (empty($data->id)) {
            $data->id = null;
        }

        if (!empty($data->subscriptionid)) {
222
            $data->subscription = calendar_get_subscription($data->subscriptionid);
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
        }

        // Default to a user event.
        if (empty($data->eventtype)) {
            $data->eventtype = 'user';
        }

        // Default to the current user.
        if (empty($data->userid)) {
            $data->userid = $USER->id;
        }

        if (!empty($data->timeduration) && is_array($data->timeduration)) {
            $data->timeduration = make_timestamp(
                    $data->timeduration['year'], $data->timeduration['month'], $data->timeduration['day'],
                    $data->timeduration['hour'], $data->timeduration['minute']) - $data->timestart;
        }

        if (!empty($data->description) && is_array($data->description)) {
            $data->format = $data->description['format'];
            $data->description = $data->description['text'];
        } else if (empty($data->description)) {
            $data->description = '';
            $data->format = editors_get_preferred_format();
        }

        // Ensure form is defaulted correctly.
        if (empty($data->format)) {
            $data->format = editors_get_preferred_format();
        }

        $this->properties = $data;
    }

    /**
     * Magic set method.
     *
     * Attempts to call a set_$key method if one exists otherwise falls back
     * to simply set the property.
     *
     * @param string $key property name
     * @param mixed $value value of the property
     */
    public function __set($key, $value) {
        if (method_exists($this, 'set_'.$key)) {
            $this->{'set_'.$key}($value);
        }
        $this->properties->{$key} = $value;
    }

    /**
     * Magic get method.
     *
     * Attempts to call a get_$key method to return the property and ralls over
     * to return the raw property.
     *
     * @param string $key property name
     * @return mixed property value
     * @throws \coding_exception
     */
    public function __get($key) {
        if (method_exists($this, 'get_'.$key)) {
            return $this->{'get_'.$key}();
        }
287
        if (!property_exists($this->properties, $key)) {
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
            throw new \coding_exception('Undefined property requested');
        }
        return $this->properties->{$key};
    }

    /**
     * Magic isset method.
     *
     * PHP needs an isset magic method if you use the get magic method and
     * still want empty calls to work.
     *
     * @param string $key $key property name
     * @return bool|mixed property value, false if property is not exist
     */
    public function __isset($key) {
        return !empty($this->properties->{$key});
    }

    /**
     * Calculate the context value needed for an event.
     *
     * Event's type can be determine by the available value store in $data
     * It is important to check for the existence of course/courseid to determine
     * the course event.
     * Default value is set to CONTEXT_USER
     *
     * @return \stdClass The context object.
     */
    protected function calculate_context() {
        global $USER, $DB;

        $context = null;
320
321
322
        if (isset($this->properties->categoryid) && $this->properties->categoryid > 0) {
            $context = \context_coursecat::instance($this->properties->categoryid);
        } else if (isset($this->properties->courseid) && $this->properties->courseid > 0) {
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
            $context = \context_course::instance($this->properties->courseid);
        } else if (isset($this->properties->course) && $this->properties->course > 0) {
            $context = \context_course::instance($this->properties->course);
        } else if (isset($this->properties->groupid) && $this->properties->groupid > 0) {
            $group = $DB->get_record('groups', array('id' => $this->properties->groupid));
            $context = \context_course::instance($group->courseid);
        } else if (isset($this->properties->userid) && $this->properties->userid > 0
            && $this->properties->userid == $USER->id) {
            $context = \context_user::instance($this->properties->userid);
        } else if (isset($this->properties->userid) && $this->properties->userid > 0
            && $this->properties->userid != $USER->id &&
            isset($this->properties->instance) && $this->properties->instance > 0) {
            $cm = get_coursemodule_from_instance($this->properties->modulename, $this->properties->instance, 0,
                false, MUST_EXIST);
            $context = \context_course::instance($cm->course);
        } else {
            $context = \context_user::instance($this->properties->userid);
        }

        return $context;
    }

345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
    /**
     * Returns the context for this event. The context is calculated
     * the first time is is requested and then stored in a member
     * variable to be returned each subsequent time.
     *
     * This is a magical getter function that will be called when
     * ever the context property is accessed, e.g. $event->context.
     *
     * @return context
     */
    protected function get_context() {
        if (!isset($this->properties->context)) {
            $this->properties->context = $this->calculate_context();
        }

        return $this->properties->context;
    }

363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
    /**
     * Returns an array of editoroptions for this event.
     *
     * @return array event editor options
     */
    protected function get_editoroptions() {
        return $this->editoroptions;
    }

    /**
     * Returns an event description: Called by __get
     * Please use $blah = $event->description;
     *
     * @return string event description
     */
    protected function get_description() {
        global $CFG;

        require_once($CFG->libdir . '/filelib.php');

        if ($this->_description === null) {
            // Check if we have already resolved the context for this event.
            if ($this->editorcontext === null) {
                // Switch on the event type to decide upon the appropriate context to use for this event.
387
                $this->editorcontext = $this->get_context();
388
                if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
                    return clean_text($this->properties->description, $this->properties->format);
                }
            }

            // Work out the item id for the editor, if this is a repeated event
            // then the files will be associated with the original.
            if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
                $itemid = $this->properties->repeatid;
            } else {
                $itemid = $this->properties->id;
            }

            // Convert file paths in the description so that things display correctly.
            $this->_description = file_rewrite_pluginfile_urls($this->properties->description, 'pluginfile.php',
                $this->editorcontext->id, 'calendar', 'event_description', $itemid);
            // Clean the text so no nasties get through.
            $this->_description = clean_text($this->_description, $this->properties->format);
        }

        // Finally return the description.
        return $this->_description;
    }

    /**
     * Return the number of repeat events there are in this events series.
     *
     * @return int number of event repeated
     */
    public function count_repeats() {
        global $DB;
        if (!empty($this->properties->repeatid)) {
            $this->properties->eventrepeats = $DB->count_records('event',
                array('repeatid' => $this->properties->repeatid));
            // We don't want to count ourselves.
            $this->properties->eventrepeats--;
        }
        return $this->properties->eventrepeats;
    }

    /**
     * Update or create an event within the database
     *
     * Pass in a object containing the event properties and this function will
     * insert it into the database and deal with any associated files
     *
434
435
436
437
438
439
440
441
442
     * Capability checking should be performed if the user is directly manipulating the event
     * and no other capability has been tested. However if the event is not being manipulated
     * directly by the user and another capability has been checked for them to do this then
     * capabilites should not be checked.
     *
     * For example if a user is editing an event in the calendar the check should be true,
     * but if you are updating an event in an activities settings are changed then the calendar
     * capabilites should not be checked.
     *
443
444
445
446
     * @see self::create()
     * @see self::update()
     *
     * @param \stdClass $data object of event
447
     * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
448
449
450
451
452
453
454
455
456
457
458
459
460
461
     * @return bool event updated
     */
    public function update($data, $checkcapability=true) {
        global $DB, $USER;

        foreach ($data as $key => $value) {
            $this->properties->$key = $value;
        }

        $this->properties->timemodified = time();
        $usingeditor = (!empty($this->properties->description) && is_array($this->properties->description));

        // Prepare event data.
        $eventargs = array(
462
            'context' => $this->get_context(),
463
464
465
466
467
468
469
470
471
472
            'objectid' => $this->properties->id,
            'other' => array(
                'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
                'timestart' => $this->properties->timestart,
                'name' => $this->properties->name
            )
        );

        if (empty($this->properties->id) || $this->properties->id < 1) {
            if ($checkcapability) {
473
                if (!calendar_add_event_allowed($this->properties)) {
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
                    print_error('nopermissiontoupdatecalendar');
                }
            }

            if ($usingeditor) {
                switch ($this->properties->eventtype) {
                    case 'user':
                        $this->properties->courseid = 0;
                        $this->properties->course = 0;
                        $this->properties->groupid = 0;
                        $this->properties->userid = $USER->id;
                        break;
                    case 'site':
                        $this->properties->courseid = SITEID;
                        $this->properties->course = SITEID;
                        $this->properties->groupid = 0;
                        $this->properties->userid = $USER->id;
                        break;
                    case 'course':
                        $this->properties->groupid = 0;
                        $this->properties->userid = $USER->id;
                        break;
496
497
498
499
500
                    case 'category':
                        $this->properties->groupid = 0;
                        $this->properties->category = 0;
                        $this->properties->userid = $USER->id;
                        break;
501
502
503
504
505
506
507
508
509
510
511
512
513
                    case 'group':
                        $this->properties->userid = $USER->id;
                        break;
                    default:
                        // We should NEVER get here, but just incase we do lets fail gracefully.
                        $usingeditor = false;
                        break;
                }

                // If we are actually using the editor, we recalculate the context because some default values
                // were set when calculate_context() was called from the constructor.
                if ($usingeditor) {
                    $this->properties->context = $this->calculate_context();
514
                    $this->editorcontext = $this->get_context();
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
                }

                $editor = $this->properties->description;
                $this->properties->format = $this->properties->description['format'];
                $this->properties->description = $this->properties->description['text'];
            }

            // Insert the event into the database.
            $this->properties->id = $DB->insert_record('event', $this->properties);

            if ($usingeditor) {
                $this->properties->description = file_save_draft_area_files(
                    $editor['itemid'],
                    $this->editorcontext->id,
                    'calendar',
                    'event_description',
                    $this->properties->id,
                    $this->editoroptions,
                    $editor['text'],
                    $this->editoroptions['forcehttps']);
                $DB->set_field('event', 'description', $this->properties->description,
                    array('id' => $this->properties->id));
            }

            // Log the event entry.
            $eventargs['objectid'] = $this->properties->id;
541
            $eventargs['context'] = $this->get_context();
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
            $event = \core\event\calendar_event_created::create($eventargs);
            $event->trigger();

            $repeatedids = array();

            if (!empty($this->properties->repeat)) {
                $this->properties->repeatid = $this->properties->id;
                $DB->set_field('event', 'repeatid', $this->properties->repeatid, array('id' => $this->properties->id));

                $eventcopy = clone($this->properties);
                unset($eventcopy->id);

                $timestart = new \DateTime('@' . $eventcopy->timestart);
                $timestart->setTimezone(\core_date::get_user_timezone_object());

                for ($i = 1; $i < $eventcopy->repeats; $i++) {

                    $timestart->add(new \DateInterval('P7D'));
                    $eventcopy->timestart = $timestart->getTimestamp();

                    // Get the event id for the log record.
                    $eventcopyid = $DB->insert_record('event', $eventcopy);

                    // If the context has been set delete all associated files.
                    if ($usingeditor) {
                        $fs = get_file_storage();
                        $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description',
                            $this->properties->id);
                        foreach ($files as $file) {
                            $fs->create_file_from_storedfile(array('itemid' => $eventcopyid), $file);
                        }
                    }

                    $repeatedids[] = $eventcopyid;

                    // Trigger an event.
                    $eventargs['objectid'] = $eventcopyid;
                    $eventargs['other']['timestart'] = $eventcopy->timestart;
                    $event = \core\event\calendar_event_created::create($eventargs);
                    $event->trigger();
                }
            }

            return true;
        } else {

            if ($checkcapability) {
589
                if (!calendar_edit_event_allowed($this->properties)) {
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
                    print_error('nopermissiontoupdatecalendar');
                }
            }

            if ($usingeditor) {
                if ($this->editorcontext !== null) {
                    $this->properties->description = file_save_draft_area_files(
                        $this->properties->description['itemid'],
                        $this->editorcontext->id,
                        'calendar',
                        'event_description',
                        $this->properties->id,
                        $this->editoroptions,
                        $this->properties->description['text'],
                        $this->editoroptions['forcehttps']);
                } else {
                    $this->properties->format = $this->properties->description['format'];
                    $this->properties->description = $this->properties->description['text'];
                }
            }

            $event = $DB->get_record('event', array('id' => $this->properties->id));

            $updaterepeated = (!empty($this->properties->repeatid) && !empty($this->properties->repeateditall));

            if ($updaterepeated) {
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634

                $sqlset = 'name = ?,
                           description = ?,
                           timeduration = ?,
                           timemodified = ?,
                           groupid = ?,
                           courseid = ?';

                // Note: Group and course id may not be set. If not, keep their current values.
                $params = [
                    $this->properties->name,
                    $this->properties->description,
                    $this->properties->timeduration,
                    time(),
                    isset($this->properties->groupid) ? $this->properties->groupid : $event->groupid,
                    isset($this->properties->courseid) ? $this->properties->courseid : $event->courseid,
                ];

                // Note: Only update start date, if it was changed by the user.
635
636
                if ($this->properties->timestart != $event->timestart) {
                    $timestartoffset = $this->properties->timestart - $event->timestart;
637
638
639
640
641
642
643
644
645
                    $sqlset .= ', timestart = timestart + ?';
                    $params[] = $timestartoffset;
                }

                // Note: Only update location, if it was changed by the user.
                $updatelocation = (!empty($this->properties->location) && $this->properties->location !== $event->location);
                if ($updatelocation) {
                    $sqlset .= ', location = ?';
                    $params[] = $this->properties->location;
646
                }
647
648
649
650
651
652
653

                // Update all.
                $sql = "UPDATE {event}
                           SET $sqlset
                         WHERE repeatid = ?";

                $params[] = $event->repeatid;
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
                $DB->execute($sql, $params);

                // Trigger an update event for each of the calendar event.
                $events = $DB->get_records('event', array('repeatid' => $event->repeatid), '', '*');
                foreach ($events as $calendarevent) {
                    $eventargs['objectid'] = $calendarevent->id;
                    $eventargs['other']['timestart'] = $calendarevent->timestart;
                    $event = \core\event\calendar_event_updated::create($eventargs);
                    $event->add_record_snapshot('event', $calendarevent);
                    $event->trigger();
                }
            } else {
                $DB->update_record('event', $this->properties);
                $event = self::load($this->properties->id);
                $this->properties = $event->properties();

                // Trigger an update event.
                $event = \core\event\calendar_event_updated::create($eventargs);
                $event->add_record_snapshot('event', $this->properties);
                $event->trigger();
            }

            return true;
        }
    }

    /**
     * Deletes an event and if selected an repeated events in the same series
     *
     * This function deletes an event, any associated events if $deleterepeated=true,
     * and cleans up any files associated with the events.
     *
     * @see self::delete()
     *
     * @param bool $deleterepeated  delete event repeatedly
     * @return bool succession of deleting event
     */
    public function delete($deleterepeated = false) {
        global $DB;

        // If $this->properties->id is not set then something is wrong.
        if (empty($this->properties->id)) {
            debugging('Attempting to delete an event before it has been loaded', DEBUG_DEVELOPER);
            return false;
        }
        $calevent = $DB->get_record('event',  array('id' => $this->properties->id), '*', MUST_EXIST);
        // Delete the event.
        $DB->delete_records('event', array('id' => $this->properties->id));

        // Trigger an event for the delete action.
        $eventargs = array(
705
            'context' => $this->get_context(),
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
            'objectid' => $this->properties->id,
            'other' => array(
                'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
                'timestart' => $this->properties->timestart,
                'name' => $this->properties->name
            ));
        $event = \core\event\calendar_event_deleted::create($eventargs);
        $event->add_record_snapshot('event', $calevent);
        $event->trigger();

        // If we are deleting parent of a repeated event series, promote the next event in the series as parent.
        if (($this->properties->id == $this->properties->repeatid) && !$deleterepeated) {
            $newparent = $DB->get_field_sql("SELECT id from {event} where repeatid = ? order by id ASC",
                array($this->properties->id), IGNORE_MULTIPLE);
            if (!empty($newparent)) {
                $DB->execute("UPDATE {event} SET repeatid = ? WHERE repeatid = ?",
                    array($newparent, $this->properties->id));
                // Get all records where the repeatid is the same as the event being removed.
                $events = $DB->get_records('event', array('repeatid' => $newparent));
                // For each of the returned events trigger an update event.
                foreach ($events as $calendarevent) {
                    // Trigger an event for the update.
                    $eventargs['objectid'] = $calendarevent->id;
                    $eventargs['other']['timestart'] = $calendarevent->timestart;
                    $event = \core\event\calendar_event_updated::create($eventargs);
                    $event->add_record_snapshot('event', $calendarevent);
                    $event->trigger();
                }
            }
        }

        // If the editor context hasn't already been set then set it now.
        if ($this->editorcontext === null) {
739
            $this->editorcontext = $this->get_context();
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
        }

        // If the context has been set delete all associated files.
        if ($this->editorcontext !== null) {
            $fs = get_file_storage();
            $files = $fs->get_area_files($this->editorcontext->id, 'calendar', 'event_description', $this->properties->id);
            foreach ($files as $file) {
                $file->delete();
            }
        }

        // If we need to delete repeated events then we will fetch them all and delete one by one.
        if ($deleterepeated && !empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
            // Get all records where the repeatid is the same as the event being removed.
            $events = $DB->get_records('event', array('repeatid' => $this->properties->repeatid));
            // For each of the returned events populate an event object and call delete.
            // make sure the arg passed is false as we are already deleting all repeats.
            foreach ($events as $event) {
                $event = new calendar_event($event);
                $event->delete(false);
            }
        }

        return true;
    }

    /**
     * Fetch all event properties.
     *
     * This function returns all of the events properties as an object and optionally
     * can prepare an editor for the description field at the same time. This is
     * designed to work when the properties are going to be used to set the default
     * values of a moodle forms form.
     *
     * @param bool $prepareeditor If set to true a editor is prepared for use with
     *              the mforms editor element. (for description)
     * @return \stdClass Object containing event properties
     */
    public function properties($prepareeditor = false) {
        global $DB;

        // First take a copy of the properties. We don't want to actually change the
        // properties or we'd forever be converting back and forwards between an
        // editor formatted description and not.
        $properties = clone($this->properties);
        // Clean the description here.
        $properties->description = clean_text($properties->description, $properties->format);

        // If set to true we need to prepare the properties for use with an editor
        // and prepare the file area.
        if ($prepareeditor) {

            // We may or may not have a property id. If we do then we need to work
            // out the context so we can copy the existing files to the draft area.
            if (!empty($properties->id)) {

                if ($properties->eventtype === 'site') {
                    // Site context.
798
                    $this->editorcontext = $this->get_context();
799
800
                } else if ($properties->eventtype === 'user') {
                    // User context.
801
                    $this->editorcontext = $this->get_context();
802
803
804
805
806
807
808
                } else if ($properties->eventtype === 'group' || $properties->eventtype === 'course') {
                    // First check the course is valid.
                    $course = $DB->get_record('course', array('id' => $properties->courseid));
                    if (!$course) {
                        print_error('invalidcourse');
                    }
                    // Course context.
809
                    $this->editorcontext = $this->get_context();
810
811
812
                    // We have a course and are within the course context so we had
                    // better use the courses max bytes value.
                    $this->editoroptions['maxbytes'] = $course->maxbytes;
813
814
                } else if ($properties->eventtype === 'category') {
                    // First check the course is valid.
815
                    \core_course_category::get($properties->categoryid, MUST_EXIST, true);
816
                    // Course context.
817
                    $this->editorcontext = $this->get_context();
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
                } else {
                    // If we get here we have a custom event type as used by some
                    // modules. In this case the event will have been added by
                    // code and we won't need the editor.
                    $this->editoroptions['maxbytes'] = 0;
                    $this->editoroptions['maxfiles'] = 0;
                }

                if (empty($this->editorcontext) || empty($this->editorcontext->id)) {
                    $contextid = false;
                } else {
                    // Get the context id that is what we really want.
                    $contextid = $this->editorcontext->id;
                }
            } else {

                // If we get here then this is a new event in which case we don't need a
                // context as there is no existing files to copy to the draft area.
                $contextid = null;
            }

            // If the contextid === false we don't support files so no preparing
            // a draft area.
            if ($contextid !== false) {
                // Just encase it has already been submitted.
                $draftiddescription = file_get_submitted_draft_itemid('description');
                // Prepare the draft area, this copies existing files to the draft area as well.
                $properties->description = file_prepare_draft_area($draftiddescription, $contextid, 'calendar',
                    'event_description', $properties->id, $this->editoroptions, $properties->description);
            } else {
                $draftiddescription = 0;
            }

            // Structure the description field as the editor requires.
            $properties->description = array('text' => $properties->description, 'format' => $properties->format,
                'itemid' => $draftiddescription);
        }

        // Finally return the properties.
        return $properties;
    }

    /**
     * Toggles the visibility of an event
     *
     * @param null|bool $force If it is left null the events visibility is flipped,
     *                   If it is false the event is made hidden, if it is true it
     *                   is made visible.
     * @return bool if event is successfully updated, toggle will be visible
     */
    public function toggle_visibility($force = null) {
        global $DB;

        // Set visible to the default if it is not already set.
        if (empty($this->properties->visible)) {
            $this->properties->visible = 1;
        }

        if ($force === true || ($force !== false && $this->properties->visible == 0)) {
            // Make this event visible.
            $this->properties->visible = 1;
        } else {
            // Make this event hidden.
            $this->properties->visible = 0;
        }

        // Update the database to reflect this change.
        $success = $DB->set_field('event', 'visible', $this->properties->visible, array('id' => $this->properties->id));
        $calendarevent = $DB->get_record('event',  array('id' => $this->properties->id), '*', MUST_EXIST);

        // Prepare event data.
        $eventargs = array(
890
            'context' => $this->get_context(),
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
            'objectid' => $this->properties->id,
            'other' => array(
                'repeatid' => empty($this->properties->repeatid) ? 0 : $this->properties->repeatid,
                'timestart' => $this->properties->timestart,
                'name' => $this->properties->name
            )
        );
        $event = \core\event\calendar_event_updated::create($eventargs);
        $event->add_record_snapshot('event', $calendarevent);
        $event->trigger();

        return $success;
    }

    /**
     * Returns an event object when provided with an event id.
     *
     * This function makes use of MUST_EXIST, if the event id passed in is invalid
     * it will result in an exception being thrown.
     *
     * @param int|object $param event object or event id
     * @return calendar_event
     */
    public static function load($param) {
        global $DB;
        if (is_object($param)) {
            $event = new calendar_event($param);
        } else {
            $event = $DB->get_record('event', array('id' => (int)$param), '*', MUST_EXIST);
            $event = new calendar_event($event);
        }
        return $event;
    }

    /**
926
927
928
929
930
931
932
933
934
935
     * Creates a new event and returns an event object.
     *
     * Capability checking should be performed if the user is directly creating the event
     * and no other capability has been tested. However if the event is not being created
     * directly by the user and another capability has been checked for them to do this then
     * capabilites should not be checked.
     *
     * For example if a user is creating an event in the calendar the check should be true,
     * but if you are creating an event in an activity when it is created then the calendar
     * capabilites should not be checked.
936
937
     *
     * @param \stdClass|array $properties An object containing event properties
938
     * @param bool $checkcapability If Moodle should check the user can manage the calendar events for this call or not.
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
     * @throws \coding_exception
     *
     * @return calendar_event|bool The event object or false if it failed
     */
    public static function create($properties, $checkcapability = true) {
        if (is_array($properties)) {
            $properties = (object)$properties;
        }
        if (!is_object($properties)) {
            throw new \coding_exception('When creating an event properties should be either an object or an assoc array');
        }
        $event = new calendar_event($properties);
        if ($event->update($properties, $checkcapability)) {
            return $event;
        } else {
            return false;
        }
    }

    /**
     * Format the text using the external API.
     *
     * This function should we used when text formatting is required in external functions.
     *
     * @return array an array containing the text formatted and the text format
     */
    public function format_external_text() {

        if ($this->editorcontext === null) {
            // Switch on the event type to decide upon the appropriate context to use for this event.
969
            $this->editorcontext = $this->get_context();
970

971
            if (!calendar_is_valid_eventtype($this->properties->eventtype)) {
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
                // We don't have a context here, do a normal format_text.
                return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id);
            }
        }

        // Work out the item id for the editor, if this is a repeated event then the files will be associated with the original.
        if (!empty($this->properties->repeatid) && $this->properties->repeatid > 0) {
            $itemid = $this->properties->repeatid;
        } else {
            $itemid = $this->properties->id;
        }

        return external_format_text($this->properties->description, $this->properties->format, $this->editorcontext->id,
            'calendar', 'event_description', $itemid);
    }
}

989
990
991
992
993
/**
 * Calendar information class
 *
 * This class is used simply to organise the information pertaining to a calendar
 * and is used primarily to make information easily available.
994
995
996
997
998
 *
 * @package core_calendar
 * @category calendar
 * @copyright 2010 Sam Hemelryk
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
999
1000
 */
class calendar_information {
1001

1002
1003
1004
1005
1006
1007
1008
    /**
     * @var int The timestamp
     *
     * Rather than setting the day, month and year we will set a timestamp which will be able
     * to be used by multiple calendars.
     */
    public $time;
1009

1010
    /** @var int A course id */
1011
    public $courseid = null;
1012

1013
1014
1015
1016
1017
1018
    /** @var array An array of categories */
    public $categories = array();

    /** @var int The current category */
    public $categoryid = null;

1019
    /** @var array An array of courses */
1020
    public $courses = array();
1021
1022

    /** @var array An array of groups */
1023
    public $groups = array();
1024
1025

    /** @var array An array of users */
1026
1027
    public $users = array();

1028
1029
1030
    /** @var context The anticipated context that the calendar is viewed in */
    public $context = null;

1031
1032
1033
    /**
     * Creates a new instance
     *
1034
1035
1036
     * @param int $day the number of the day
     * @param int $month the number of the month
     * @param int $year the number of the year
1037
1038
     * @param int $time the unixtimestamp representing the date we want to view, this is used instead of $calmonth
     *     and $calyear to support multiple calendars
1039
     */
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
    public function __construct($day = 0, $month = 0, $year = 0, $time = 0) {
        // If a day, month and year were passed then convert it to a timestamp. If these were passed
        // then we can assume the day, month and year are passed as Gregorian, as no where in core
        // should we be passing these values rather than the time. This is done for BC.
        if (!empty($day) || !empty($month) || !empty($year)) {
            $date = usergetdate(time());
            if (empty($day)) {
                $day = $date['mday'];
            }
            if (empty($month)) {
                $month = $date['mon'];
            }
            if (empty($year)) {
                $year =  $date['year'];
            }
            if (checkdate($month, $day, $year)) {
1056
                $time = make_timestamp($year, $month, $day);
1057
            } else {
1058
                $time = time();
1059
            }
1060
1061
1062
1063
1064
        }

        $this->set_time($time);
    }

1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
    /**
     * Creates and set up a instance.
     *
     * @param   int                     $time the unixtimestamp representing the date we want to view.
     * @param   int                     $courseid The ID of the course the user wishes to view.
     * @param   int                     $categoryid The ID of the category the user wishes to view
     *                                  If a courseid is specified, this value is ignored.
     * @return  calendar_information
     */
    public static function create($time, int $courseid, int $categoryid = null) : calendar_information {
        $calendar = new static(0, 0, 0, $time);
        if ($courseid != SITEID && !empty($courseid)) {
            // Course ID must be valid and existing.
            $course = get_course($courseid);
            $calendar->context = context_course::instance($course->id);

1081
            if (!$course->visible && !is_role_switched($course->id)) {
1082
1083
1084
1085
                require_capability('moodle/course:viewhiddencourses', $calendar->context);
            }

            $courses = [$course->id => $course];
1086
            $category = (\core_course_category::get($course->category, MUST_EXIST, true))->get_db_record();
1087
1088
        } else if (!empty($categoryid)) {
            $course = get_site();
1089
            $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1090
1091
1092

            // Filter available courses to those within this category or it's children.
            $ids = [$categoryid];
1093
            $category = \core_course_category::get($categoryid);
1094
1095
1096
1097
1098
1099
1100
1101
1102
            $ids = array_merge($ids, array_keys($category->get_children()));
            $courses = array_filter($courses, function($course) use ($ids) {
                return array_search($course->category, $ids) !== false;
            });
            $category = $category->get_db_record();

            $calendar->context = context_coursecat::instance($categoryid);
        } else {
            $course = get_site();
1103
            $courses = calendar_get_default_courses(null, 'id, category, groupmode, groupmodeforce');
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
            $category = null;

            $calendar->context = context_system::instance();
        }

        $calendar->set_sources($course, $courses, $category);

        return $calendar;
    }

1114
1115
1116
1117
1118
1119
1120
    /**
     * Set the time period of this instance.
     *
     * @param   int $time the unixtimestamp representing the date we want to view.
     * @return  $this
     */
    public function set_time($time = null) {
1121
        if (empty($time)) {
1122
            $this->time = time();
1123
1124
        } else {
            $this->time = $time;
1125
        }
1126
1127

        return $this;
1128
1129
    }

1130
    /**
1131
     * Initialize calendar information
1132
     *
1133
     * @deprecated 3.4
1134
     * @param stdClass $course object
1135
     * @param array $coursestoload An array of courses [$course->id => $course]
1136
     * @param bool $ignorefilters options to use filter
1137
1138
     */
    public function prepare_for_view(stdClass $course, array $coursestoload, $ignorefilters = false) {
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
        debugging('The prepare_for_view() function has been deprecated. Please update your code to use set_sources()',
                DEBUG_DEVELOPER);
        $this->set_sources($course, $coursestoload);
    }

    /**
     * Set the sources for events within the calendar.
     *
     * If no category is provided, then the category path for the current
     * course will be used.
     *
     * @param   stdClass    $course The current course being viewed.
1151
     * @param   stdClass[]  $courses The list of all courses currently accessible.
1152
1153
1154
     * @param   stdClass    $category The current category to show.
     */
    public function set_sources(stdClass $course, array $courses, stdClass $category = null) {
1155
1156
        global $USER;

1157
        // A cousre must always be specified.
1158
        $this->course = $course;
1159
1160
1161
1162
        $this->courseid = $course->id;

        list($courseids, $group, $user) = calendar_set_filters($courses);
        $this->courses = $courseids;
1163
1164
        $this->groups = $group;
        $this->users = $user;
1165
1166
1167
1168
1169

        // Do not show category events by default.
        $this->categoryid = null;
        $this->categories = null;

1170
1171
1172
1173
1174
1175
1176
        // Determine the correct category information to show.
        // When called with a course, the category of that course is usually included too.
        // When a category was specifically requested, it should be requested with the site id.
        if (SITEID !== $this->courseid) {
            // A specific course was requested.
            // Fetch the category that this course is in, along with all parents.
            // Do not include child categories of this category, as the user many not have enrolments in those siblings or children.
1177
            $category = \core_course_category::get($course->category, MUST_EXIST, true);
1178
1179
1180
1181
            $this->categoryid = $category->id;

            $this->categories = $category->get_parents();
            $this->categories[] = $category->id;
1182
1183
1184
        } else if (null !== $category && $category->id > 0) {
            // A specific category was requested.
            // Fetch all parents of this category, along with all children too.
1185
            $category = \core_course_category::get($category->id);
1186
1187
1188
1189
            $this->categoryid = $category->id;

            // Build the category list.
            // This includes the current category.
1190
1191
1192
            $this->categories = $category->get_parents();
            $this->categories[] = $category->id;
            $this->categories = array_merge($this->categories, $category->get_all_children_ids());
1193
1194
1195
1196
1197
1198
1199
1200
1201
        } else if (SITEID === $this->courseid) {
            // The site was requested.
            // Fetch all categories where this user has any enrolment, and all categories that this user can manage.

            // Grab the list of categories that this user has courses in.
            $coursecategories = array_flip(array_map(function($course) {
                return $course->category;
            }, $courses));

1202
1203
1204
1205
1206
            $calcatcache = cache::make('core', 'calendar_categories');
            $this->categories = $calcatcache->get('site');
            if ($this->categories === false) {
                // Use the category id as the key in the following array. That way we do not have to remove duplicates.
                $categories = [];
1207
                foreach (\core_course_category::get_all() as $category) {
1208
1209
1210
1211
1212
1213
1214
                    if (isset($coursecategories[$category->id]) ||
                            has_capability('moodle/category:manage', $category->get_context(), $USER, false)) {
                        // If the user has access to a course in this category or can manage the category,
                        // then they can see all parent categories too.
                        $categories[$category->id] = true;
                        foreach ($category->get_parents() as $catid) {
                            $categories[$catid] = true;
1215
1216
                        }
                    }
1217
                }
1218
1219
                $this->categories = array_keys($categories);
                $calcatcache->set('site', $this->categories);
1220
1221
            }
        }
1222
1223
    }

1224
1225
1226
1227
    /**
     * Ensures the date for the calendar is correct and either sets it to now
     * or throws a moodle_exception if not
     *
1228
1229
1230
     * @param bool $defaultonow use current time
     * @throws moodle_exception
     * @return bool validation of checkdate
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
     */
    public function checkdate($defaultonow = true) {
        if (!checkdate($this->month, $this->day, $this->year)) {
            if ($defaultonow) {
                $now = usergetdate(time());
                $this->day = intval($now['mday']);
                $this->month = intval($now['mon']);
                $this->year = intval($now['year']);
                return true;
            } else {
                throw new moodle_exception('invaliddate');
            }
        }
        return true;
    }
1246

1247
1248
    /**
     * Gets todays timestamp for the calendar
1249
1250
     *
     * @return int today timestamp
1251
1252
     */
    public function timestamp_today() {
1253
        return $this->time;
1254
1255
1256
    }
    /**
     * Gets tomorrows timestamp for the calendar
1257
1258
     *
     * @return int tomorrow timestamp
1259
1260
     */
    public function timestamp_tomorrow() {
1261
        return strtotime('+1 day', $this->time);
1262
1263
    }
    /**
1264
     * Adds the pretend blocks for the calendar
1265
1266
     *
     * @param core_calendar_renderer $renderer
1267
1268
     * @param bool $showfilters display filters, false is set as default
     * @param string|null $view preference view options (eg: day, month, upcoming)
1269
1270
     */
    public function add_sidecalendar_blocks(core_calendar_renderer $renderer, $showfilters=false, $view=null) {
1271
1272
1273
        global $PAGE;

        if (!has_capability('moodle/block:view', $PAGE->context) ) {
1274
1275
            return;
        }
1276

1277
1278
        if ($showfilters) {
            $filters = new block_contents();
1279
            $filters->content = $renderer->event_filter();
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
            $filters->footer = '';
            $filters->title = get_string('eventskey', 'calendar');
            $renderer->add_pretend_calendar_block($filters, BLOCK_POS_RIGHT);
        }
        $block = new block_contents;
        $block->content = $renderer->fake_block_threemonths($this);
        $block->footer = '';
        $block->title = get_string('monthlyview', 'calendar');
        $renderer->add_pretend_calendar_block($block, BLOCK_POS_RIGHT);
    }
1290
}
1291

1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
/**
 * Get calendar events.
 *
 * @param int $tstart Start time of time range for events
 * @param int $tend End time of time range for events
 * @param array|int|boolean $users array of users, user id or boolean for all/no user events
 * @param array|int|boolean $groups array of groups, group id or boolean for all/no group events
 * @param array|int|boolean $courses array of courses, course id or boolean for all/no course events
 * @param boolean $withduration whether only events starting within time range selected
 *                              or events in progress/already started selected as well
 * @param boolean $ignorehidden whether to select only visible events or all events
1303
 * @param array|int|boolean $categories array of categories, category id or boolean for all/no course events
1304
1305
 * @return array $events of selected events or an empty array if there aren't any (or there was an error)
 */
1306
1307
function calendar_get_events($tstart, $tend, $users, $groups, $courses,
        $withduration = true, $ignorehidden = true, $categories = []) {
1308
1309
    global $DB;

1310
1311
    $whereclause = '';
    $params = array();
1312
    // Quick test.
1313
    if (empty($users) && empty($groups) && empty($courses) && empty($categories)) {
1314
1315
1316
1317
        return array();
    }

    if ((is_array($users) && !empty($users)) or is_numeric($users)) {
1318
1319
        // Events from a number of users
        if(!empty($whereclause)) $whereclause .= ' OR';
1320
        list($insqlusers, $inparamsusers) = $DB->get_in_or_equal($users, SQL_PARAMS_NAMED);
1321
        $whereclause .= " (e.userid $insqlusers AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)";
1322
        $params = array_merge($params, $inparamsusers);
1323
1324
1325
    } else if($users === true) {
        // Events from ALL users
        if(!empty($whereclause)) $whereclause .= ' OR';
1326
        $whereclause .= ' (e.userid != 0 AND e.courseid = 0 AND e.groupid = 0 AND e.categoryid = 0)';
1327
1328
    } else if($users === false) {
        // No user at all, do nothing
1329
1330
1331
    }

    if ((is_array($groups) && !empty($groups)) or is_numeric($groups)) {
1332
1333
        // Events from a number of groups
        if(!empty($whereclause)) $whereclause .= ' OR';
1334
        list($insqlgroups, $inparamsgroups) = $DB->get_in_or_equal($groups, SQL_PARAMS_NAMED);
1335
        $whereclause .= " e.groupid $insqlgroups ";
1336
        $params = array_merge($params, $inparamsgroups);
1337
1338
1339
1340
    } else if($groups === true) {
        // Events from ALL groups
        if(!empty($whereclause)) $whereclause .= ' OR ';
        $whereclause .= ' e.groupid != 0';
1341
    }
1342
    // boolean false (no groups at all): we don't need to do anything
1343
1344

    if ((is_array($courses) && !empty($courses)) or is_numeric($courses)) {
1345
        if(!empty($whereclause)) $whereclause .= ' OR';
1346
        list($insqlcourses, $inparamscourses) = $DB->get_in_or_equal($courses, SQL_PARAMS_NAMED);
1347
        $whereclause .= " (e.groupid = 0 AND e.courseid $insqlcourses)";
1348
1349
        $params = array_merge($params, $inparamscourses);
    } else if ($courses === true) {
1350
1351
1352
        // Events from ALL courses
        if(!empty($whereclause)) $whereclause .= ' OR';
        $whereclause .= ' (e.groupid = 0 AND e.courseid != 0)';
1353
1354
    }

1355
    if ((is_array($categories) && !empty($categories)) || is_numeric($categories)) {
1356
1357
1358
        if (!empty($whereclause)) {
            $whereclause .= ' OR';
        }
1359
1360
1361
1362
1363
        list($insqlcategories, $inparamscategories) = $DB->get_in_or_equal($categories, SQL_PARAMS_NAMED);
        $whereclause .= " (e.groupid = 0 AND e.courseid = 0 AND e.categoryid $insqlcategories)";
        $params = array_merge($params, $inparamscategories);
    } else if ($categories === true) {
        // Events from ALL categories.
1364
1365
1366
        if (!empty($whereclause)) {
            $whereclause .= ' OR';
        }
1367
1368
1369
        $whereclause .= ' (e.groupid = 0 AND e.courseid = 0 AND e.categoryid != 0)';
    }

1370
1371
1372
1373
    // Security check: if, by now, we have NOTHING in $whereclause, then it means
    // that NO event-selecting clauses were defined. Thus, we won't be returning ANY
    // events no matter what. Allowing the code to proceed might return a completely
    // valid query with only time constraints, thus selecting ALL events in that time frame!
1374
    if(empty($whereclause)) {
1375
1376
1377
        return array();
    }

1378
1379
    if($withduration) {
        $timeclause = '(e.timestart >= '.$tstart.' OR e.timestart + e.timeduration > '.$tstart.') AND e.timestart <= '.$tend;
1380
    }
1381
1382
    else {
        $timeclause = 'e.timestart >= '.$tstart.' AND e.timestart <= '.$tend;
1383
    }
1384
1385
1386
    if(!empty($whereclause)) {
        // We have additional constraints
        $whereclause = $timeclause.' AND ('.$whereclause.')';
1387
    }
1388
1389
1390
    else {
        // Just basic time filtering
        $whereclause = $timeclause;
1391
1392
    }

1393
1394
    if ($ignorehidden) {
        $whereclause .= ' AND e.visible = 1';
1395
1396
1397
    }

    $sql = "SELECT e.*
1398
1399
1400
1401
1402
              FROM {event} e
         LEFT JOIN {modules} m ON e.modulename = m.name
                -- Non visible modules will have a value of 0.
             WHERE (m.visible = 1 OR m.visible IS NULL) AND $whereclause
          ORDER BY e.timestart";
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
    $events = $DB->get_records_sql($sql, $params);

    if ($events === false) {
        $events = array();
    }
    return $events;
}

/**
 * Return the days of the week.
 *
 * @return array array of days
 */
function calendar_get_days() {
1417
1418
    $calendartype = \core_calendar\type_factory::get_calendar_instance();
    return $calendartype->get_weekdays();
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
}

/**
 * Get the subscription from a given id.
 *
 * @since Moodle 2.5
 * @param int $id id of the subscription
 * @return stdClass Subscription record from DB
 * @throws moodle_exception for an invalid id
 */
function calendar_get_subscription($id) {
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
    global $DB;

    $cache = \cache::make('core', 'calendar_subscriptions');
    $subscription = $cache->get($id);
    if (empty($subscription)) {
        $subscription = $DB->get_record('event_subscriptions', array('id' => $id), '*', MUST_EXIST);
        $cache->set($id, $subscription);
    }

    return $subscription;
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
}

/**
 * Gets the first day of the week.
 *
 * Used to be define('CALENDAR_STARTING_WEEKDAY', blah);
 *
 * @return int
 */
function calendar_get_starting_weekday() {
1450
1451
    $calendartype = \core_calendar\type_factory::get_calendar_instance();
    return $calendartype->get_starting_weekday();
1452
1453
1454
1455
1456
}

/**
 * Get a HTML link to a course.
 *
1457
 * @param int|stdClass $course the course id or course object
1458
1459
 * @return string a link to the course (as HTML); empty if the course id is invalid
 */
1460
1461
function calendar_get_courselink($course) {
    if (!$course) {
1462
1463
1464
        return '';
    }

1465
1466
1467
1468
1469
1470
    if (!is_object($course)) {
        $course = calendar_get_course_cached($coursecache, $course);
    }
    $context = \context_course::instance($course->id);
    $fullname = format_string($course->fullname, true, array('context' => $context));
    $url = new \moodle_url('/course/view.php', array('id' => $course->id));
1471
1472
1473
    $link = \html_writer::link($url, $fullname);

    return $link;
1474
1475
1476
1477
1478
}

/**
 * Get current module cache.
 *
1479
 * Only use this method if you do not know courseid. Otherwise use:
1480
1481
 * get_fast_modinfo($courseid)->instances[$modulename][$instance]
 *
1482
 * @param array $modulecache in memory module cache
1483
1484
1485
1486
 * @param string $modulename name of the module
 * @param int $instance module instance number
 * @return stdClass|bool $module information
 */
1487
1488
1489
function calendar_get_module_cached(&$modulecache, $modulename, $instance) {
    if (!isset($modulecache[$modulename . '_' . $instance])) {
        $modulecache[$modulename . '_' . $instance] = get_coursemodule_from_instance($modulename, $instance);
1490
    }
1491
1492

    return $modulecache[$modulename . '_' . $instance];
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
}

/**
 * Get current course cache.
 *
 * @param array $coursecache list of course cache
 * @param int $courseid id of the course
 * @return stdClass $coursecache[$courseid] return the specific course cache
 */
function calendar_get_course_cached(&$coursecache, $courseid) {
1503
1504
1505
1506
    if (!isset($coursecache[$courseid])) {
        $coursecache[$courseid] = get_course($courseid);
    }
    return $coursecache[$courseid];
1507
1508
1509
1510
1511
1512
1513
1514
1515
}

/**
 * Get group from groupid for calendar display
 *
 * @param int $groupid
 * @return stdClass group object with fields 'id', 'name' and 'courseid'
 */
function calendar_get_group_cached($groupid) {
1516
1517
1518
1519
1520
    static $groupscache = array();
    if (!isset($groupscache[$groupid])) {
        $groupscache[$groupid] = groups_get_group($groupid, 'id,name,courseid');
    }
    return $groupscache[$groupid];
1521
1522
1523
1524
1525
1526
1527
1528
1529
}

/**
 * Add calendar event metadata
 *
 * @param stdClass $event event info
 * @return stdClass $event metadata
 */
function calendar_add_event_metadata($event) {
1530
1531
1532
1533
1534
1535
1536
1537
    global $CFG, $OUTPUT;

    // Support multilang in event->name.
    $event->name = format_string($event->name, true);

    if (!empty($event->modulename)) { // Activity event.
        // The module name is set. I will assume that it has to be displayed, and
        // also that it is an automatically-generated event. And of course that the
1538
1539
1540
        // instace id and modulename are set correctly.
        $instances = get_fast_modinfo($event->courseid)->get_instances_of($event->modulename);
        if (!array_key_exists($event->instance, $instances)) {
1541
1542
            return;
        }
1543
        $module = $instances[$event->instance];
1544

1545
        $modulename = $module->get_module_type_name(false);
1546
1547
1548
1549
1550
1551
1552
        if (get_string_manager()->string_exists($event->eventtype, $event->modulename)) {
            // Will be used as alt text if the event icon.
            $eventtype = get_string($event->eventtype, $event->modulename);
        } else {
            $eventtype = '';
        }

1553
1554
1555
1556
        $event->icon = '<img src="' . s($module->get_icon_url()) . '" alt="' . s($eventtype) .
            '" title="' . s($modulename) . '" class="icon" />';
        $event->referer = html_writer::link($module->url, $event->name);
        $event->courselink = calendar_get_courselink($module->get_course());
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
        $event->cmid = $module->id;
    } else if ($event->courseid == SITEID) { // Site event.
        $event->icon = '<img src="' . $OUTPUT->image_url('i/siteevent') . '" alt="' .
            get_string('globalevent', 'calendar') . '" class="icon" />';
        $event->cssclass = 'calendar_event_global';
    } else if ($event->courseid != 0 && $event->courseid != SITEID && $event->groupid == 0) { // Course event.
        $event->icon = '<img src="' . $OUTPUT->image_url('i/courseevent') . '" alt="' .
            get_string('courseevent', 'calendar') . '" class="icon" />';
        $event->courselink = calendar_get_courselink($event->courseid);
        $event->cssclass = 'calendar_event_course';
    } else if ($event->groupid) { // Group event.
        if ($group = calendar_get_group_cached($event->groupid)) {
            $groupname = format_string($group->name, true, \context_course::instance($group->courseid));
        } else {
            $groupname = '';
        }
        $event->icon = \html_writer::empty_tag('image', array('src' => $OUTPUT->image_url('i/groupevent'),
            'alt' => get_string('groupevent', 'calendar'), 'title' => $groupname, 'class' => 'icon'));
        $event->courselink = calendar_get_courselink($event->courseid) . ', ' . $groupname;
        $event->cssclass = 'calendar_event_group';
    } else if ($event->userid) { // User event.
        $event->icon = '<img src="' . $OUTPUT->image_url('i/userevent') . '" alt="' .
            get_string('userevent', 'calendar') . '" class="icon" />';
        $event->cssclass = 'calendar_event_user';
    }

    return $event;
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
}

/**
 * Get calendar events by id.
 *
 * @since Moodle 2.5
 * @param array $eventids list of event ids
 * @return array Array of event entries, empty array if nothing found
 */
function calendar_get_events_by_id($eventids) {
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
    global $DB;

    if (!is_array($eventids) || empty($eventids)) {
        return array();
    }

    list($wheresql, $params) = $DB->get_in_or_equal($eventids);
    $wheresql = "id $wheresql";

    return $DB->get_records_select('event', $wheresql, $params);
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
}

/**
 * Get control options for calendar.
 *