Proyectos de Subversion Moodle

Rev

| 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
 * Classes representing HTML elements, used by $OUTPUT methods
19
 *
20
 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
21
 * for an overview.
22
 *
23
 * @package core
24
 * @category output
25
 * @copyright 2009 Tim Hunt
26
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27
 */
28
 
29
use core\output\local\action_menu\subpanel;
30
 
31
defined('MOODLE_INTERNAL') || die();
32
 
33
/**
34
 * Interface marking other classes as suitable for renderer_base::render()
35
 *
36
 * @copyright 2010 Petr Skoda (skodak) info@skodak.org
37
 * @package core
38
 * @category output
39
 */
40
interface renderable {
41
    // intentionally empty
42
}
43
 
44
/**
45
 * Interface marking other classes having the ability to export their data for use by templates.
46
 *
47
 * @copyright 2015 Damyon Wiese
48
 * @package core
49
 * @category output
50
 * @since 2.9
51
 */
52
interface templatable {
53
 
54
    /**
55
     * Function to export the renderer data in a format that is suitable for a
56
     * mustache template. This means:
57
     * 1. No complex types - only stdClass, array, int, string, float, bool
58
     * 2. Any additional info that is required for the template is pre-calculated (e.g. capability checks).
59
     *
60
     * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
61
     * @return stdClass|array
62
     */
63
    public function export_for_template(renderer_base $output);
64
}
65
 
66
/**
67
 * Data structure representing a file picker.
68
 *
69
 * @copyright 2010 Dongsheng Cai
70
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
71
 * @since Moodle 2.0
72
 * @package core
73
 * @category output
74
 */
75
class file_picker implements renderable {
76
 
77
    /**
78
     * @var stdClass An object containing options for the file picker
79
     */
80
    public $options;
81
 
82
    /**
83
     * Constructs a file picker object.
84
     *
85
     * The following are possible options for the filepicker:
86
     *    - accepted_types  (*)
87
     *    - return_types    (FILE_INTERNAL)
88
     *    - env             (filepicker)
89
     *    - client_id       (uniqid)
90
     *    - itemid          (0)
91
     *    - maxbytes        (-1)
92
     *    - maxfiles        (1)
93
     *    - buttonname      (false)
94
     *
95
     * @param stdClass $options An object containing options for the file picker.
96
     */
97
    public function __construct(stdClass $options) {
98
        global $CFG, $USER, $PAGE;
99
        require_once($CFG->dirroot. '/repository/lib.php');
100
        $defaults = array(
101
            'accepted_types'=>'*',
102
            'return_types'=>FILE_INTERNAL,
103
            'env' => 'filepicker',
104
            'client_id' => uniqid(),
105
            'itemid' => 0,
106
            'maxbytes'=>-1,
107
            'maxfiles'=>1,
108
            'buttonname'=>false
109
        );
110
        foreach ($defaults as $key=>$value) {
111
            if (empty($options->$key)) {
112
                $options->$key = $value;
113
            }
114
        }
115
 
116
        $options->currentfile = '';
117
        if (!empty($options->itemid)) {
118
            $fs = get_file_storage();
119
            $usercontext = context_user::instance($USER->id);
120
            if (empty($options->filename)) {
121
                if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
122
                    $file = reset($files);
123
                }
124
            } else {
125
                $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
126
            }
127
            if (!empty($file)) {
128
                $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
129
            }
130
        }
131
 
132
        // initilise options, getting files in root path
133
        $this->options = initialise_filepicker($options);
134
 
135
        // copying other options
136
        foreach ($options as $name=>$value) {
137
            if (!isset($this->options->$name)) {
138
                $this->options->$name = $value;
139
            }
140
        }
141
    }
142
}
143
 
144
/**
145
 * Data structure representing a user picture.
146
 *
147
 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
148
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
149
 * @since Modle 2.0
150
 * @package core
151
 * @category output
152
 */
153
class user_picture implements renderable {
154
    /**
155
     * @var stdClass A user object with at least fields all columns specified
156
     * in $fields array constant set.
157
     */
158
    public $user;
159
 
160
    /**
161
     * @var int The course id. Used when constructing the link to the user's
162
     * profile, page course id used if not specified.
163
     */
164
    public $courseid;
165
 
166
    /**
167
     * @var bool Add course profile link to image
168
     */
169
    public $link = true;
170
 
171
    /**
172
     * @var int Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility.
173
     * Recommended values (supporting user initials too): 16, 35, 64 and 100.
174
     */
175
    public $size = 35;
176
 
177
    /**
178
     * @var bool Add non-blank alt-text to the image.
179
     * Default true, set to false when image alt just duplicates text in screenreaders.
180
     */
181
    public $alttext = true;
182
 
183
    /**
184
     * @var bool Whether or not to open the link in a popup window.
185
     */
186
    public $popup = false;
187
 
188
    /**
189
     * @var string Image class attribute
190
     */
191
    public $class = 'userpicture';
192
 
193
    /**
194
     * @var bool Whether to be visible to screen readers.
195
     */
196
    public $visibletoscreenreaders = true;
197
 
198
    /**
199
     * @var bool Whether to include the fullname in the user picture link.
200
     */
201
    public $includefullname = false;
202
 
203
    /**
204
     * @var mixed Include user authentication token. True indicates to generate a token for current user, and integer value
205
     * indicates to generate a token for the user whose id is the value indicated.
206
     */
207
    public $includetoken = false;
208
 
209
    /**
210
     * User picture constructor.
211
     *
212
     * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
213
     *                 It is recommended to add also contextid of the user for performance reasons.
214
     */
215
    public function __construct(stdClass $user) {
216
        global $DB;
217
 
218
        if (empty($user->id)) {
219
            throw new coding_exception('User id is required when printing user avatar image.');
220
        }
221
 
222
        // only touch the DB if we are missing data and complain loudly...
223
        $needrec = false;
224
        foreach (\core_user\fields::get_picture_fields() as $field) {
225
            if (!property_exists($user, $field)) {
226
                $needrec = true;
227
                debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
228
                    .'Please use the \core_user\fields API to get the full list of required fields.', DEBUG_DEVELOPER);
229
                break;
230
            }
231
        }
232
 
233
        if ($needrec) {
234
            $this->user = $DB->get_record('user', array('id' => $user->id),
235
                implode(',', \core_user\fields::get_picture_fields()), MUST_EXIST);
236
        } else {
237
            $this->user = clone($user);
238
        }
239
    }
240
 
241
    /**
242
     * Returns a list of required user fields, useful when fetching required user info from db.
243
     *
244
     * In some cases we have to fetch the user data together with some other information,
245
     * the idalias is useful there because the id would otherwise override the main
246
     * id of the result record. Please note it has to be converted back to id before rendering.
247
     *
248
     * @param string $tableprefix name of database table prefix in query
249
     * @param array $extrafields extra fields to be included in result (do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
250
     * @param string $idalias alias of id field
251
     * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
252
     * @return string
253
     * @deprecated since Moodle 3.11 MDL-45242
254
     * @see \core_user\fields
255
     */
256
    public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
257
        debugging('user_picture::fields() is deprecated. Please use the \core_user\fields API instead.', DEBUG_DEVELOPER);
258
        $userfields = \core_user\fields::for_userpic();
259
        if ($extrafields) {
260
            $userfields->including(...$extrafields);
261
        }
262
        $selects = $userfields->get_sql($tableprefix, false, $fieldprefix, $idalias, false)->selects;
263
        if ($tableprefix === '') {
264
            // If no table alias is specified, don't add {user}. in front of fields.
265
            $selects = str_replace('{user}.', '', $selects);
266
        }
267
        // Maintain legacy behaviour where the field list was done with 'implode' and no spaces.
268
        $selects = str_replace(', ', ',', $selects);
269
        return $selects;
270
    }
271
 
272
    /**
273
     * Extract the aliased user fields from a given record
274
     *
275
     * Given a record that was previously obtained using {@link self::fields()} with aliases,
276
     * this method extracts user related unaliased fields.
277
     *
278
     * @param stdClass $record containing user picture fields
279
     * @param array $extrafields extra fields included in the $record
280
     * @param string $idalias alias of the id field
281
     * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
282
     * @return stdClass object with unaliased user fields
283
     */
284
    public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
285
 
286
        if (empty($idalias)) {
287
            $idalias = 'id';
288
        }
289
 
290
        $return = new stdClass();
291
 
292
        foreach (\core_user\fields::get_picture_fields() as $field) {
293
            if ($field === 'id') {
294
                if (property_exists($record, $idalias)) {
295
                    $return->id = $record->{$idalias};
296
                }
297
            } else {
298
                if (property_exists($record, $fieldprefix.$field)) {
299
                    $return->{$field} = $record->{$fieldprefix.$field};
300
                }
301
            }
302
        }
303
        // add extra fields if not already there
304
        if ($extrafields) {
305
            foreach ($extrafields as $e) {
306
                if ($e === 'id' or property_exists($return, $e)) {
307
                    continue;
308
                }
309
                $return->{$e} = $record->{$fieldprefix.$e};
310
            }
311
        }
312
 
313
        return $return;
314
    }
315
 
316
    /**
317
     * Works out the URL for the users picture.
318
     *
319
     * This method is recommended as it avoids costly redirects of user pictures
320
     * if requests are made for non-existent files etc.
321
     *
322
     * @param moodle_page $page
323
     * @param renderer_base $renderer
324
     * @return moodle_url
325
     */
326
    public function get_url(moodle_page $page, renderer_base $renderer = null) {
327
        global $CFG;
328
 
329
        if (is_null($renderer)) {
330
            $renderer = $page->get_renderer('core');
331
        }
332
 
333
        // Sort out the filename and size. Size is only required for the gravatar
334
        // implementation presently.
335
        if (empty($this->size)) {
336
            $filename = 'f2';
337
            $size = 35;
338
        } else if ($this->size === true or $this->size == 1) {
339
            $filename = 'f1';
340
            $size = 100;
341
        } else if ($this->size > 100) {
342
            $filename = 'f3';
343
            $size = (int)$this->size;
344
        } else if ($this->size >= 50) {
345
            $filename = 'f1';
346
            $size = (int)$this->size;
347
        } else {
348
            $filename = 'f2';
349
            $size = (int)$this->size;
350
        }
351
 
352
        $defaulturl = $renderer->image_url('u/'.$filename); // default image
353
 
354
        if ((!empty($CFG->forcelogin) and !isloggedin()) ||
355
            (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
356
            // Protect images if login required and not logged in;
357
            // also if login is required for profile images and is not logged in or guest
358
            // do not use require_login() because it is expensive and not suitable here anyway.
359
            return $defaulturl;
360
        }
361
 
362
        // First try to detect deleted users - but do not read from database for performance reasons!
363
        if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
364
            // All deleted users should have email replaced by md5 hash,
365
            // all active users are expected to have valid email.
366
            return $defaulturl;
367
        }
368
 
369
        // Did the user upload a picture?
370
        if ($this->user->picture > 0) {
371
            if (!empty($this->user->contextid)) {
372
                $contextid = $this->user->contextid;
373
            } else {
374
                $context = context_user::instance($this->user->id, IGNORE_MISSING);
375
                if (!$context) {
376
                    // This must be an incorrectly deleted user, all other users have context.
377
                    return $defaulturl;
378
                }
379
                $contextid = $context->id;
380
            }
381
 
382
            $path = '/';
383
            if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
384
                // We append the theme name to the file path if we have it so that
385
                // in the circumstance that the profile picture is not available
386
                // when the user actually requests it they still get the profile
387
                // picture for the correct theme.
388
                $path .= $page->theme->name.'/';
389
            }
390
            // Set the image URL to the URL for the uploaded file and return.
391
            $url = moodle_url::make_pluginfile_url(
392
                $contextid, 'user', 'icon', null, $path, $filename, false, $this->includetoken);
393
            $url->param('rev', $this->user->picture);
394
            return $url;
395
        }
396
 
397
        if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
398
            // Normalise the size variable to acceptable bounds
399
            if ($size < 1 || $size > 512) {
400
                $size = 35;
401
            }
402
            // Hash the users email address
403
            $md5 = md5(strtolower(trim($this->user->email)));
404
            // Build a gravatar URL with what we know.
405
 
406
            // Find the best default image URL we can (MDL-35669)
407
            if (empty($CFG->gravatardefaulturl)) {
408
                $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
409
                if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
410
                    $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
411
                } else {
412
                    $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
413
                }
414
            } else {
415
                $gravatardefault = $CFG->gravatardefaulturl;
416
            }
417
 
418
            // If the currently requested page is https then we'll return an
419
            // https gravatar page.
420
            if (is_https()) {
421
                return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
422
            } else {
423
                return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
424
            }
425
        }
426
 
427
        return $defaulturl;
428
    }
429
}
430
 
431
/**
432
 * Data structure representing a help icon.
433
 *
434
 * @copyright 2010 Petr Skoda (info@skodak.org)
435
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
436
 * @since Moodle 2.0
437
 * @package core
438
 * @category output
439
 */
440
class help_icon implements renderable, templatable {
441
 
442
    /**
443
     * @var string lang pack identifier (without the "_help" suffix),
444
     * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
445
     * must exist.
446
     */
447
    public $identifier;
448
 
449
    /**
450
     * @var string Component name, the same as in get_string()
451
     */
452
    public $component;
453
 
454
    /**
455
     * @var string Extra descriptive text next to the icon
456
     */
457
    public $linktext = null;
458
 
459
    /**
460
     * @var mixed An object, string or number that can be used within translation strings
461
     */
462
    public $a = null;
463
 
464
    /**
465
     * Constructor
466
     *
467
     * @param string $identifier string for help page title,
468
     *  string with _help suffix is used for the actual help text.
469
     *  string with _link suffix is used to create a link to further info (if it exists)
470
     * @param string $component
471
     * @param string|object|array|int $a An object, string or number that can be used
472
     *      within translation strings
473
     */
474
    public function __construct($identifier, $component, $a = null) {
475
        $this->identifier = $identifier;
476
        $this->component  = $component;
477
        $this->a = $a;
478
    }
479
 
480
    /**
481
     * Verifies that both help strings exists, shows debug warnings if not
482
     */
483
    public function diag_strings() {
484
        $sm = get_string_manager();
485
        if (!$sm->string_exists($this->identifier, $this->component)) {
486
            debugging("Help title string does not exist: [$this->identifier, $this->component]");
487
        }
488
        if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
489
            debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
490
        }
491
    }
492
 
493
    /**
494
     * Export this data so it can be used as the context for a mustache template.
495
     *
496
     * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
497
     * @return stdClass
498
     */
499
    public function export_for_template(renderer_base $output) {
500
        global $CFG;
501
 
502
        $title = get_string($this->identifier, $this->component, $this->a);
503
 
504
        if (empty($this->linktext)) {
505
            $alt = get_string('helpprefix2', '', trim($title, ". \t"));
506
        } else {
507
            $alt = get_string('helpwiththis');
508
        }
509
 
510
        $data = get_formatted_help_string($this->identifier, $this->component, false, $this->a);
511
 
512
        $data->alt = $alt;
513
        $data->icon = (new pix_icon('help', $alt, 'core', ['class' => 'iconhelp']))->export_for_template($output);
514
        $data->linktext = $this->linktext;
515
        $data->title = get_string('helpprefix2', '', trim($title, ". \t"));
516
 
517
        $options = [
518
            'component' => $this->component,
519
            'identifier' => $this->identifier,
520
            'lang' => current_language()
521
        ];
522
 
523
        // Debugging feature lets you display string identifier and component.
524
        if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
525
            $options['strings'] = 1;
526
        }
527
 
528
        $data->url = (new moodle_url('/help.php', $options))->out(false);
529
        $data->ltr = !right_to_left();
530
        return $data;
531
    }
532
}
533
 
534
 
535
/**
536
 * Data structure representing an icon font.
537
 *
538
 * @copyright 2016 Damyon Wiese
539
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
540
 * @package core
541
 * @category output
542
 */
543
class pix_icon_font implements templatable {
544
 
545
    /**
546
     * @var pix_icon $pixicon The original icon.
547
     */
548
    private $pixicon = null;
549
 
550
    /**
551
     * @var string $key The mapped key.
552
     */
553
    private $key;
554
 
555
    /**
556
     * @var bool $mapped The icon could not be mapped.
557
     */
558
    private $mapped;
559
 
560
    /**
561
     * Constructor
562
     *
563
     * @param pix_icon $pixicon The original icon
564
     */
565
    public function __construct(pix_icon $pixicon) {
566
        global $PAGE;
567
 
568
        $this->pixicon = $pixicon;
569
        $this->mapped = false;
570
        $iconsystem = \core\output\icon_system::instance();
571
 
572
        $this->key = $iconsystem->remap_icon_name($pixicon->pix, $pixicon->component);
573
        if (!empty($this->key)) {
574
            $this->mapped = true;
575
        }
576
    }
577
 
578
    /**
579
     * Return true if this pix_icon was successfully mapped to an icon font.
580
     *
581
     * @return bool
582
     */
583
    public function is_mapped() {
584
        return $this->mapped;
585
    }
586
 
587
    /**
588
     * Export this data so it can be used as the context for a mustache template.
589
     *
590
     * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
591
     * @return array
592
     */
593
    public function export_for_template(renderer_base $output) {
594
 
595
        $pixdata = $this->pixicon->export_for_template($output);
596
 
597
        $title = isset($this->pixicon->attributes['title']) ? $this->pixicon->attributes['title'] : '';
598
        $alt = isset($this->pixicon->attributes['alt']) ? $this->pixicon->attributes['alt'] : '';
599
        if (empty($title)) {
600
            $title = $alt;
601
        }
602
        $data = array(
603
            'extraclasses' => $pixdata['extraclasses'],
604
            'title' => $title,
605
            'alt' => $alt,
606
            'key' => $this->key
607
        );
608
 
609
        return $data;
610
    }
611
}
612
 
613
/**
614
 * Data structure representing an icon subtype.
615
 *
616
 * @copyright 2016 Damyon Wiese
617
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
618
 * @package core
619
 * @category output
620
 */
621
class pix_icon_fontawesome extends pix_icon_font {
622
 
623
}
624
 
625
/**
626
 * Data structure representing an icon.
627
 *
628
 * @copyright 2010 Petr Skoda
629
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
630
 * @since Moodle 2.0
631
 * @package core
632
 * @category output
633
 */
634
class pix_icon implements renderable, templatable {
635
 
636
    /**
637
     * @var string The icon name
638
     */
639
    var $pix;
640
 
641
    /**
642
     * @var string The component the icon belongs to.
643
     */
644
    var $component;
645
 
646
    /**
647
     * @var array An array of attributes to use on the icon
648
     */
649
    var $attributes = array();
650
 
651
    /**
652
     * Constructor
653
     *
654
     * @param string $pix short icon name
655
     * @param string $alt The alt text to use for the icon
656
     * @param string $component component name
657
     * @param array $attributes html attributes
658
     */
659
    public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
660
        global $PAGE;
661
 
662
        $this->pix = $pix;
663
        $this->component  = $component;
664
        $this->attributes = (array)$attributes;
665
 
666
        if (empty($this->attributes['class'])) {
667
            $this->attributes['class'] = '';
668
        }
669
 
670
        // Set an additional class for big icons so that they can be styled properly.
671
        if (substr($pix, 0, 2) === 'b/') {
672
            $this->attributes['class'] .= ' iconsize-big';
673
        }
674
 
675
        // If the alt is empty, don't place it in the attributes, otherwise it will override parent alt text.
676
        if (!is_null($alt)) {
677
            $this->attributes['alt'] = $alt;
678
 
679
            // If there is no title, set it to the attribute.
680
            if (!isset($this->attributes['title'])) {
681
                $this->attributes['title'] = $this->attributes['alt'];
682
            }
683
        } else {
684
            unset($this->attributes['alt']);
685
        }
686
 
687
        if (empty($this->attributes['title'])) {
688
            // Remove the title attribute if empty, we probably want to use the parent node's title
689
            // and some browsers might overwrite it with an empty title.
690
            unset($this->attributes['title']);
691
        }
692
 
693
        // Hide icons from screen readers that have no alt.
694
        if (empty($this->attributes['alt'])) {
695
            $this->attributes['aria-hidden'] = 'true';
696
        }
697
    }
698
 
699
    /**
700
     * Export this data so it can be used as the context for a mustache template.
701
     *
702
     * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
703
     * @return array
704
     */
705
    public function export_for_template(renderer_base $output) {
706
        $attributes = $this->attributes;
707
        $extraclasses = '';
708
 
709
        foreach ($attributes as $key => $item) {
710
            if ($key == 'class') {
711
                $extraclasses = $item;
712
                unset($attributes[$key]);
713
                break;
714
            }
715
        }
716
 
717
        $attributes['src'] = $output->image_url($this->pix, $this->component)->out(false);
718
        $templatecontext = array();
719
        foreach ($attributes as $name => $value) {
720
            $templatecontext[] = array('name' => $name, 'value' => $value);
721
        }
722
        $title = isset($attributes['title']) ? $attributes['title'] : '';
723
        if (empty($title)) {
724
            $title = isset($attributes['alt']) ? $attributes['alt'] : '';
725
        }
726
        $data = array(
727
            'attributes' => $templatecontext,
728
            'extraclasses' => $extraclasses
729
        );
730
 
731
        return $data;
732
    }
733
 
734
    /**
735
     * Much simpler version of export that will produce the data required to render this pix with the
736
     * pix helper in a mustache tag.
737
     *
738
     * @return array
739
     */
740
    public function export_for_pix() {
741
        $title = isset($this->attributes['title']) ? $this->attributes['title'] : '';
742
        if (empty($title)) {
743
            $title = isset($this->attributes['alt']) ? $this->attributes['alt'] : '';
744
        }
745
        return [
746
            'key' => $this->pix,
747
            'component' => $this->component,
748
            'title' => (string) $title,
749
        ];
750
    }
751
}
752
 
753
/**
754
 * Data structure representing an activity icon.
755
 *
756
 * The difference is that activity icons will always render with the standard icon system (no font icons).
757
 *
758
 * @copyright 2017 Damyon Wiese
759
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
760
 * @package core
761
 */
762
class image_icon extends pix_icon {
763
}
764
 
765
/**
766
 * Data structure representing an emoticon image
767
 *
768
 * @copyright 2010 David Mudrak
769
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
770
 * @since Moodle 2.0
771
 * @package core
772
 * @category output
773
 */
774
class pix_emoticon extends pix_icon implements renderable {
775
 
776
    /**
777
     * Constructor
778
     * @param string $pix short icon name
779
     * @param string $alt alternative text
780
     * @param string $component emoticon image provider
781
     * @param array $attributes explicit HTML attributes
782
     */
783
    public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
784
        if (empty($attributes['class'])) {
785
            $attributes['class'] = 'emoticon';
786
        }
787
        parent::__construct($pix, $alt, $component, $attributes);
788
    }
789
}
790
 
791
/**
792
 * Data structure representing a simple form with only one button.
793
 *
794
 * @copyright 2009 Petr Skoda
795
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
796
 * @since Moodle 2.0
797
 * @package core
798
 * @category output
799
 */
800
class single_button implements renderable {
801
 
802
    /**
803
     * Possible button types. From boostrap.
804
     */
805
    const BUTTON_TYPES = [
806
        self::BUTTON_PRIMARY,
807
        self::BUTTON_SECONDARY,
808
        self::BUTTON_SUCCESS,
809
        self::BUTTON_DANGER,
810
        self::BUTTON_WARNING,
811
        self::BUTTON_INFO
812
    ];
813
 
814
    /**
815
     * Possible button types - Primary.
816
     */
817
    const BUTTON_PRIMARY = 'primary';
818
    /**
819
     * Possible button types - Secondary.
820
     */
821
    const BUTTON_SECONDARY = 'secondary';
822
    /**
823
     * Possible button types - Danger.
824
     */
825
    const BUTTON_DANGER = 'danger';
826
    /**
827
     * Possible button types - Success.
828
     */
829
    const BUTTON_SUCCESS = 'success';
830
    /**
831
     * Possible button types - Warning.
832
     */
833
    const BUTTON_WARNING = 'warning';
834
    /**
835
     * Possible button types - Info.
836
     */
837
    const BUTTON_INFO = 'info';
838
 
839
    /**
840
     * @var moodle_url Target url
841
     */
842
    public $url;
843
 
844
    /**
845
     * @var string Button label
846
     */
847
    public $label;
848
 
849
    /**
850
     * @var string Form submit method post or get
851
     */
852
    public $method = 'post';
853
 
854
    /**
855
     * @var string Wrapping div class
856
     */
857
    public $class = 'singlebutton';
858
 
859
    /**
860
     * @var string Type of button (from defined types). Used for styling.
861
     */
862
    protected $type;
863
 
864
    /**
865
     * @var bool True if button is primary button. Used for styling.
866
     * @deprecated since Moodle 4.2
867
     */
868
    private $primary = false;
869
 
870
    /**
871
     * @var bool True if button disabled, false if normal
872
     */
873
    public $disabled = false;
874
 
875
    /**
876
     * @var string Button tooltip
877
     */
878
    public $tooltip = null;
879
 
880
    /**
881
     * @var string Form id
882
     */
883
    public $formid;
884
 
885
    /**
886
     * @var array List of attached actions
887
     */
888
    public $actions = array();
889
 
890
    /**
891
     * @var array $params URL Params
892
     */
893
    public $params;
894
 
895
    /**
896
     * @var string Action id
897
     */
898
    public $actionid;
899
 
900
    /**
901
     * @var array
902
     */
903
    protected $attributes = [];
904
 
905
    /**
906
     * Constructor
907
     *
908
     * @param moodle_url $url
909
     * @param string $label button text
910
     * @param string $method get or post submit method
911
     * @param string $type whether this is a primary button or another type, used for styling
912
     * @param array $attributes Attributes for the HTML button tag
913
     */
914
    public function __construct(moodle_url $url, $label, $method = 'post', $type = self::BUTTON_SECONDARY,
915
        $attributes = []) {
916
        if (is_bool($type)) {
917
            debugging('The boolean $primary is deprecated and replaced by $type,
918
            use single_button::BUTTON_PRIMARY or self::BUTTON_SECONDARY instead');
919
            $type = $type ? self::BUTTON_PRIMARY : self::BUTTON_SECONDARY;
920
        }
921
        $this->url = clone($url);
922
        $this->label = $label;
923
        $this->method = $method;
924
        $this->type = $type;
925
        $this->attributes = $attributes;
926
    }
927
 
928
    /**
929
     * Shortcut for adding a JS confirm dialog when the button is clicked.
930
     * The message must be a yes/no question.
931
     *
932
     * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
933
     */
934
    public function add_confirm_action($confirmmessage) {
935
        $this->add_action(new confirm_action($confirmmessage));
936
    }
937
 
938
    /**
939
     * Add action to the button.
940
     * @param component_action $action
941
     */
942
    public function add_action(component_action $action) {
943
        $this->actions[] = $action;
944
    }
945
 
946
    /**
947
     * Sets an attribute for the HTML button tag.
948
     *
949
     * @param  string $name  The attribute name
950
     * @param  mixed  $value The value
951
     * @return null
952
     */
953
    public function set_attribute($name, $value) {
954
        $this->attributes[$name] = $value;
955
    }
956
 
957
    /**
958
     * Magic setter method.
959
     *
960
     * This method manages access to some properties and will display deprecation message when accessing 'primary' property.
961
     *
962
     * @param string $name
963
     * @param mixed $value
964
     */
965
    public function __set($name, $value) {
966
        switch ($name) {
967
            case 'primary':
968
                debugging('The primary field is deprecated, use the type field instead');
969
                // Here just in case we modified the primary field from outside {@see \mod_quiz_renderer::summary_page_controls}.
970
                $this->type = $value ? self::BUTTON_PRIMARY : self::BUTTON_SECONDARY;
971
                break;
972
            case 'type':
973
                $this->type = in_array($value, self::BUTTON_TYPES) ? $value : self::BUTTON_SECONDARY;
974
                break;
975
            default:
976
                $this->$name = $value;
977
        }
978
    }
979
 
980
    /**
981
     * Magic method getter.
982
     *
983
     * This method manages access to some properties and will display deprecation message when accessing 'primary' property.
984
     *
985
     * @param string $name
986
     * @return mixed
987
     */
988
    public function __get($name) {
989
        switch ($name) {
990
            case 'primary':
991
                debugging('The primary field is deprecated, use type field instead');
992
                return $this->type == self::BUTTON_PRIMARY;
993
            case 'type':
994
                return $this->type;
995
            default:
996
                return $this->$name;
997
        }
998
    }
999
 
1000
    /**
1001
     * Export data.
1002
     *
1003
     * @param renderer_base $output Renderer.
1004
     * @return stdClass
1005
     */
1006
    public function export_for_template(renderer_base $output) {
1007
        $url = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
1008
 
1009
        $data = new stdClass();
1010
        $data->id = html_writer::random_id('single_button');
1011
        $data->formid = $this->formid;
1012
        $data->method = $this->method;
1013
        $data->url = $url === '' ? '#' : $url;
1014
        $data->label = $this->label;
1015
        $data->classes = $this->class;
1016
        $data->disabled = $this->disabled;
1017
        $data->tooltip = $this->tooltip;
1018
        $data->type = $this->type;
1019
        $data->attributes = [];
1020
        foreach ($this->attributes as $key => $value) {
1021
            $data->attributes[] = ['name' => $key, 'value' => $value];
1022
        }
1023
 
1024
        // Form parameters.
1025
        $actionurl = new moodle_url($this->url);
1026
        if ($this->method === 'post') {
1027
            $actionurl->param('sesskey', sesskey());
1028
        }
1029
        $data->params = $actionurl->export_params_for_template();
1030
 
1031
        // Button actions.
1032
        $actions = $this->actions;
1033
        $data->actions = array_map(function($action) use ($output) {
1034
            return $action->export_for_template($output);
1035
        }, $actions);
1036
        $data->hasactions = !empty($data->actions);
1037
 
1038
        return $data;
1039
    }
1040
}
1041
 
1042
 
1043
/**
1044
 * Simple form with just one select field that gets submitted automatically.
1045
 *
1046
 * If JS not enabled small go button is printed too.
1047
 *
1048
 * @copyright 2009 Petr Skoda
1049
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1050
 * @since Moodle 2.0
1051
 * @package core
1052
 * @category output
1053
 */
1054
class single_select implements renderable, templatable {
1055
 
1056
    /**
1057
     * @var moodle_url Target url - includes hidden fields
1058
     */
1059
    var $url;
1060
 
1061
    /**
1062
     * @var string Name of the select element.
1063
     */
1064
    var $name;
1065
 
1066
    /**
1067
     * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
1068
     *     it is also possible to specify optgroup as complex label array ex.:
1069
     *         array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1070
     *         array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1071
     */
1072
    var $options;
1073
 
1074
    /**
1075
     * @var string Selected option
1076
     */
1077
    var $selected;
1078
 
1079
    /**
1080
     * @var array Nothing selected
1081
     */
1082
    var $nothing;
1083
 
1084
    /**
1085
     * @var array Extra select field attributes
1086
     */
1087
    var $attributes = array();
1088
 
1089
    /**
1090
     * @var string Button label
1091
     */
1092
    var $label = '';
1093
 
1094
    /**
1095
     * @var array Button label's attributes
1096
     */
1097
    var $labelattributes = array();
1098
 
1099
    /**
1100
     * @var string Form submit method post or get
1101
     */
1102
    var $method = 'get';
1103
 
1104
    /**
1105
     * @var string Wrapping div class
1106
     */
1107
    var $class = 'singleselect';
1108
 
1109
    /**
1110
     * @var bool True if button disabled, false if normal
1111
     */
1112
    var $disabled = false;
1113
 
1114
    /**
1115
     * @var string Button tooltip
1116
     */
1117
    var $tooltip = null;
1118
 
1119
    /**
1120
     * @var string Form id
1121
     */
1122
    var $formid = null;
1123
 
1124
    /**
1125
     * @var help_icon The help icon for this element.
1126
     */
1127
    var $helpicon = null;
1128
 
1129
    /** @var component_action[] component action. */
1130
    public $actions = [];
1131
 
1132
    /**
1133
     * Constructor
1134
     * @param moodle_url $url form action target, includes hidden fields
1135
     * @param string $name name of selection field - the changing parameter in url
1136
     * @param array $options list of options
1137
     * @param string $selected selected element
1138
     * @param ?array $nothing
1139
     * @param string $formid
1140
     */
1141
    public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1142
        $this->url      = $url;
1143
        $this->name     = $name;
1144
        $this->options  = $options;
1145
        $this->selected = $selected;
1146
        $this->nothing  = $nothing;
1147
        $this->formid   = $formid;
1148
    }
1149
 
1150
    /**
1151
     * Shortcut for adding a JS confirm dialog when the button is clicked.
1152
     * The message must be a yes/no question.
1153
     *
1154
     * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
1155
     */
1156
    public function add_confirm_action($confirmmessage) {
1157
        $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
1158
    }
1159
 
1160
    /**
1161
     * Add action to the button.
1162
     *
1163
     * @param component_action $action
1164
     */
1165
    public function add_action(component_action $action) {
1166
        $this->actions[] = $action;
1167
    }
1168
 
1169
    /**
1170
     * Adds help icon.
1171
     *
1172
     * @deprecated since Moodle 2.0
1173
     */
1174
    public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1175
        throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1176
    }
1177
 
1178
    /**
1179
     * Adds help icon.
1180
     *
1181
     * @param string $identifier The keyword that defines a help page
1182
     * @param string $component
1183
     */
1184
    public function set_help_icon($identifier, $component = 'moodle') {
1185
        $this->helpicon = new help_icon($identifier, $component);
1186
    }
1187
 
1188
    /**
1189
     * Sets select's label
1190
     *
1191
     * @param string $label
1192
     * @param array $attributes (optional)
1193
     */
1194
    public function set_label($label, $attributes = array()) {
1195
        $this->label = $label;
1196
        $this->labelattributes = $attributes;
1197
 
1198
    }
1199
 
1200
    /**
1201
     * Export data.
1202
     *
1203
     * @param renderer_base $output Renderer.
1204
     * @return stdClass
1205
     */
1206
    public function export_for_template(renderer_base $output) {
1207
        $attributes = $this->attributes;
1208
 
1209
        $data = new stdClass();
1210
        $data->name = $this->name;
1211
        $data->method = $this->method;
1212
        $data->action = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
1213
        $data->classes = $this->class;
1214
        $data->label = $this->label;
1215
        $data->disabled = $this->disabled;
1216
        $data->title = $this->tooltip;
1217
        $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('single_select_f');
1218
        $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('single_select');
1219
 
1220
        // Select element attributes.
1221
        // Unset attributes that are already predefined in the template.
1222
        unset($attributes['id']);
1223
        unset($attributes['class']);
1224
        unset($attributes['name']);
1225
        unset($attributes['title']);
1226
        unset($attributes['disabled']);
1227
 
1228
        // Map the attributes.
1229
        $data->attributes = array_map(function($key) use ($attributes) {
1230
            return ['name' => $key, 'value' => $attributes[$key]];
1231
        }, array_keys($attributes));
1232
 
1233
        // Form parameters.
1234
        $actionurl = new moodle_url($this->url);
1235
        if ($this->method === 'post') {
1236
            $actionurl->param('sesskey', sesskey());
1237
        }
1238
        $data->params = $actionurl->export_params_for_template();
1239
 
1240
        // Select options.
1241
        $hasnothing = false;
1242
        if (is_string($this->nothing) && $this->nothing !== '') {
1243
            $nothing = ['' => $this->nothing];
1244
            $hasnothing = true;
1245
            $nothingkey = '';
1246
        } else if (is_array($this->nothing)) {
1247
            $nothingvalue = reset($this->nothing);
1248
            if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1249
                $nothing = [key($this->nothing) => get_string('choosedots')];
1250
            } else {
1251
                $nothing = $this->nothing;
1252
            }
1253
            $hasnothing = true;
1254
            $nothingkey = key($this->nothing);
1255
        }
1256
        if ($hasnothing) {
1257
            $options = $nothing + $this->options;
1258
        } else {
1259
            $options = $this->options;
1260
        }
1261
 
1262
        foreach ($options as $value => $name) {
1263
            if (is_array($options[$value])) {
1264
                foreach ($options[$value] as $optgroupname => $optgroupvalues) {
1265
                    $sublist = [];
1266
                    foreach ($optgroupvalues as $optvalue => $optname) {
1267
                        $option = [
1268
                            'value' => $optvalue,
1269
                            'name' => $optname,
1270
                            'selected' => strval($this->selected) === strval($optvalue),
1271
                        ];
1272
 
1273
                        if ($hasnothing && $nothingkey === $optvalue) {
1274
                            $option['ignore'] = 'data-ignore';
1275
                        }
1276
 
1277
                        $sublist[] = $option;
1278
                    }
1279
                    $data->options[] = [
1280
                        'name' => $optgroupname,
1281
                        'optgroup' => true,
1282
                        'options' => $sublist
1283
                    ];
1284
                }
1285
            } else {
1286
                $option = [
1287
                    'value' => $value,
1288
                    'name' => $options[$value],
1289
                    'selected' => strval($this->selected) === strval($value),
1290
                    'optgroup' => false
1291
                ];
1292
 
1293
                if ($hasnothing && $nothingkey === $value) {
1294
                    $option['ignore'] = 'data-ignore';
1295
                }
1296
 
1297
                $data->options[] = $option;
1298
            }
1299
        }
1300
 
1301
        // Label attributes.
1302
        $data->labelattributes = [];
1303
        // Unset label attributes that are already in the template.
1304
        unset($this->labelattributes['for']);
1305
        // Map the label attributes.
1306
        foreach ($this->labelattributes as $key => $value) {
1307
            $data->labelattributes[] = ['name' => $key, 'value' => $value];
1308
        }
1309
 
1310
        // Help icon.
1311
        $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1312
 
1313
        return $data;
1314
    }
1315
}
1316
 
1317
/**
1318
 * Simple URL selection widget description.
1319
 *
1320
 * @copyright 2009 Petr Skoda
1321
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1322
 * @since Moodle 2.0
1323
 * @package core
1324
 * @category output
1325
 */
1326
class url_select implements renderable, templatable {
1327
    /**
1328
     * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
1329
     *     it is also possible to specify optgroup as complex label array ex.:
1330
     *         array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1331
     *         array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1332
     */
1333
    var $urls;
1334
 
1335
    /**
1336
     * @var string Selected option
1337
     */
1338
    var $selected;
1339
 
1340
    /**
1341
     * @var array Nothing selected
1342
     */
1343
    var $nothing;
1344
 
1345
    /**
1346
     * @var array Extra select field attributes
1347
     */
1348
    var $attributes = array();
1349
 
1350
    /**
1351
     * @var string Button label
1352
     */
1353
    var $label = '';
1354
 
1355
    /**
1356
     * @var array Button label's attributes
1357
     */
1358
    var $labelattributes = array();
1359
 
1360
    /**
1361
     * @var string Wrapping div class
1362
     */
1363
    var $class = 'urlselect';
1364
 
1365
    /**
1366
     * @var bool True if button disabled, false if normal
1367
     */
1368
    var $disabled = false;
1369
 
1370
    /**
1371
     * @var string Button tooltip
1372
     */
1373
    var $tooltip = null;
1374
 
1375
    /**
1376
     * @var string Form id
1377
     */
1378
    var $formid = null;
1379
 
1380
    /**
1381
     * @var help_icon The help icon for this element.
1382
     */
1383
    var $helpicon = null;
1384
 
1385
    /**
1386
     * @var string If set, makes button visible with given name for button
1387
     */
1388
    var $showbutton = null;
1389
 
1390
    /**
1391
     * Constructor
1392
     * @param array $urls list of options
1393
     * @param string $selected selected element
1394
     * @param array $nothing
1395
     * @param string $formid
1396
     * @param string $showbutton Set to text of button if it should be visible
1397
     *   or null if it should be hidden (hidden version always has text 'go')
1398
     */
1399
    public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
1400
        $this->urls       = $urls;
1401
        $this->selected   = $selected;
1402
        $this->nothing    = $nothing;
1403
        $this->formid     = $formid;
1404
        $this->showbutton = $showbutton;
1405
    }
1406
 
1407
    /**
1408
     * Adds help icon.
1409
     *
1410
     * @deprecated since Moodle 2.0
1411
     */
1412
    public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1413
        throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1414
    }
1415
 
1416
    /**
1417
     * Adds help icon.
1418
     *
1419
     * @param string $identifier The keyword that defines a help page
1420
     * @param string $component
1421
     */
1422
    public function set_help_icon($identifier, $component = 'moodle') {
1423
        $this->helpicon = new help_icon($identifier, $component);
1424
    }
1425
 
1426
    /**
1427
     * Sets select's label
1428
     *
1429
     * @param string $label
1430
     * @param array $attributes (optional)
1431
     */
1432
    public function set_label($label, $attributes = array()) {
1433
        $this->label = $label;
1434
        $this->labelattributes = $attributes;
1435
    }
1436
 
1437
    /**
1438
     * Clean a URL.
1439
     *
1440
     * @param string $value The URL.
1441
     * @return string The cleaned URL.
1442
     */
1443
    protected function clean_url($value) {
1444
        global $CFG;
1445
 
1446
        if (empty($value)) {
1447
            // Nothing.
1448
 
1449
        } else if (strpos($value, $CFG->wwwroot . '/') === 0) {
1450
            $value = str_replace($CFG->wwwroot, '', $value);
1451
 
1452
        } else if (strpos($value, '/') !== 0) {
1453
            debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER);
1454
        }
1455
 
1456
        return $value;
1457
    }
1458
 
1459
    /**
1460
     * Flatten the options for Mustache.
1461
     *
1462
     * This also cleans the URLs.
1463
     *
1464
     * @param array $options The options.
1465
     * @param array $nothing The nothing option.
1466
     * @return array
1467
     */
1468
    protected function flatten_options($options, $nothing) {
1469
        $flattened = [];
1470
 
1471
        foreach ($options as $value => $option) {
1472
            if (is_array($option)) {
1473
                foreach ($option as $groupname => $optoptions) {
1474
                    if (!isset($flattened[$groupname])) {
1475
                        $flattened[$groupname] = [
1476
                            'name' => $groupname,
1477
                            'isgroup' => true,
1478
                            'options' => []
1479
                        ];
1480
                    }
1481
                    foreach ($optoptions as $optvalue => $optoption) {
1482
                        $cleanedvalue = $this->clean_url($optvalue);
1483
                        $flattened[$groupname]['options'][$cleanedvalue] = [
1484
                            'name' => $optoption,
1485
                            'value' => $cleanedvalue,
1486
                            'selected' => $this->selected == $optvalue,
1487
                        ];
1488
                    }
1489
                }
1490
 
1491
            } else {
1492
                $cleanedvalue = $this->clean_url($value);
1493
                $flattened[$cleanedvalue] = [
1494
                    'name' => $option,
1495
                    'value' => $cleanedvalue,
1496
                    'selected' => $this->selected == $value,
1497
                ];
1498
            }
1499
        }
1500
 
1501
        if (!empty($nothing)) {
1502
            $value = key($nothing);
1503
            $name = reset($nothing);
1504
            $flattened = [
1505
                    $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value]
1506
                ] + $flattened;
1507
        }
1508
 
1509
        // Make non-associative array.
1510
        foreach ($flattened as $key => $value) {
1511
            if (!empty($value['options'])) {
1512
                $flattened[$key]['options'] = array_values($value['options']);
1513
            }
1514
        }
1515
        $flattened = array_values($flattened);
1516
 
1517
        return $flattened;
1518
    }
1519
 
1520
    /**
1521
     * Export for template.
1522
     *
1523
     * @param renderer_base $output Renderer.
1524
     * @return stdClass
1525
     */
1526
    public function export_for_template(renderer_base $output) {
1527
        $attributes = $this->attributes;
1528
 
1529
        $data = new stdClass();
1530
        $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('url_select_f');
1531
        $data->classes = $this->class;
1532
        $data->label = $this->label;
1533
        $data->disabled = $this->disabled;
1534
        $data->title = $this->tooltip;
1535
        $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('url_select');
1536
        $data->sesskey = sesskey();
1537
        $data->action = (new moodle_url('/course/jumpto.php'))->out(false);
1538
 
1539
        // Remove attributes passed as property directly.
1540
        unset($attributes['class']);
1541
        unset($attributes['id']);
1542
        unset($attributes['name']);
1543
        unset($attributes['title']);
1544
        unset($attributes['disabled']);
1545
 
1546
        $data->showbutton = $this->showbutton;
1547
 
1548
        // Select options.
1549
        $nothing = false;
1550
        if (is_string($this->nothing) && $this->nothing !== '') {
1551
            $nothing = ['' => $this->nothing];
1552
        } else if (is_array($this->nothing)) {
1553
            $nothingvalue = reset($this->nothing);
1554
            if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1555
                $nothing = [key($this->nothing) => get_string('choosedots')];
1556
            } else {
1557
                $nothing = $this->nothing;
1558
            }
1559
        }
1560
        $data->options = $this->flatten_options($this->urls, $nothing);
1561
 
1562
        // Label attributes.
1563
        $data->labelattributes = [];
1564
        // Unset label attributes that are already in the template.
1565
        unset($this->labelattributes['for']);
1566
        // Map the label attributes.
1567
        foreach ($this->labelattributes as $key => $value) {
1568
            $data->labelattributes[] = ['name' => $key, 'value' => $value];
1569
        }
1570
 
1571
        // Help icon.
1572
        $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1573
 
1574
        // Finally all the remaining attributes.
1575
        $data->attributes = [];
1576
        foreach ($attributes as $key => $value) {
1577
            $data->attributes[] = ['name' => $key, 'value' => $value];
1578
        }
1579
 
1580
        return $data;
1581
    }
1582
}
1583
 
1584
/**
1585
 * Data structure describing html link with special action attached.
1586
 *
1587
 * @copyright 2010 Petr Skoda
1588
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1589
 * @since Moodle 2.0
1590
 * @package core
1591
 * @category output
1592
 */
1593
class action_link implements renderable {
1594
 
1595
    /**
1596
     * @var moodle_url Href url
1597
     */
1598
    public $url;
1599
 
1600
    /**
1601
     * @var string Link text HTML fragment
1602
     */
1603
    public $text;
1604
 
1605
    /**
1606
     * @var array HTML attributes
1607
     */
1608
    public $attributes;
1609
 
1610
    /**
1611
     * @var array List of actions attached to link
1612
     */
1613
    public $actions;
1614
 
1615
    /**
1616
     * @var pix_icon Optional pix icon to render with the link
1617
     */
1618
    public $icon;
1619
 
1620
    /**
1621
     * Constructor
1622
     * @param moodle_url $url
1623
     * @param string $text HTML fragment
1624
     * @param component_action $action
1625
     * @param array $attributes associative array of html link attributes + disabled
1626
     * @param pix_icon $icon optional pix_icon to render with the link text
1627
     */
1628
    public function __construct(moodle_url $url,
1629
        $text,
1630
        component_action $action=null,
1631
        array $attributes=null,
1632
        pix_icon $icon=null) {
1633
        $this->url = clone($url);
1634
        $this->text = $text;
1635
        if (empty($attributes['id'])) {
1636
            $attributes['id'] = html_writer::random_id('action_link');
1637
        }
1638
        $this->attributes = (array)$attributes;
1639
        if ($action) {
1640
            $this->add_action($action);
1641
        }
1642
        $this->icon = $icon;
1643
    }
1644
 
1645
    /**
1646
     * Add action to the link.
1647
     *
1648
     * @param component_action $action
1649
     */
1650
    public function add_action(component_action $action) {
1651
        $this->actions[] = $action;
1652
    }
1653
 
1654
    /**
1655
     * Adds a CSS class to this action link object
1656
     * @param string $class
1657
     */
1658
    public function add_class($class) {
1659
        if (empty($this->attributes['class'])) {
1660
            $this->attributes['class'] = $class;
1661
        } else {
1662
            $this->attributes['class'] .= ' ' . $class;
1663
        }
1664
    }
1665
 
1666
    /**
1667
     * Returns true if the specified class has been added to this link.
1668
     * @param string $class
1669
     * @return bool
1670
     */
1671
    public function has_class($class) {
1672
        return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
1673
    }
1674
 
1675
    /**
1676
     * Return the rendered HTML for the icon. Useful for rendering action links in a template.
1677
     * @return string
1678
     */
1679
    public function get_icon_html() {
1680
        global $OUTPUT;
1681
        if (!$this->icon) {
1682
            return '';
1683
        }
1684
        return $OUTPUT->render($this->icon);
1685
    }
1686
 
1687
    /**
1688
     * Export for template.
1689
     *
1690
     * @param renderer_base $output The renderer.
1691
     * @return stdClass
1692
     */
1693
    public function export_for_template(renderer_base $output) {
1694
        $data = new stdClass();
1695
        $attributes = $this->attributes;
1696
 
1697
        $data->id = $attributes['id'];
1698
        unset($attributes['id']);
1699
 
1700
        $data->disabled = !empty($attributes['disabled']);
1701
        unset($attributes['disabled']);
1702
 
1703
        $data->text = $this->text instanceof renderable ? $output->render($this->text) : (string) $this->text;
1704
        $data->url = $this->url ? $this->url->out(false) : '';
1705
        $data->icon = $this->icon ? $this->icon->export_for_pix() : null;
1706
        $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
1707
        unset($attributes['class']);
1708
 
1709
        $data->attributes = array_map(function($key, $value) {
1710
            return [
1711
                'name' => $key,
1712
                'value' => $value
1713
            ];
1714
        }, array_keys($attributes), $attributes);
1715
 
1716
        $data->actions = array_map(function($action) use ($output) {
1717
            return $action->export_for_template($output);
1718
        }, !empty($this->actions) ? $this->actions : []);
1719
        $data->hasactions = !empty($this->actions);
1720
 
1721
        return $data;
1722
    }
1723
}
1724
 
1725
/**
1726
 * Simple html output class
1727
 *
1728
 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1729
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1730
 * @since Moodle 2.0
1731
 * @package core
1732
 * @category output
1733
 */
1734
class html_writer {
1735
 
1736
    /**
1737
     * Outputs a tag with attributes and contents
1738
     *
1739
     * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1740
     * @param string $contents What goes between the opening and closing tags
1741
     * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1742
     * @return string HTML fragment
1743
     */
1744
    public static function tag($tagname, $contents, array $attributes = null) {
1745
        return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1746
    }
1747
 
1748
    /**
1749
     * Outputs an opening tag with attributes
1750
     *
1751
     * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1752
     * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1753
     * @return string HTML fragment
1754
     */
1755
    public static function start_tag($tagname, array $attributes = null) {
1756
        return '<' . $tagname . self::attributes($attributes) . '>';
1757
    }
1758
 
1759
    /**
1760
     * Outputs a closing tag
1761
     *
1762
     * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1763
     * @return string HTML fragment
1764
     */
1765
    public static function end_tag($tagname) {
1766
        return '</' . $tagname . '>';
1767
    }
1768
 
1769
    /**
1770
     * Outputs an empty tag with attributes
1771
     *
1772
     * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1773
     * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1774
     * @return string HTML fragment
1775
     */
1776
    public static function empty_tag($tagname, array $attributes = null) {
1777
        return '<' . $tagname . self::attributes($attributes) . ' />';
1778
    }
1779
 
1780
    /**
1781
     * Outputs a tag, but only if the contents are not empty
1782
     *
1783
     * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1784
     * @param string $contents What goes between the opening and closing tags
1785
     * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1786
     * @return string HTML fragment
1787
     */
1788
    public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1789
        if ($contents === '' || is_null($contents)) {
1790
            return '';
1791
        }
1792
        return self::tag($tagname, $contents, $attributes);
1793
    }
1794
 
1795
    /**
1796
     * Outputs a HTML attribute and value
1797
     *
1798
     * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1799
     * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1800
     * @return string HTML fragment
1801
     */
1802
    public static function attribute($name, $value) {
1803
        if ($value instanceof moodle_url) {
1804
            return ' ' . $name . '="' . $value->out() . '"';
1805
        }
1806
 
1807
        // special case, we do not want these in output
1808
        if ($value === null) {
1809
            return '';
1810
        }
1811
 
1812
        // no sloppy trimming here!
1813
        return ' ' . $name . '="' . s($value) . '"';
1814
    }
1815
 
1816
    /**
1817
     * Outputs a list of HTML attributes and values
1818
     *
1819
     * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1820
     *       The values will be escaped with {@link s()}
1821
     * @return string HTML fragment
1822
     */
1823
    public static function attributes(array $attributes = null) {
1824
        $attributes = (array)$attributes;
1825
        $output = '';
1826
        foreach ($attributes as $name => $value) {
1827
            $output .= self::attribute($name, $value);
1828
        }
1829
        return $output;
1830
    }
1831
 
1832
    /**
1833
     * Generates a simple image tag with attributes.
1834
     *
1835
     * @param string $src The source of image
1836
     * @param string $alt The alternate text for image
1837
     * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1838
     * @return string HTML fragment
1839
     */
1840
    public static function img($src, $alt, array $attributes = null) {
1841
        $attributes = (array)$attributes;
1842
        $attributes['src'] = $src;
1843
        // In case a null alt text is provided, set it to an empty string.
1844
        $attributes['alt'] = $alt ?? '';
1845
        if (array_key_exists('role', $attributes) && core_text::strtolower($attributes['role']) === 'presentation') {
1846
            // A presentation role is not necessary for the img tag.
1847
            // If a non-empty alt text is provided, the presentation role will conflict with the alt text.
1848
            // An empty alt text denotes a decorative image. The presence of a presentation role is redundant.
1849
            unset($attributes['role']);
1850
            debugging('The presentation role is not necessary for an img tag.', DEBUG_DEVELOPER);
1851
        }
1852
 
1853
        return self::empty_tag('img', $attributes);
1854
    }
1855
 
1856
    /**
1857
     * Generates random html element id.
1858
     *
1859
     * @staticvar int $counter
1860
     * @staticvar string $uniq
1861
     * @param string $base A string fragment that will be included in the random ID.
1862
     * @return string A unique ID
1863
     */
1864
    public static function random_id($base='random') {
1865
        static $counter = 0;
1866
        static $uniq;
1867
 
1868
        if (!isset($uniq)) {
1869
            $uniq = uniqid();
1870
        }
1871
 
1872
        $counter++;
1873
        return $base.$uniq.$counter;
1874
    }
1875
 
1876
    /**
1877
     * Generates a simple html link
1878
     *
1879
     * @param string|moodle_url $url The URL
1880
     * @param string $text The text
1881
     * @param array $attributes HTML attributes
1882
     * @return string HTML fragment
1883
     */
1884
    public static function link($url, $text, array $attributes = null) {
1885
        $attributes = (array)$attributes;
1886
        $attributes['href']  = $url;
1887
        return self::tag('a', $text, $attributes);
1888
    }
1889
 
1890
    /**
1891
     * Generates a simple checkbox with optional label
1892
     *
1893
     * @param string $name The name of the checkbox
1894
     * @param string $value The value of the checkbox
1895
     * @param bool $checked Whether the checkbox is checked
1896
     * @param string $label The label for the checkbox
1897
     * @param array $attributes Any attributes to apply to the checkbox
1898
     * @param array $labelattributes Any attributes to apply to the label, if present
1899
     * @return string html fragment
1900
     */
1901
    public static function checkbox($name, $value, $checked = true, $label = '',
1902
        array $attributes = null, array $labelattributes = null) {
1903
        $attributes = (array) $attributes;
1904
        $output = '';
1905
 
1906
        if ($label !== '' and !is_null($label)) {
1907
            if (empty($attributes['id'])) {
1908
                $attributes['id'] = self::random_id('checkbox_');
1909
            }
1910
        }
1911
        $attributes['type']    = 'checkbox';
1912
        $attributes['value']   = $value;
1913
        $attributes['name']    = $name;
1914
        $attributes['checked'] = $checked ? 'checked' : null;
1915
 
1916
        $output .= self::empty_tag('input', $attributes);
1917
 
1918
        if ($label !== '' and !is_null($label)) {
1919
            $labelattributes = (array) $labelattributes;
1920
            $labelattributes['for'] = $attributes['id'];
1921
            $output .= self::tag('label', $label, $labelattributes);
1922
        }
1923
 
1924
        return $output;
1925
    }
1926
 
1927
    /**
1928
     * Generates a simple select yes/no form field
1929
     *
1930
     * @param string $name name of select element
1931
     * @param bool $selected
1932
     * @param array $attributes - html select element attributes
1933
     * @return string HTML fragment
1934
     */
1935
    public static function select_yes_no($name, $selected=true, array $attributes = null) {
1936
        $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1937
        return self::select($options, $name, $selected, null, $attributes);
1938
    }
1939
 
1940
    /**
1941
     * Generates a simple select form field
1942
     *
1943
     * Note this function does HTML escaping on the optgroup labels, but not on the choice labels.
1944
     *
1945
     * @param array $options associative array value=>label ex.:
1946
     *                array(1=>'One, 2=>Two)
1947
     *              it is also possible to specify optgroup as complex label array ex.:
1948
     *                array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1949
     *                array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1950
     * @param string $name name of select element
1951
     * @param string|array $selected value or array of values depending on multiple attribute
1952
     * @param array|bool|null $nothing add nothing selected option, or false of not added
1953
     * @param array $attributes html select element attributes
1954
     * @return string HTML fragment
1955
     */
1956
    public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1957
        $attributes = (array)$attributes;
1958
        if (is_array($nothing)) {
1959
            foreach ($nothing as $k=>$v) {
1960
                if ($v === 'choose' or $v === 'choosedots') {
1961
                    $nothing[$k] = get_string('choosedots');
1962
                }
1963
            }
1964
            $options = $nothing + $options; // keep keys, do not override
1965
 
1966
        } else if (is_string($nothing) and $nothing !== '') {
1967
            // BC
1968
            $options = array(''=>$nothing) + $options;
1969
        }
1970
 
1971
        // we may accept more values if multiple attribute specified
1972
        $selected = (array)$selected;
1973
        foreach ($selected as $k=>$v) {
1974
            $selected[$k] = (string)$v;
1975
        }
1976
 
1977
        if (!isset($attributes['id'])) {
1978
            $id = 'menu'.$name;
1979
            // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1980
            $id = str_replace('[', '', $id);
1981
            $id = str_replace(']', '', $id);
1982
            $attributes['id'] = $id;
1983
        }
1984
 
1985
        if (!isset($attributes['class'])) {
1986
            $class = 'menu'.$name;
1987
            // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1988
            $class = str_replace('[', '', $class);
1989
            $class = str_replace(']', '', $class);
1990
            $attributes['class'] = $class;
1991
        }
1992
        $attributes['class'] = 'select custom-select ' . $attributes['class']; // Add 'select' selector always.
1993
 
1994
        $attributes['name'] = $name;
1995
 
1996
        if (!empty($attributes['disabled'])) {
1997
            $attributes['disabled'] = 'disabled';
1998
        } else {
1999
            unset($attributes['disabled']);
2000
        }
2001
 
2002
        $output = '';
2003
        foreach ($options as $value=>$label) {
2004
            if (is_array($label)) {
2005
                // ignore key, it just has to be unique
2006
                $output .= self::select_optgroup(key($label), current($label), $selected);
2007
            } else {
2008
                $output .= self::select_option($label, $value, $selected);
2009
            }
2010
        }
2011
        return self::tag('select', $output, $attributes);
2012
    }
2013
 
2014
    /**
2015
     * Returns HTML to display a select box option.
2016
     *
2017
     * @param string $label The label to display as the option.
2018
     * @param string|int $value The value the option represents
2019
     * @param array $selected An array of selected options
2020
     * @return string HTML fragment
2021
     */
2022
    private static function select_option($label, $value, array $selected) {
2023
        $attributes = array();
2024
        $value = (string)$value;
2025
        if (in_array($value, $selected, true)) {
2026
            $attributes['selected'] = 'selected';
2027
        }
2028
        $attributes['value'] = $value;
2029
        return self::tag('option', $label, $attributes);
2030
    }
2031
 
2032
    /**
2033
     * Returns HTML to display a select box option group.
2034
     *
2035
     * @param string $groupname The label to use for the group
2036
     * @param array $options The options in the group
2037
     * @param array $selected An array of selected values.
2038
     * @return string HTML fragment.
2039
     */
2040
    private static function select_optgroup($groupname, $options, array $selected) {
2041
        if (empty($options)) {
2042
            return '';
2043
        }
2044
        $attributes = array('label'=>$groupname);
2045
        $output = '';
2046
        foreach ($options as $value=>$label) {
2047
            $output .= self::select_option($label, $value, $selected);
2048
        }
2049
        return self::tag('optgroup', $output, $attributes);
2050
    }
2051
 
2052
    /**
2053
     * This is a shortcut for making an hour selector menu.
2054
     *
2055
     * @param string $type The type of selector (years, months, days, hours, minutes)
2056
     * @param string $name fieldname
2057
     * @param int $currenttime A default timestamp in GMT
2058
     * @param int $step minute spacing
2059
     * @param array $attributes - html select element attributes
2060
     * @param float|int|string $timezone the timezone to use to calculate the time
2061
     *        {@link https://moodledev.io/docs/apis/subsystems/time#timezone}
2062
     * @return string HTML fragment
2063
     */
2064
    public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null, $timezone = 99) {
2065
        global $OUTPUT;
2066
 
2067
        if (!$currenttime) {
2068
            $currenttime = time();
2069
        }
2070
        $calendartype = \core_calendar\type_factory::get_calendar_instance();
2071
        $currentdate = $calendartype->timestamp_to_date_array($currenttime, $timezone);
2072
 
2073
        $userdatetype = $type;
2074
        $timeunits = array();
2075
 
2076
        switch ($type) {
2077
            case 'years':
2078
                $timeunits = $calendartype->get_years();
2079
                $userdatetype = 'year';
2080
                break;
2081
            case 'months':
2082
                $timeunits = $calendartype->get_months();
2083
                $userdatetype = 'month';
2084
                $currentdate['month'] = (int)$currentdate['mon'];
2085
                break;
2086
            case 'days':
2087
                $timeunits = $calendartype->get_days();
2088
                $userdatetype = 'mday';
2089
                break;
2090
            case 'hours':
2091
                for ($i=0; $i<=23; $i++) {
2092
                    $timeunits[$i] = sprintf("%02d",$i);
2093
                }
2094
                break;
2095
            case 'minutes':
2096
                if ($step != 1) {
2097
                    $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
2098
                }
2099
 
2100
                for ($i=0; $i<=59; $i+=$step) {
2101
                    $timeunits[$i] = sprintf("%02d",$i);
2102
                }
2103
                break;
2104
            default:
2105
                throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
2106
        }
2107
 
2108
        $attributes = (array) $attributes;
2109
        $data = (object) [
2110
            'name' => $name,
2111
            'id' => !empty($attributes['id']) ? $attributes['id'] : self::random_id('ts_'),
2112
            'label' => get_string(substr($type, 0, -1), 'form'),
2113
            'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) {
2114
                return [
2115
                    'name' => $timeunits[$value],
2116
                    'value' => $value,
2117
                    'selected' => $currentdate[$userdatetype] == $value
2118
                ];
2119
            }, array_keys($timeunits)),
2120
        ];
2121
 
2122
        unset($attributes['id']);
2123
        unset($attributes['name']);
2124
        $data->attributes = array_map(function($name) use ($attributes) {
2125
            return [
2126
                'name' => $name,
2127
                'value' => $attributes[$name]
2128
            ];
2129
        }, array_keys($attributes));
2130
 
2131
        return $OUTPUT->render_from_template('core/select_time', $data);
2132
    }
2133
 
2134
    /**
2135
     * Shortcut for quick making of lists
2136
     *
2137
     * Note: 'list' is a reserved keyword ;-)
2138
     *
2139
     * @param array $items
2140
     * @param array $attributes
2141
     * @param string $tag ul or ol
2142
     * @return string
2143
     */
2144
    public static function alist(array $items, array $attributes = null, $tag = 'ul') {
2145
        $output = html_writer::start_tag($tag, $attributes)."\n";
2146
        foreach ($items as $item) {
2147
            $output .= html_writer::tag('li', $item)."\n";
2148
        }
2149
        $output .= html_writer::end_tag($tag);
2150
        return $output;
2151
    }
2152
 
2153
    /**
2154
     * Returns hidden input fields created from url parameters.
2155
     *
2156
     * @param moodle_url $url
2157
     * @param array $exclude list of excluded parameters
2158
     * @return string HTML fragment
2159
     */
2160
    public static function input_hidden_params(moodle_url $url, array $exclude = null) {
2161
        $exclude = (array)$exclude;
2162
        $params = $url->params();
2163
        foreach ($exclude as $key) {
2164
            unset($params[$key]);
2165
        }
2166
 
2167
        $output = '';
2168
        foreach ($params as $key => $value) {
2169
            $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
2170
            $output .= self::empty_tag('input', $attributes)."\n";
2171
        }
2172
        return $output;
2173
    }
2174
 
2175
    /**
2176
     * Generate a script tag containing the the specified code.
2177
     *
2178
     * @param string $jscode the JavaScript code
2179
     * @param moodle_url|string $url optional url of the external script, $code ignored if specified
2180
     * @return string HTML, the code wrapped in <script> tags.
2181
     */
2182
    public static function script($jscode, $url=null) {
2183
        if ($jscode) {
2184
            return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n") . "\n";
2185
 
2186
        } else if ($url) {
2187
            return self::tag('script', '', ['src' => $url]) . "\n";
2188
 
2189
        } else {
2190
            return '';
2191
        }
2192
    }
2193
 
2194
    /**
2195
     * Renders HTML table
2196
     *
2197
     * This method may modify the passed instance by adding some default properties if they are not set yet.
2198
     * If this is not what you want, you should make a full clone of your data before passing them to this
2199
     * method. In most cases this is not an issue at all so we do not clone by default for performance
2200
     * and memory consumption reasons.
2201
     *
2202
     * @param html_table $table data to be rendered
2203
     * @return string HTML code
2204
     */
2205
    public static function table(html_table $table) {
2206
        // prepare table data and populate missing properties with reasonable defaults
2207
        if (!empty($table->align)) {
2208
            foreach ($table->align as $key => $aa) {
2209
                if ($aa) {
2210
                    $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';';  // Fix for RTL languages
2211
                } else {
2212
                    $table->align[$key] = null;
2213
                }
2214
            }
2215
        }
2216
        if (!empty($table->size)) {
2217
            foreach ($table->size as $key => $ss) {
2218
                if ($ss) {
2219
                    $table->size[$key] = 'width:'. $ss .';';
2220
                } else {
2221
                    $table->size[$key] = null;
2222
                }
2223
            }
2224
        }
2225
        if (!empty($table->wrap)) {
2226
            foreach ($table->wrap as $key => $ww) {
2227
                if ($ww) {
2228
                    $table->wrap[$key] = 'white-space:nowrap;';
2229
                } else {
2230
                    $table->wrap[$key] = '';
2231
                }
2232
            }
2233
        }
2234
        if (!empty($table->head)) {
2235
            foreach ($table->head as $key => $val) {
2236
                if (!isset($table->align[$key])) {
2237
                    $table->align[$key] = null;
2238
                }
2239
                if (!isset($table->size[$key])) {
2240
                    $table->size[$key] = null;
2241
                }
2242
                if (!isset($table->wrap[$key])) {
2243
                    $table->wrap[$key] = null;
2244
                }
2245
 
2246
            }
2247
        }
2248
        if (empty($table->attributes['class'])) {
2249
            $table->attributes['class'] = 'generaltable';
2250
        }
2251
        if (!empty($table->tablealign)) {
2252
            $table->attributes['class'] .= ' boxalign' . $table->tablealign;
2253
        }
2254
 
2255
        // explicitly assigned properties override those defined via $table->attributes
2256
        $table->attributes['class'] = trim($table->attributes['class']);
2257
        $attributes = array_merge($table->attributes, array(
2258
            'id'            => $table->id,
2259
            'width'         => $table->width,
2260
            'summary'       => $table->summary,
2261
            'cellpadding'   => $table->cellpadding,
2262
            'cellspacing'   => $table->cellspacing,
2263
        ));
2264
        $output = html_writer::start_tag('table', $attributes) . "\n";
2265
 
2266
        $countcols = 0;
2267
 
2268
        // Output a caption if present.
2269
        if (!empty($table->caption)) {
2270
            $captionattributes = array();
2271
            if ($table->captionhide) {
2272
                $captionattributes['class'] = 'accesshide';
2273
            }
2274
            $output .= html_writer::tag(
2275
                'caption',
2276
                $table->caption,
2277
                $captionattributes
2278
            );
2279
        }
2280
 
2281
        if (!empty($table->head)) {
2282
            $countcols = count($table->head);
2283
 
2284
            $output .= html_writer::start_tag('thead', array()) . "\n";
2285
            $output .= html_writer::start_tag('tr', array()) . "\n";
2286
            $keys = array_keys($table->head);
2287
            $lastkey = end($keys);
2288
 
2289
            foreach ($table->head as $key => $heading) {
2290
                // Convert plain string headings into html_table_cell objects
2291
                if (!($heading instanceof html_table_cell)) {
2292
                    $headingtext = $heading;
2293
                    $heading = new html_table_cell();
2294
                    $heading->text = $headingtext;
2295
                    $heading->header = true;
2296
                }
2297
 
2298
                if ($heading->header !== false) {
2299
                    $heading->header = true;
2300
                }
2301
 
2302
                $tagtype = 'td';
2303
                if ($heading->header && (string)$heading->text != '') {
2304
                    $tagtype = 'th';
2305
                }
2306
 
2307
                $heading->attributes['class'] .= ' header c' . $key;
2308
                if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
2309
                    $heading->colspan = $table->headspan[$key];
2310
                    $countcols += $table->headspan[$key] - 1;
2311
                }
2312
 
2313
                if ($key == $lastkey) {
2314
                    $heading->attributes['class'] .= ' lastcol';
2315
                }
2316
                if (isset($table->colclasses[$key])) {
2317
                    $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
2318
                }
2319
                $heading->attributes['class'] = trim($heading->attributes['class']);
2320
                $attributes = array_merge($heading->attributes, [
2321
                    'style'     => $table->align[$key] . $table->size[$key] . $heading->style,
2322
                    'colspan'   => $heading->colspan,
2323
                ]);
2324
 
2325
                if ($tagtype == 'th') {
2326
                    $attributes['scope'] = !empty($heading->scope) ? $heading->scope : 'col';
2327
                }
2328
 
2329
                $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
2330
            }
2331
            $output .= html_writer::end_tag('tr') . "\n";
2332
            $output .= html_writer::end_tag('thead') . "\n";
2333
 
2334
            if (empty($table->data)) {
2335
                // For valid XHTML strict every table must contain either a valid tr
2336
                // or a valid tbody... both of which must contain a valid td
2337
                $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
2338
                $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
2339
                $output .= html_writer::end_tag('tbody');
2340
            }
2341
        }
2342
 
2343
        if (!empty($table->data)) {
2344
            $keys       = array_keys($table->data);
2345
            $lastrowkey = end($keys);
2346
            $output .= html_writer::start_tag('tbody', array());
2347
 
2348
            foreach ($table->data as $key => $row) {
2349
                if (($row === 'hr') && ($countcols)) {
2350
                    $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
2351
                } else {
2352
                    // Convert array rows to html_table_rows and cell strings to html_table_cell objects
2353
                    if (!($row instanceof html_table_row)) {
2354
                        $newrow = new html_table_row();
2355
 
2356
                        foreach ($row as $cell) {
2357
                            if (!($cell instanceof html_table_cell)) {
2358
                                $cell = new html_table_cell($cell);
2359
                            }
2360
                            $newrow->cells[] = $cell;
2361
                        }
2362
                        $row = $newrow;
2363
                    }
2364
 
2365
                    if (isset($table->rowclasses[$key])) {
2366
                        $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
2367
                    }
2368
 
2369
                    if ($key == $lastrowkey) {
2370
                        $row->attributes['class'] .= ' lastrow';
2371
                    }
2372
 
2373
                    // Explicitly assigned properties should override those defined in the attributes.
2374
                    $row->attributes['class'] = trim($row->attributes['class']);
2375
                    $trattributes = array_merge($row->attributes, array(
2376
                        'id'            => $row->id,
2377
                        'style'         => $row->style,
2378
                    ));
2379
                    $output .= html_writer::start_tag('tr', $trattributes) . "\n";
2380
                    $keys2 = array_keys($row->cells);
2381
                    $lastkey = end($keys2);
2382
 
2383
                    $gotlastkey = false; //flag for sanity checking
2384
                    foreach ($row->cells as $key => $cell) {
2385
                        if ($gotlastkey) {
2386
                            //This should never happen. Why do we have a cell after the last cell?
2387
                            mtrace("A cell with key ($key) was found after the last key ($lastkey)");
2388
                        }
2389
 
2390
                        if (!($cell instanceof html_table_cell)) {
2391
                            $mycell = new html_table_cell();
2392
                            $mycell->text = $cell;
2393
                            $cell = $mycell;
2394
                        }
2395
 
2396
                        if (($cell->header === true) && empty($cell->scope)) {
2397
                            $cell->scope = 'row';
2398
                        }
2399
 
2400
                        if (isset($table->colclasses[$key])) {
2401
                            $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
2402
                        }
2403
 
2404
                        $cell->attributes['class'] .= ' cell c' . $key;
2405
                        if ($key == $lastkey) {
2406
                            $cell->attributes['class'] .= ' lastcol';
2407
                            $gotlastkey = true;
2408
                        }
2409
                        $tdstyle = '';
2410
                        $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
2411
                        $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
2412
                        $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
2413
                        $cell->attributes['class'] = trim($cell->attributes['class']);
2414
                        $tdattributes = array_merge($cell->attributes, array(
2415
                            'style' => $tdstyle . $cell->style,
2416
                            'colspan' => $cell->colspan,
2417
                            'rowspan' => $cell->rowspan,
2418
                            'id' => $cell->id,
2419
                            'abbr' => $cell->abbr,
2420
                            'scope' => $cell->scope,
2421
                        ));
2422
                        $tagtype = 'td';
2423
                        if ($cell->header === true) {
2424
                            $tagtype = 'th';
2425
                        }
2426
                        $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
2427
                    }
2428
                }
2429
                $output .= html_writer::end_tag('tr') . "\n";
2430
            }
2431
            $output .= html_writer::end_tag('tbody') . "\n";
2432
        }
2433
        $output .= html_writer::end_tag('table') . "\n";
2434
 
2435
        if ($table->responsive) {
2436
            return self::div($output, 'table-responsive');
2437
        }
2438
 
2439
        return $output;
2440
    }
2441
 
2442
    /**
2443
     * Renders form element label
2444
     *
2445
     * By default, the label is suffixed with a label separator defined in the
2446
     * current language pack (colon by default in the English lang pack).
2447
     * Adding the colon can be explicitly disabled if needed. Label separators
2448
     * are put outside the label tag itself so they are not read by
2449
     * screenreaders (accessibility).
2450
     *
2451
     * Parameter $for explicitly associates the label with a form control. When
2452
     * set, the value of this attribute must be the same as the value of
2453
     * the id attribute of the form control in the same document. When null,
2454
     * the label being defined is associated with the control inside the label
2455
     * element.
2456
     *
2457
     * @param string $text content of the label tag
2458
     * @param string|null $for id of the element this label is associated with, null for no association
2459
     * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
2460
     * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
2461
     * @return string HTML of the label element
2462
     */
2463
    public static function label($text, $for, $colonize = true, array $attributes=array()) {
2464
        if (!is_null($for)) {
2465
            $attributes = array_merge($attributes, array('for' => $for));
2466
        }
2467
        $text = trim($text ?? '');
2468
        $label = self::tag('label', $text, $attributes);
2469
 
2470
        // TODO MDL-12192 $colonize disabled for now yet
2471
        // if (!empty($text) and $colonize) {
2472
        //     // the $text may end with the colon already, though it is bad string definition style
2473
        //     $colon = get_string('labelsep', 'langconfig');
2474
        //     if (!empty($colon)) {
2475
        //         $trimmed = trim($colon);
2476
        //         if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
2477
        //             //debugging('The label text should not end with colon or other label separator,
2478
        //             //           please fix the string definition.', DEBUG_DEVELOPER);
2479
        //         } else {
2480
        //             $label .= $colon;
2481
        //         }
2482
        //     }
2483
        // }
2484
 
2485
        return $label;
2486
    }
2487
 
2488
    /**
2489
     * Combines a class parameter with other attributes. Aids in code reduction
2490
     * because the class parameter is very frequently used.
2491
     *
2492
     * If the class attribute is specified both in the attributes and in the
2493
     * class parameter, the two values are combined with a space between.
2494
     *
2495
     * @param string $class Optional CSS class (or classes as space-separated list)
2496
     * @param array $attributes Optional other attributes as array
2497
     * @return array Attributes (or null if still none)
2498
     */
2499
    private static function add_class($class = '', array $attributes = null) {
2500
        if ($class !== '') {
2501
            $classattribute = array('class' => $class);
2502
            if ($attributes) {
2503
                if (array_key_exists('class', $attributes)) {
2504
                    $attributes['class'] = trim($attributes['class'] . ' ' . $class);
2505
                } else {
2506
                    $attributes = $classattribute + $attributes;
2507
                }
2508
            } else {
2509
                $attributes = $classattribute;
2510
            }
2511
        }
2512
        return $attributes;
2513
    }
2514
 
2515
    /**
2516
     * Creates a <div> tag. (Shortcut function.)
2517
     *
2518
     * @param string $content HTML content of tag
2519
     * @param string $class Optional CSS class (or classes as space-separated list)
2520
     * @param array $attributes Optional other attributes as array
2521
     * @return string HTML code for div
2522
     */
2523
    public static function div($content, $class = '', array $attributes = null) {
2524
        return self::tag('div', $content, self::add_class($class, $attributes));
2525
    }
2526
 
2527
    /**
2528
     * Starts a <div> tag. (Shortcut function.)
2529
     *
2530
     * @param string $class Optional CSS class (or classes as space-separated list)
2531
     * @param array $attributes Optional other attributes as array
2532
     * @return string HTML code for open div tag
2533
     */
2534
    public static function start_div($class = '', array $attributes = null) {
2535
        return self::start_tag('div', self::add_class($class, $attributes));
2536
    }
2537
 
2538
    /**
2539
     * Ends a <div> tag. (Shortcut function.)
2540
     *
2541
     * @return string HTML code for close div tag
2542
     */
2543
    public static function end_div() {
2544
        return self::end_tag('div');
2545
    }
2546
 
2547
    /**
2548
     * Creates a <span> tag. (Shortcut function.)
2549
     *
2550
     * @param string $content HTML content of tag
2551
     * @param string $class Optional CSS class (or classes as space-separated list)
2552
     * @param array $attributes Optional other attributes as array
2553
     * @return string HTML code for span
2554
     */
2555
    public static function span($content, $class = '', array $attributes = null) {
2556
        return self::tag('span', $content, self::add_class($class, $attributes));
2557
    }
2558
 
2559
    /**
2560
     * Starts a <span> tag. (Shortcut function.)
2561
     *
2562
     * @param string $class Optional CSS class (or classes as space-separated list)
2563
     * @param array $attributes Optional other attributes as array
2564
     * @return string HTML code for open span tag
2565
     */
2566
    public static function start_span($class = '', array $attributes = null) {
2567
        return self::start_tag('span', self::add_class($class, $attributes));
2568
    }
2569
 
2570
    /**
2571
     * Ends a <span> tag. (Shortcut function.)
2572
     *
2573
     * @return string HTML code for close span tag
2574
     */
2575
    public static function end_span() {
2576
        return self::end_tag('span');
2577
    }
2578
}
2579
 
2580
/**
2581
 * Simple javascript output class
2582
 *
2583
 * @copyright 2010 Petr Skoda
2584
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2585
 * @since Moodle 2.0
2586
 * @package core
2587
 * @category output
2588
 */
2589
class js_writer {
2590
 
2591
    /**
2592
     * Returns javascript code calling the function
2593
     *
2594
     * @param string $function function name, can be complex like Y.Event.purgeElement
2595
     * @param array $arguments parameters
2596
     * @param int $delay execution delay in seconds
2597
     * @return string JS code fragment
2598
     */
2599
    public static function function_call($function, array $arguments = null, $delay=0) {
2600
        if ($arguments) {
2601
            $arguments = array_map('json_encode', convert_to_array($arguments));
2602
            $arguments = implode(', ', $arguments);
2603
        } else {
2604
            $arguments = '';
2605
        }
2606
        $js = "$function($arguments);";
2607
 
2608
        if ($delay) {
2609
            $delay = $delay * 1000; // in miliseconds
2610
            $js = "setTimeout(function() { $js }, $delay);";
2611
        }
2612
        return $js . "\n";
2613
    }
2614
 
2615
    /**
2616
     * Special function which adds Y as first argument of function call.
2617
     *
2618
     * @param string $function The function to call
2619
     * @param array $extraarguments Any arguments to pass to it
2620
     * @return string Some JS code
2621
     */
2622
    public static function function_call_with_Y($function, array $extraarguments = null) {
2623
        if ($extraarguments) {
2624
            $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
2625
            $arguments = 'Y, ' . implode(', ', $extraarguments);
2626
        } else {
2627
            $arguments = 'Y';
2628
        }
2629
        return "$function($arguments);\n";
2630
    }
2631
 
2632
    /**
2633
     * Returns JavaScript code to initialise a new object
2634
     *
2635
     * @param string $var If it is null then no var is assigned the new object.
2636
     * @param string $class The class to initialise an object for.
2637
     * @param array $arguments An array of args to pass to the init method.
2638
     * @param array $requirements Any modules required for this class.
2639
     * @param int $delay The delay before initialisation. 0 = no delay.
2640
     * @return string Some JS code
2641
     */
2642
    public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
2643
        if (is_array($arguments)) {
2644
            $arguments = array_map('json_encode', convert_to_array($arguments));
2645
            $arguments = implode(', ', $arguments);
2646
        }
2647
 
2648
        if ($var === null) {
2649
            $js = "new $class(Y, $arguments);";
2650
        } else if (strpos($var, '.')!==false) {
2651
            $js = "$var = new $class(Y, $arguments);";
2652
        } else {
2653
            $js = "var $var = new $class(Y, $arguments);";
2654
        }
2655
 
2656
        if ($delay) {
2657
            $delay = $delay * 1000; // in miliseconds
2658
            $js = "setTimeout(function() { $js }, $delay);";
2659
        }
2660
 
2661
        if (count($requirements) > 0) {
2662
            $requirements = implode("', '", $requirements);
2663
            $js = "Y.use('$requirements', function(Y){ $js });";
2664
        }
2665
        return $js."\n";
2666
    }
2667
 
2668
    /**
2669
     * Returns code setting value to variable
2670
     *
2671
     * @param string $name
2672
     * @param mixed $value json serialised value
2673
     * @param bool $usevar add var definition, ignored for nested properties
2674
     * @return string JS code fragment
2675
     */
2676
    public static function set_variable($name, $value, $usevar = true) {
2677
        $output = '';
2678
 
2679
        if ($usevar) {
2680
            if (strpos($name, '.')) {
2681
                $output .= '';
2682
            } else {
2683
                $output .= 'var ';
2684
            }
2685
        }
2686
 
2687
        $output .= "$name = ".json_encode($value).";";
2688
 
2689
        return $output;
2690
    }
2691
 
2692
    /**
2693
     * Writes event handler attaching code
2694
     *
2695
     * @param array|string $selector standard YUI selector for elements, may be
2696
     *     array or string, element id is in the form "#idvalue"
2697
     * @param string $event A valid DOM event (click, mousedown, change etc.)
2698
     * @param string $function The name of the function to call
2699
     * @param array $arguments An optional array of argument parameters to pass to the function
2700
     * @return string JS code fragment
2701
     */
2702
    public static function event_handler($selector, $event, $function, array $arguments = null) {
2703
        $selector = json_encode($selector);
2704
        $output = "Y.on('$event', $function, $selector, null";
2705
        if (!empty($arguments)) {
2706
            $output .= ', ' . json_encode($arguments);
2707
        }
2708
        return $output . ");\n";
2709
    }
2710
}
2711
 
2712
/**
2713
 * Holds all the information required to render a <table> by {@link core_renderer::table()}
2714
 *
2715
 * Example of usage:
2716
 * $t = new html_table();
2717
 * ... // set various properties of the object $t as described below
2718
 * echo html_writer::table($t);
2719
 *
2720
 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
2721
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2722
 * @since Moodle 2.0
2723
 * @package core
2724
 * @category output
2725
 */
2726
class html_table {
2727
 
2728
    /**
2729
     * @var string Value to use for the id attribute of the table
2730
     */
2731
    public $id = null;
2732
 
2733
    /**
2734
     * @var array Attributes of HTML attributes for the <table> element
2735
     */
2736
    public $attributes = array();
2737
 
2738
    /**
2739
     * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
2740
     * For more control over the rendering of the headers, an array of html_table_cell objects
2741
     * can be passed instead of an array of strings.
2742
     *
2743
     * Example of usage:
2744
     * $t->head = array('Student', 'Grade');
2745
     */
2746
    public $head;
2747
 
2748
    /**
2749
     * @var array An array that can be used to make a heading span multiple columns.
2750
     * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
2751
     * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
2752
     *
2753
     * Example of usage:
2754
     * $t->headspan = array(2,1);
2755
     */
2756
    public $headspan;
2757
 
2758
    /**
2759
     * @var array An array of column alignments.
2760
     * The value is used as CSS 'text-align' property. Therefore, possible
2761
     * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
2762
     * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
2763
     *
2764
     * Examples of usage:
2765
     * $t->align = array(null, 'right');
2766
     * or
2767
     * $t->align[1] = 'right';
2768
     */
2769
    public $align;
2770
 
2771
    /**
2772
     * @var array The value is used as CSS 'size' property.
2773
     *
2774
     * Examples of usage:
2775
     * $t->size = array('50%', '50%');
2776
     * or
2777
     * $t->size[1] = '120px';
2778
     */
2779
    public $size;
2780
 
2781
    /**
2782
     * @var array An array of wrapping information.
2783
     * The only possible value is 'nowrap' that sets the
2784
     * CSS property 'white-space' to the value 'nowrap' in the given column.
2785
     *
2786
     * Example of usage:
2787
     * $t->wrap = array(null, 'nowrap');
2788
     */
2789
    public $wrap;
2790
 
2791
    /**
2792
     * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2793
     * $head specified, the string 'hr' (for horizontal ruler) can be used
2794
     * instead of an array of cells data resulting in a divider rendered.
2795
     *
2796
     * Example of usage with array of arrays:
2797
     * $row1 = array('Harry Potter', '76 %');
2798
     * $row2 = array('Hermione Granger', '100 %');
2799
     * $t->data = array($row1, $row2);
2800
     *
2801
     * Example with array of html_table_row objects: (used for more fine-grained control)
2802
     * $cell1 = new html_table_cell();
2803
     * $cell1->text = 'Harry Potter';
2804
     * $cell1->colspan = 2;
2805
     * $row1 = new html_table_row();
2806
     * $row1->cells[] = $cell1;
2807
     * $cell2 = new html_table_cell();
2808
     * $cell2->text = 'Hermione Granger';
2809
     * $cell3 = new html_table_cell();
2810
     * $cell3->text = '100 %';
2811
     * $row2 = new html_table_row();
2812
     * $row2->cells = array($cell2, $cell3);
2813
     * $t->data = array($row1, $row2);
2814
     */
2815
    public $data = [];
2816
 
2817
    /**
2818
     * @deprecated since Moodle 2.0. Styling should be in the CSS.
2819
     * @var string Width of the table, percentage of the page preferred.
2820
     */
2821
    public $width = null;
2822
 
2823
    /**
2824
     * @deprecated since Moodle 2.0. Styling should be in the CSS.
2825
     * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2826
     */
2827
    public $tablealign = null;
2828
 
2829
    /**
2830
     * @deprecated since Moodle 2.0. Styling should be in the CSS.
2831
     * @var int Padding on each cell, in pixels
2832
     */
2833
    public $cellpadding = null;
2834
 
2835
    /**
2836
     * @var int Spacing between cells, in pixels
2837
     * @deprecated since Moodle 2.0. Styling should be in the CSS.
2838
     */
2839
    public $cellspacing = null;
2840
 
2841
    /**
2842
     * @var array Array of classes to add to particular rows, space-separated string.
2843
     * Class 'lastrow' is added automatically for the last row in the table.
2844
     *
2845
     * Example of usage:
2846
     * $t->rowclasses[9] = 'tenth'
2847
     */
2848
    public $rowclasses;
2849
 
2850
    /**
2851
     * @var array An array of classes to add to every cell in a particular column,
2852
     * space-separated string. Class 'cell' is added automatically by the renderer.
2853
     * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2854
     * respectively. Class 'lastcol' is added automatically for all last cells
2855
     * in a row.
2856
     *
2857
     * Example of usage:
2858
     * $t->colclasses = array(null, 'grade');
2859
     */
2860
    public $colclasses;
2861
 
2862
    /**
2863
     * @var string Description of the contents for screen readers.
2864
     *
2865
     * The "summary" attribute on the "table" element is not supported in HTML5.
2866
     * Consider describing the structure of the table in a "caption" element or in a "figure" element containing the table;
2867
     * or, simplify the structure of the table so that no description is needed.
2868
     *
2869
     * @deprecated since Moodle 3.9.
2870
     */
2871
    public $summary;
2872
 
2873
    /**
2874
     * @var string Caption for the table, typically a title.
2875
     *
2876
     * Example of usage:
2877
     * $t->caption = "TV Guide";
2878
     */
2879
    public $caption;
2880
 
2881
    /**
2882
     * @var bool Whether to hide the table's caption from sighted users.
2883
     *
2884
     * Example of usage:
2885
     * $t->caption = "TV Guide";
2886
     * $t->captionhide = true;
2887
     */
2888
    public $captionhide = false;
2889
 
2890
    /** @var bool Whether to make the table to be scrolled horizontally with ease. Make table responsive across all viewports. */
2891
    public $responsive = true;
2892
 
2893
    /** @var string class name to add to this html table. */
2894
    public $class;
2895
 
2896
    /**
2897
     * Constructor
2898
     */
2899
    public function __construct() {
2900
        $this->attributes['class'] = '';
2901
    }
2902
}
2903
 
2904
/**
2905
 * Component representing a table row.
2906
 *
2907
 * @copyright 2009 Nicolas Connault
2908
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2909
 * @since Moodle 2.0
2910
 * @package core
2911
 * @category output
2912
 */
2913
class html_table_row {
2914
 
2915
    /**
2916
     * @var string Value to use for the id attribute of the row.
2917
     */
2918
    public $id = null;
2919
 
2920
    /**
2921
     * @var array Array of html_table_cell objects
2922
     */
2923
    public $cells = array();
2924
 
2925
    /**
2926
     * @var string Value to use for the style attribute of the table row
2927
     */
2928
    public $style = null;
2929
 
2930
    /**
2931
     * @var array Attributes of additional HTML attributes for the <tr> element
2932
     */
2933
    public $attributes = array();
2934
 
2935
    /**
2936
     * Constructor
2937
     * @param array $cells
2938
     */
2939
    public function __construct(array $cells=null) {
2940
        $this->attributes['class'] = '';
2941
        $cells = (array)$cells;
2942
        foreach ($cells as $cell) {
2943
            if ($cell instanceof html_table_cell) {
2944
                $this->cells[] = $cell;
2945
            } else {
2946
                $this->cells[] = new html_table_cell($cell);
2947
            }
2948
        }
2949
    }
2950
}
2951
 
2952
/**
2953
 * Component representing a table cell.
2954
 *
2955
 * @copyright 2009 Nicolas Connault
2956
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2957
 * @since Moodle 2.0
2958
 * @package core
2959
 * @category output
2960
 */
2961
class html_table_cell {
2962
 
2963
    /**
2964
     * @var string Value to use for the id attribute of the cell.
2965
     */
2966
    public $id = null;
2967
 
2968
    /**
2969
     * @var string The contents of the cell.
2970
     */
2971
    public $text;
2972
 
2973
    /**
2974
     * @var string Abbreviated version of the contents of the cell.
2975
     */
2976
    public $abbr = null;
2977
 
2978
    /**
2979
     * @var int Number of columns this cell should span.
2980
     */
2981
    public $colspan = null;
2982
 
2983
    /**
2984
     * @var int Number of rows this cell should span.
2985
     */
2986
    public $rowspan = null;
2987
 
2988
    /**
2989
     * @var string Defines a way to associate header cells and data cells in a table.
2990
     */
2991
    public $scope = null;
2992
 
2993
    /**
2994
     * @var bool Whether or not this cell is a header cell.
2995
     */
2996
    public $header = null;
2997
 
2998
    /**
2999
     * @var string Value to use for the style attribute of the table cell
3000
     */
3001
    public $style = null;
3002
 
3003
    /**
3004
     * @var array Attributes of additional HTML attributes for the <td> element
3005
     */
3006
    public $attributes = array();
3007
 
3008
    /**
3009
     * Constructs a table cell
3010
     *
3011
     * @param string $text
3012
     */
3013
    public function __construct($text = null) {
3014
        $this->text = $text;
3015
        $this->attributes['class'] = '';
3016
    }
3017
}
3018
 
3019
/**
3020
 * Component representing a paging bar.
3021
 *
3022
 * @copyright 2009 Nicolas Connault
3023
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3024
 * @since Moodle 2.0
3025
 * @package core
3026
 * @category output
3027
 */
3028
class paging_bar implements renderable, templatable {
3029
 
3030
    /**
3031
     * @var int The maximum number of pagelinks to display.
3032
     */
3033
    public $maxdisplay = 18;
3034
 
3035
    /**
3036
     * @var int The total number of entries to be pages through..
3037
     */
3038
    public $totalcount;
3039
 
3040
    /**
3041
     * @var int The page you are currently viewing.
3042
     */
3043
    public $page;
3044
 
3045
    /**
3046
     * @var int The number of entries that should be shown per page.
3047
     */
3048
    public $perpage;
3049
 
3050
    /**
3051
     * @var string|moodle_url If this  is a string then it is the url which will be appended with $pagevar,
3052
     * an equals sign and the page number.
3053
     * If this is a moodle_url object then the pagevar param will be replaced by
3054
     * the page no, for each page.
3055
     */
3056
    public $baseurl;
3057
 
3058
    /**
3059
     * @var string This is the variable name that you use for the pagenumber in your
3060
     * code (ie. 'tablepage', 'blogpage', etc)
3061
     */
3062
    public $pagevar;
3063
 
3064
    /**
3065
     * @var string A HTML link representing the "previous" page.
3066
     */
3067
    public $previouslink = null;
3068
 
3069
    /**
3070
     * @var string A HTML link representing the "next" page.
3071
     */
3072
    public $nextlink = null;
3073
 
3074
    /**
3075
     * @var string A HTML link representing the first page.
3076
     */
3077
    public $firstlink = null;
3078
 
3079
    /**
3080
     * @var string A HTML link representing the last page.
3081
     */
3082
    public $lastlink = null;
3083
 
3084
    /**
3085
     * @var array An array of strings. One of them is just a string: the current page
3086
     */
3087
    public $pagelinks = array();
3088
 
3089
    /**
3090
     * Constructor paging_bar with only the required params.
3091
     *
3092
     * @param int $totalcount The total number of entries available to be paged through
3093
     * @param int $page The page you are currently viewing
3094
     * @param int $perpage The number of entries that should be shown per page
3095
     * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3096
     * @param string $pagevar name of page parameter that holds the page number
3097
     */
3098
    public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3099
        $this->totalcount = $totalcount;
3100
        $this->page       = $page;
3101
        $this->perpage    = $perpage;
3102
        $this->baseurl    = $baseurl;
3103
        $this->pagevar    = $pagevar;
3104
    }
3105
 
3106
    /**
3107
     * Prepares the paging bar for output.
3108
     *
3109
     * This method validates the arguments set up for the paging bar and then
3110
     * produces fragments of HTML to assist display later on.
3111
     *
3112
     * @param renderer_base $output
3113
     * @param moodle_page $page
3114
     * @param string $target
3115
     * @throws coding_exception
3116
     */
3117
    public function prepare(renderer_base $output, moodle_page $page, $target) {
3118
        if (!isset($this->totalcount) || is_null($this->totalcount)) {
3119
            throw new coding_exception('paging_bar requires a totalcount value.');
3120
        }
3121
        if (!isset($this->page) || is_null($this->page)) {
3122
            throw new coding_exception('paging_bar requires a page value.');
3123
        }
3124
        if (empty($this->perpage)) {
3125
            throw new coding_exception('paging_bar requires a perpage value.');
3126
        }
3127
        if (empty($this->baseurl)) {
3128
            throw new coding_exception('paging_bar requires a baseurl value.');
3129
        }
3130
 
3131
        if ($this->totalcount > $this->perpage) {
3132
            $pagenum = $this->page - 1;
3133
 
3134
            if ($this->page > 0) {
3135
                $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
3136
            }
3137
 
3138
            if ($this->perpage > 0) {
3139
                $lastpage = ceil($this->totalcount / $this->perpage);
3140
            } else {
3141
                $lastpage = 1;
3142
            }
3143
 
3144
            if ($this->page > round(($this->maxdisplay/3)*2)) {
3145
                $currpage = $this->page - round($this->maxdisplay/3);
3146
 
3147
                $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
3148
            } else {
3149
                $currpage = 0;
3150
            }
3151
 
3152
            $displaycount = $displaypage = 0;
3153
 
3154
            while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3155
                $displaypage = $currpage + 1;
3156
 
3157
                if ($this->page == $currpage) {
3158
                    $this->pagelinks[] = html_writer::span($displaypage, 'current-page');
3159
                } else {
3160
                    $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
3161
                    $this->pagelinks[] = $pagelink;
3162
                }
3163
 
3164
                $displaycount++;
3165
                $currpage++;
3166
            }
3167
 
3168
            if ($currpage < $lastpage) {
3169
                $lastpageactual = $lastpage - 1;
3170
                $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
3171
            }
3172
 
3173
            $pagenum = $this->page + 1;
3174
 
3175
            if ($pagenum != $lastpage) {
3176
                $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
3177
            }
3178
        }
3179
    }
3180
 
3181
    /**
3182
     * Export for template.
3183
     *
3184
     * @param renderer_base $output The renderer.
3185
     * @return stdClass
3186
     */
3187
    public function export_for_template(renderer_base $output) {
3188
        $data = new stdClass();
3189
        $data->previous = null;
3190
        $data->next = null;
3191
        $data->first = null;
3192
        $data->last = null;
3193
        $data->label = get_string('page');
3194
        $data->pages = [];
3195
        $data->haspages = $this->totalcount > $this->perpage;
3196
        $data->pagesize = $this->perpage;
3197
 
3198
        if (!$data->haspages) {
3199
            return $data;
3200
        }
3201
 
3202
        if ($this->page > 0) {
3203
            $data->previous = [
3204
                'page' => $this->page,
3205
                'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page - 1]))->out(false)
3206
            ];
3207
        }
3208
 
3209
        $currpage = 0;
3210
        if ($this->page > round(($this->maxdisplay / 3) * 2)) {
3211
            $currpage = $this->page - round($this->maxdisplay / 3);
3212
            $data->first = [
3213
                'page' => 1,
3214
                'url' => (new moodle_url($this->baseurl, [$this->pagevar => 0]))->out(false)
3215
            ];
3216
        }
3217
 
3218
        $lastpage = 1;
3219
        if ($this->perpage > 0) {
3220
            $lastpage = ceil($this->totalcount / $this->perpage);
3221
        }
3222
 
3223
        $displaycount = 0;
3224
        $displaypage = 0;
3225
        while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3226
            $displaypage = $currpage + 1;
3227
 
3228
            $iscurrent = $this->page == $currpage;
3229
            $link = new moodle_url($this->baseurl, [$this->pagevar => $currpage]);
3230
 
3231
            $data->pages[] = [
3232
                'page' => $displaypage,
3233
                'active' => $iscurrent,
3234
                'url' => $iscurrent ? null : $link->out(false)
3235
            ];
3236
 
3237
            $displaycount++;
3238
            $currpage++;
3239
        }
3240
 
3241
        if ($currpage < $lastpage) {
3242
            $data->last = [
3243
                'page' => $lastpage,
3244
                'url' => (new moodle_url($this->baseurl, [$this->pagevar => $lastpage - 1]))->out(false)
3245
            ];
3246
        }
3247
 
3248
        if ($this->page + 1 != $lastpage) {
3249
            $data->next = [
3250
                'page' => $this->page + 2,
3251
                'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page + 1]))->out(false)
3252
            ];
3253
        }
3254
 
3255
        return $data;
3256
    }
3257
}
3258
 
3259
/**
3260
 * Component representing initials bar.
3261
 *
3262
 * @copyright 2017 Ilya Tregubov
3263
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3264
 * @since Moodle 3.3
3265
 * @package core
3266
 * @category output
3267
 */
3268
class initials_bar implements renderable, templatable {
3269
 
3270
    /**
3271
     * @var string Currently selected letter.
3272
     */
3273
    public $current;
3274
 
3275
    /**
3276
     * @var string Class name to add to this initial bar.
3277
     */
3278
    public $class;
3279
 
3280
    /**
3281
     * @var string The name to put in front of this initial bar.
3282
     */
3283
    public $title;
3284
 
3285
    /**
3286
     * @var string URL parameter name for this initial.
3287
     */
3288
    public $urlvar;
3289
 
3290
    /**
3291
     * @var moodle_url URL object.
3292
     */
3293
    public $url;
3294
 
3295
    /**
3296
     * @var array An array of letters in the alphabet.
3297
     */
3298
    public $alpha;
3299
 
3300
    /**
3301
     * @var bool Omit links if we are doing a mini render.
3302
     */
3303
    public $minirender;
3304
 
3305
    /**
3306
     * Constructor initials_bar with only the required params.
3307
     *
3308
     * @param string $current the currently selected letter.
3309
     * @param string $class class name to add to this initial bar.
3310
     * @param string $title the name to put in front of this initial bar.
3311
     * @param string $urlvar URL parameter name for this initial.
3312
     * @param string $url URL object.
3313
     * @param array $alpha of letters in the alphabet.
3314
     * @param bool $minirender Return a trimmed down view of the initials bar.
3315
     */
3316
    public function __construct($current, $class, $title, $urlvar, $url, $alpha = null, bool $minirender = false) {
3317
        $this->current       = $current;
3318
        $this->class    = $class;
3319
        $this->title    = $title;
3320
        $this->urlvar    = $urlvar;
3321
        $this->url    = $url;
3322
        $this->alpha    = $alpha;
3323
        $this->minirender = $minirender;
3324
    }
3325
 
3326
    /**
3327
     * Export for template.
3328
     *
3329
     * @param renderer_base $output The renderer.
3330
     * @return stdClass
3331
     */
3332
    public function export_for_template(renderer_base $output) {
3333
        $data = new stdClass();
3334
 
3335
        if ($this->alpha == null) {
3336
            $this->alpha = explode(',', get_string('alphabet', 'langconfig'));
3337
        }
3338
 
3339
        if ($this->current == 'all') {
3340
            $this->current = '';
3341
        }
3342
 
3343
        // We want to find a letter grouping size which suits the language so
3344
        // find the largest group size which is less than 15 chars.
3345
        // The choice of 15 chars is the largest number of chars that reasonably
3346
        // fits on the smallest supported screen size. By always using a max number
3347
        // of groups which is a factor of 2, we always get nice wrapping, and the
3348
        // last row is always the shortest.
3349
        $groupsize = count($this->alpha);
3350
        $groups = 1;
3351
        while ($groupsize > 15) {
3352
            $groups *= 2;
3353
            $groupsize = ceil(count($this->alpha) / $groups);
3354
        }
3355
 
3356
        $groupsizelimit = 0;
3357
        $groupnumber = 0;
3358
        foreach ($this->alpha as $letter) {
3359
            if ($groupsizelimit++ > 0 && $groupsizelimit % $groupsize == 1) {
3360
                $groupnumber++;
3361
            }
3362
            $groupletter = new stdClass();
3363
            $groupletter->name = $letter;
3364
            if (!$this->minirender) {
3365
                $groupletter->url = $this->url->out(false, array($this->urlvar => $letter));
3366
            } else {
3367
                $groupletter->input = $letter;
3368
            }
3369
            if ($letter == $this->current) {
3370
                $groupletter->selected = $this->current;
3371
            }
3372
            if (!isset($data->group[$groupnumber])) {
3373
                $data->group[$groupnumber] = new stdClass();
3374
            }
3375
            $data->group[$groupnumber]->letter[] = $groupletter;
3376
        }
3377
 
3378
        $data->class = $this->class;
3379
        $data->title = $this->title;
3380
        if (!$this->minirender) {
3381
            $data->url = $this->url->out(false, array($this->urlvar => ''));
3382
        } else {
3383
            $data->input = 'ALL';
3384
        }
3385
        $data->current = $this->current;
3386
        $data->all = get_string('all');
3387
 
3388
        return $data;
3389
    }
3390
}
3391
 
3392
/**
3393
 * This class represents how a block appears on a page.
3394
 *
3395
 * During output, each block instance is asked to return a block_contents object,
3396
 * those are then passed to the $OUTPUT->block function for display.
3397
 *
3398
 * contents should probably be generated using a moodle_block_..._renderer.
3399
 *
3400
 * Other block-like things that need to appear on the page, for example the
3401
 * add new block UI, are also represented as block_contents objects.
3402
 *
3403
 * @copyright 2009 Tim Hunt
3404
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3405
 * @since Moodle 2.0
3406
 * @package core
3407
 * @category output
3408
 */
3409
class block_contents {
3410
 
3411
    /** Used when the block cannot be collapsed **/
3412
    const NOT_HIDEABLE = 0;
3413
 
3414
    /** Used when the block can be collapsed but currently is not **/
3415
    const VISIBLE = 1;
3416
 
3417
    /** Used when the block has been collapsed **/
3418
    const HIDDEN = 2;
3419
 
3420
    /**
3421
     * @var int Used to set $skipid.
3422
     */
3423
    protected static $idcounter = 1;
3424
 
3425
    /**
3426
     * @var int All the blocks (or things that look like blocks) printed on
3427
     * a page are given a unique number that can be used to construct id="" attributes.
3428
     * This is set automatically be the {@link prepare()} method.
3429
     * Do not try to set it manually.
3430
     */
3431
    public $skipid;
3432
 
3433
    /**
3434
     * @var int If this is the contents of a real block, this should be set
3435
     * to the block_instance.id. Otherwise this should be set to 0.
3436
     */
3437
    public $blockinstanceid = 0;
3438
 
3439
    /**
3440
     * @var int If this is a real block instance, and there is a corresponding
3441
     * block_position.id for the block on this page, this should be set to that id.
3442
     * Otherwise it should be 0.
3443
     */
3444
    public $blockpositionid = 0;
3445
 
3446
    /**
3447
     * @var array An array of attribute => value pairs that are put on the outer div of this
3448
     * block. {@link $id} and {@link $classes} attributes should be set separately.
3449
     */
3450
    public $attributes;
3451
 
3452
    /**
3453
     * @var string The title of this block. If this came from user input, it should already
3454
     * have had format_string() processing done on it. This will be output inside
3455
     * <h2> tags. Please do not cause invalid XHTML.
3456
     */
3457
    public $title = '';
3458
 
3459
    /**
3460
     * @var string The label to use when the block does not, or will not have a visible title.
3461
     * You should never set this as well as title... it will just be ignored.
3462
     */
3463
    public $arialabel = '';
3464
 
3465
    /**
3466
     * @var string HTML for the content
3467
     */
3468
    public $content = '';
3469
 
3470
    /**
3471
     * @var array An alternative to $content, it you want a list of things with optional icons.
3472
     */
3473
    public $footer = '';
3474
 
3475
    /**
3476
     * @var string Any small print that should appear under the block to explain
3477
     * to the teacher about the block, for example 'This is a sticky block that was
3478
     * added in the system context.'
3479
     */
3480
    public $annotation = '';
3481
 
3482
    /**
3483
     * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
3484
     * the user can toggle whether this block is visible.
3485
     */
3486
    public $collapsible = self::NOT_HIDEABLE;
3487
 
3488
    /**
3489
     * Set this to true if the block is dockable.
3490
     * @var bool
3491
     */
3492
    public $dockable = false;
3493
 
3494
    /**
3495
     * @var array A (possibly empty) array of editing controls. Each element of
3496
     * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
3497
     * $icon is the icon name. Fed to $OUTPUT->image_url.
3498
     */
3499
    public $controls = array();
3500
 
3501
 
3502
    /**
3503
     * Create new instance of block content
3504
     * @param array $attributes
3505
     */
3506
    public function __construct(array $attributes = null) {
3507
        $this->skipid = self::$idcounter;
3508
        self::$idcounter += 1;
3509
 
3510
        if ($attributes) {
3511
            // standard block
3512
            $this->attributes = $attributes;
3513
        } else {
3514
            // simple "fake" blocks used in some modules and "Add new block" block
3515
            $this->attributes = array('class'=>'block');
3516
        }
3517
    }
3518
 
3519
    /**
3520
     * Add html class to block
3521
     *
3522
     * @param string $class
3523
     */
3524
    public function add_class($class) {
3525
        $this->attributes['class'] .= ' '.$class;
3526
    }
3527
 
3528
    /**
3529
     * Check if the block is a fake block.
3530
     *
3531
     * @return boolean
3532
     */
3533
    public function is_fake() {
3534
        return isset($this->attributes['data-block']) && $this->attributes['data-block'] == '_fake';
3535
    }
3536
}
3537
 
3538
 
3539
/**
3540
 * This class represents a target for where a block can go when it is being moved.
3541
 *
3542
 * This needs to be rendered as a form with the given hidden from fields, and
3543
 * clicking anywhere in the form should submit it. The form action should be
3544
 * $PAGE->url.
3545
 *
3546
 * @copyright 2009 Tim Hunt
3547
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3548
 * @since Moodle 2.0
3549
 * @package core
3550
 * @category output
3551
 */
3552
class block_move_target {
3553
 
3554
    /**
3555
     * @var moodle_url Move url
3556
     */
3557
    public $url;
3558
 
3559
    /**
3560
     * Constructor
3561
     * @param moodle_url $url
3562
     */
3563
    public function __construct(moodle_url $url) {
3564
        $this->url  = $url;
3565
    }
3566
}
3567
 
3568
/**
3569
 * Custom menu item
3570
 *
3571
 * This class is used to represent one item within a custom menu that may or may
3572
 * not have children.
3573
 *
3574
 * @copyright 2010 Sam Hemelryk
3575
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3576
 * @since Moodle 2.0
3577
 * @package core
3578
 * @category output
3579
 */
3580
class custom_menu_item implements renderable, templatable {
3581
 
3582
    /**
3583
     * @var string The text to show for the item
3584
     */
3585
    protected $text;
3586
 
3587
    /**
3588
     * @var moodle_url The link to give the icon if it has no children
3589
     */
3590
    protected $url;
3591
 
3592
    /**
3593
     * @var string A title to apply to the item. By default the text
3594
     */
3595
    protected $title;
3596
 
3597
    /**
3598
     * @var int A sort order for the item, not necessary if you order things in
3599
     * the CFG var.
3600
     */
3601
    protected $sort;
3602
 
3603
    /**
3604
     * @var custom_menu_item A reference to the parent for this item or NULL if
3605
     * it is a top level item
3606
     */
3607
    protected $parent;
3608
 
3609
    /**
3610
     * @var array A array in which to store children this item has.
3611
     */
3612
    protected $children = array();
3613
 
3614
    /**
3615
     * @var int A reference to the sort var of the last child that was added
3616
     */
3617
    protected $lastsort = 0;
3618
 
3619
    /** @var array Array of other HTML attributes for the custom menu item. */
3620
    protected $attributes = [];
3621
 
3622
    /**
3623
     * Constructs the new custom menu item
3624
     *
3625
     * @param string $text
3626
     * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
3627
     * @param string $title A title to apply to this item [Optional]
3628
     * @param int $sort A sort or to use if we need to sort differently [Optional]
3629
     * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
3630
     *        belongs to, only if the child has a parent. [Optional]
3631
     * @param array $attributes Array of other HTML attributes for the custom menu item.
3632
     */
3633
    public function __construct($text, moodle_url $url = null, $title = null, $sort = null, custom_menu_item $parent = null,
3634
        array $attributes = []) {
3635
 
3636
        // Use class setter method for text to ensure it's always a string type.
3637
        $this->set_text($text);
3638
 
3639
        $this->url = $url;
3640
        $this->title = $title;
3641
        $this->sort = (int)$sort;
3642
        $this->parent = $parent;
3643
        $this->attributes = $attributes;
3644
    }
3645
 
3646
    /**
3647
     * Adds a custom menu item as a child of this node given its properties.
3648
     *
3649
     * @param string $text
3650
     * @param moodle_url $url
3651
     * @param string $title
3652
     * @param int $sort
3653
     * @param array $attributes Array of other HTML attributes for the custom menu item.
3654
     * @return custom_menu_item
3655
     */
3656
    public function add($text, moodle_url $url = null, $title = null, $sort = null, $attributes = []) {
3657
        $key = count($this->children);
3658
        if (empty($sort)) {
3659
            $sort = $this->lastsort + 1;
3660
        }
3661
        $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this, $attributes);
3662
        $this->lastsort = (int)$sort;
3663
        return $this->children[$key];
3664
    }
3665
 
3666
    /**
3667
     * Removes a custom menu item that is a child or descendant to the current menu.
3668
     *
3669
     * Returns true if child was found and removed.
3670
     *
3671
     * @param custom_menu_item $menuitem
3672
     * @return bool
3673
     */
3674
    public function remove_child(custom_menu_item $menuitem) {
3675
        $removed = false;
3676
        if (($key = array_search($menuitem, $this->children)) !== false) {
3677
            unset($this->children[$key]);
3678
            $this->children = array_values($this->children);
3679
            $removed = true;
3680
        } else {
3681
            foreach ($this->children as $child) {
3682
                if ($removed = $child->remove_child($menuitem)) {
3683
                    break;
3684
                }
3685
            }
3686
        }
3687
        return $removed;
3688
    }
3689
 
3690
    /**
3691
     * Returns the text for this item
3692
     * @return string
3693
     */
3694
    public function get_text() {
3695
        return $this->text;
3696
    }
3697
 
3698
    /**
3699
     * Returns the url for this item
3700
     * @return moodle_url
3701
     */
3702
    public function get_url() {
3703
        return $this->url;
3704
    }
3705
 
3706
    /**
3707
     * Returns the title for this item
3708
     * @return string
3709
     */
3710
    public function get_title() {
3711
        return $this->title;
3712
    }
3713
 
3714
    /**
3715
     * Sorts and returns the children for this item
3716
     * @return array
3717
     */
3718
    public function get_children() {
3719
        $this->sort();
3720
        return $this->children;
3721
    }
3722
 
3723
    /**
3724
     * Gets the sort order for this child
3725
     * @return int
3726
     */
3727
    public function get_sort_order() {
3728
        return $this->sort;
3729
    }
3730
 
3731
    /**
3732
     * Gets the parent this child belong to
3733
     * @return custom_menu_item
3734
     */
3735
    public function get_parent() {
3736
        return $this->parent;
3737
    }
3738
 
3739
    /**
3740
     * Sorts the children this item has
3741
     */
3742
    public function sort() {
3743
        usort($this->children, array('custom_menu','sort_custom_menu_items'));
3744
    }
3745
 
3746
    /**
3747
     * Returns true if this item has any children
3748
     * @return bool
3749
     */
3750
    public function has_children() {
3751
        return (count($this->children) > 0);
3752
    }
3753
 
3754
    /**
3755
     * Sets the text for the node
3756
     * @param string $text
3757
     */
3758
    public function set_text($text) {
3759
        $this->text = (string)$text;
3760
    }
3761
 
3762
    /**
3763
     * Sets the title for the node
3764
     * @param string $title
3765
     */
3766
    public function set_title($title) {
3767
        $this->title = (string)$title;
3768
    }
3769
 
3770
    /**
3771
     * Sets the url for the node
3772
     * @param moodle_url $url
3773
     */
3774
    public function set_url(moodle_url $url) {
3775
        $this->url = $url;
3776
    }
3777
 
3778
    /**
3779
     * Export this data so it can be used as the context for a mustache template.
3780
     *
3781
     * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
3782
     * @return stdClass
3783
     */
3784
    public function export_for_template(renderer_base $output) {
3785
        $syscontext = context_system::instance();
3786
 
3787
        $context = new stdClass();
3788
        $context->moremenuid = uniqid();
3789
        $context->text = \core_external\util::format_string($this->text, $syscontext->id);
3790
        $context->url = $this->url ? $this->url->out() : null;
3791
        // No need for the title if it's the same with text.
3792
        if ($this->text !== $this->title) {
3793
            // Show the title attribute only if it's different from the text.
3794
            $context->title = \core_external\util::format_string($this->title, $syscontext->id);
3795
        }
3796
        $context->sort = $this->sort;
3797
        if (!empty($this->attributes)) {
3798
            $context->attributes = $this->attributes;
3799
        }
3800
        $context->children = array();
3801
        if (preg_match("/^#+$/", $this->text)) {
3802
            $context->divider = true;
3803
        }
3804
        $context->haschildren = !empty($this->children) && (count($this->children) > 0);
3805
        foreach ($this->children as $child) {
3806
            $child = $child->export_for_template($output);
3807
            array_push($context->children, $child);
3808
        }
3809
 
3810
        return $context;
3811
    }
3812
}
3813
 
3814
/**
3815
 * Custom menu class
3816
 *
3817
 * This class is used to operate a custom menu that can be rendered for the page.
3818
 * The custom menu is built using $CFG->custommenuitems and is a structured collection
3819
 * of custom_menu_item nodes that can be rendered by the core renderer.
3820
 *
3821
 * To configure the custom menu:
3822
 *     Settings: Administration > Appearance > Advanced theme settings
3823
 *
3824
 * @copyright 2010 Sam Hemelryk
3825
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3826
 * @since Moodle 2.0
3827
 * @package core
3828
 * @category output
3829
 */
3830
class custom_menu extends custom_menu_item {
3831
 
3832
    /**
3833
     * @var string The language we should render for, null disables multilang support.
3834
     */
3835
    protected $currentlanguage = null;
3836
 
3837
    /**
3838
     * Creates the custom menu
3839
     *
3840
     * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
3841
     * @param string $currentlanguage the current language code, null disables multilang support
3842
     */
3843
    public function __construct($definition = '', $currentlanguage = null) {
3844
        $this->currentlanguage = $currentlanguage;
3845
        parent::__construct('root'); // create virtual root element of the menu
3846
        if (!empty($definition)) {
3847
            $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
3848
        }
3849
    }
3850
 
3851
    /**
3852
     * Overrides the children of this custom menu. Useful when getting children
3853
     * from $CFG->custommenuitems
3854
     *
3855
     * @param array $children
3856
     */
3857
    public function override_children(array $children) {
3858
        $this->children = array();
3859
        foreach ($children as $child) {
3860
            if ($child instanceof custom_menu_item) {
3861
                $this->children[] = $child;
3862
            }
3863
        }
3864
    }
3865
 
3866
    /**
3867
     * Converts a string into a structured array of custom_menu_items which can
3868
     * then be added to a custom menu.
3869
     *
3870
     * Structure:
3871
     *     text|url|title|langs
3872
     * The number of hyphens at the start determines the depth of the item. The
3873
     * languages are optional, comma separated list of languages the line is for.
3874
     *
3875
     * Example structure:
3876
     *     First level first item|http://www.moodle.com/
3877
     *     -Second level first item|http://www.moodle.com/partners/
3878
     *     -Second level second item|http://www.moodle.com/hq/
3879
     *     --Third level first item|http://www.moodle.com/jobs/
3880
     *     -Second level third item|http://www.moodle.com/development/
3881
     *     First level second item|http://www.moodle.com/feedback/
3882
     *     First level third item
3883
     *     English only|http://moodle.com|English only item|en
3884
     *     German only|http://moodle.de|Deutsch|de,de_du,de_kids
3885
     *
3886
     *
3887
     * @static
3888
     * @param string $text the menu items definition
3889
     * @param string $language the language code, null disables multilang support
3890
     * @return array
3891
     */
3892
    public static function convert_text_to_menu_nodes($text, $language = null) {
3893
        $root = new custom_menu();
3894
        $lastitem = $root;
3895
        $lastdepth = 0;
3896
        $hiddenitems = array();
3897
        $lines = explode("\n", $text);
3898
        foreach ($lines as $linenumber => $line) {
3899
            $line = trim($line);
3900
            if (strlen($line) == 0) {
3901
                continue;
3902
            }
3903
            // Parse item settings.
3904
            $itemtext = null;
3905
            $itemurl = null;
3906
            $itemtitle = null;
3907
            $itemvisible = true;
3908
            $settings = explode('|', $line);
3909
            foreach ($settings as $i => $setting) {
3910
                $setting = trim($setting);
3911
                if ($setting !== '') {
3912
                    switch ($i) {
3913
                        case 0: // Menu text.
3914
                            $itemtext = ltrim($setting, '-');
3915
                            break;
3916
                        case 1: // URL.
3917
                            try {
3918
                                $itemurl = new moodle_url($setting);
3919
                            } catch (moodle_exception $exception) {
3920
                                // We're not actually worried about this, we don't want to mess up the display
3921
                                // just for a wrongly entered URL.
3922
                                $itemurl = null;
3923
                            }
3924
                            break;
3925
                        case 2: // Title attribute.
3926
                            $itemtitle = $setting;
3927
                            break;
3928
                        case 3: // Language.
3929
                            if (!empty($language)) {
3930
                                $itemlanguages = array_map('trim', explode(',', $setting));
3931
                                $itemvisible &= in_array($language, $itemlanguages);
3932
                            }
3933
                            break;
3934
                    }
3935
                }
3936
            }
3937
            // Get depth of new item.
3938
            preg_match('/^(\-*)/', $line, $match);
3939
            $itemdepth = strlen($match[1]) + 1;
3940
            // Find parent item for new item.
3941
            while (($lastdepth - $itemdepth) >= 0) {
3942
                $lastitem = $lastitem->get_parent();
3943
                $lastdepth--;
3944
            }
3945
            $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1);
3946
            $lastdepth++;
3947
            if (!$itemvisible) {
3948
                $hiddenitems[] = $lastitem;
3949
            }
3950
        }
3951
        foreach ($hiddenitems as $item) {
3952
            $item->parent->remove_child($item);
3953
        }
3954
        return $root->get_children();
3955
    }
3956
 
3957
    /**
3958
     * Sorts two custom menu items
3959
     *
3960
     * This function is designed to be used with the usort method
3961
     *     usort($this->children, array('custom_menu','sort_custom_menu_items'));
3962
     *
3963
     * @static
3964
     * @param custom_menu_item $itema
3965
     * @param custom_menu_item $itemb
3966
     * @return int
3967
     */
3968
    public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
3969
        $itema = $itema->get_sort_order();
3970
        $itemb = $itemb->get_sort_order();
3971
        if ($itema == $itemb) {
3972
            return 0;
3973
        }
3974
        return ($itema > $itemb) ? +1 : -1;
3975
    }
3976
}
3977
 
3978
/**
3979
 * Stores one tab
3980
 *
3981
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3982
 * @package core
3983
 */
3984
class tabobject implements renderable, templatable {
3985
    /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
3986
    var $id;
3987
    /** @var moodle_url|string link */
3988
    var $link;
3989
    /** @var string text on the tab */
3990
    var $text;
3991
    /** @var string title under the link, by defaul equals to text */
3992
    var $title;
3993
    /** @var bool whether to display a link under the tab name when it's selected */
3994
    var $linkedwhenselected = false;
3995
    /** @var bool whether the tab is inactive */
3996
    var $inactive = false;
3997
    /** @var bool indicates that this tab's child is selected */
3998
    var $activated = false;
3999
    /** @var bool indicates that this tab is selected */
4000
    var $selected = false;
4001
    /** @var array stores children tabobjects */
4002
    var $subtree = array();
4003
    /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
4004
    var $level = 1;
4005
 
4006
    /**
4007
     * Constructor
4008
     *
4009
     * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
4010
     * @param string|moodle_url $link
4011
     * @param string $text text on the tab
4012
     * @param string $title title under the link, by defaul equals to text
4013
     * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
4014
     */
4015
    public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
4016
        $this->id = $id;
4017
        $this->link = $link;
4018
        $this->text = $text;
4019
        $this->title = $title ? $title : $text;
4020
        $this->linkedwhenselected = $linkedwhenselected;
4021
    }
4022
 
4023
    /**
4024
     * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
4025
     *
4026
     * @param string $selected the id of the selected tab (whatever row it's on),
4027
     *    if null marks all tabs as unselected
4028
     * @return bool whether this tab is selected or contains selected tab in its subtree
4029
     */
4030
    protected function set_selected($selected) {
4031
        if ((string)$selected === (string)$this->id) {
4032
            $this->selected = true;
4033
            // This tab is selected. No need to travel through subtree.
4034
            return true;
4035
        }
4036
        foreach ($this->subtree as $subitem) {
4037
            if ($subitem->set_selected($selected)) {
4038
                // This tab has child that is selected. Mark it as activated. No need to check other children.
4039
                $this->activated = true;
4040
                return true;
4041
            }
4042
        }
4043
        return false;
4044
    }
4045
 
4046
    /**
4047
     * Travels through tree and finds a tab with specified id
4048
     *
4049
     * @param string $id
4050
     * @return tabtree|null
4051
     */
4052
    public function find($id) {
4053
        if ((string)$this->id === (string)$id) {
4054
            return $this;
4055
        }
4056
        foreach ($this->subtree as $tab) {
4057
            if ($obj = $tab->find($id)) {
4058
                return $obj;
4059
            }
4060
        }
4061
        return null;
4062
    }
4063
 
4064
    /**
4065
     * Allows to mark each tab's level in the tree before rendering.
4066
     *
4067
     * @param int $level
4068
     */
4069
    protected function set_level($level) {
4070
        $this->level = $level;
4071
        foreach ($this->subtree as $tab) {
4072
            $tab->set_level($level + 1);
4073
        }
4074
    }
4075
 
4076
    /**
4077
     * Export for template.
4078
     *
4079
     * @param renderer_base $output Renderer.
4080
     * @return object
4081
     */
4082
    public function export_for_template(renderer_base $output) {
4083
        if ($this->inactive || ($this->selected && !$this->linkedwhenselected) || $this->activated) {
4084
            $link = null;
4085
        } else {
4086
            $link = $this->link;
4087
        }
4088
        $active = $this->activated || $this->selected;
4089
 
4090
        return (object) [
4091
            'id' => $this->id,
4092
            'link' => is_object($link) ? $link->out(false) : $link,
4093
            'text' => $this->text,
4094
            'title' => $this->title,
4095
            'inactive' => !$active && $this->inactive,
4096
            'active' => $active,
4097
            'level' => $this->level,
4098
        ];
4099
    }
4100
 
4101
}
4102
 
4103
/**
4104
 * Renderable for the main page header.
4105
 *
4106
 * @package core
4107
 * @category output
4108
 * @since 2.9
4109
 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
4110
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4111
 */
4112
class context_header implements renderable, templatable {
4113
 
4114
    /**
4115
     * @var string $heading Main heading.
4116
     */
4117
    public $heading;
4118
    /**
4119
     * @var int $headinglevel Main heading 'h' tag level.
4120
     */
4121
    public $headinglevel;
4122
    /**
4123
     * @var string|null $imagedata HTML code for the picture in the page header.
4124
     */
4125
    public $imagedata;
4126
    /**
4127
     * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
4128
     *      array elements - title => alternate text for the image, or if no image is available the button text.
4129
     *                       url => Link for the button to head to. Should be a moodle_url.
4130
     *                       image => location to the image, or name of the image in /pix/t/{image name}.
4131
     *                       linkattributes => additional attributes for the <a href> element.
4132
     *                       page => page object. Don't include if the image is an external image.
4133
     */
4134
    public $additionalbuttons;
4135
    /**
4136
     * @var string $prefix A string that is before the title.
4137
     */
4138
    public $prefix;
4139
 
4140
    /**
4141
     * Constructor.
4142
     *
4143
     * @param string $heading Main heading data.
4144
     * @param int $headinglevel Main heading 'h' tag level.
4145
     * @param string|null $imagedata HTML code for the picture in the page header.
4146
     * @param string $additionalbuttons Buttons for the header e.g. Messaging button for the user header.
4147
     * @param string $prefix Text that precedes the heading.
4148
     */
4149
    public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null, $prefix = null) {
4150
 
4151
        $this->heading = $heading;
4152
        $this->headinglevel = $headinglevel;
4153
        $this->imagedata = $imagedata;
4154
        $this->additionalbuttons = $additionalbuttons;
4155
        // If we have buttons then format them.
4156
        if (isset($this->additionalbuttons)) {
4157
            $this->format_button_images();
4158
        }
4159
        $this->prefix = $prefix;
4160
    }
4161
 
4162
    /**
4163
     * Adds an array element for a formatted image.
4164
     */
4165
    protected function format_button_images() {
4166
 
4167
        foreach ($this->additionalbuttons as $buttontype => $button) {
4168
            $page = $button['page'];
4169
            // If no image is provided then just use the title.
4170
            if (!isset($button['image'])) {
4171
                $this->additionalbuttons[$buttontype]['formattedimage'] = $button['title'];
4172
            } else {
4173
                // Check to see if this is an internal Moodle icon.
4174
                $internalimage = $page->theme->resolve_image_location('t/' . $button['image'], 'moodle');
4175
                if ($internalimage) {
4176
                    $this->additionalbuttons[$buttontype]['formattedimage'] = 't/' . $button['image'];
4177
                } else {
4178
                    // Treat as an external image.
4179
                    $this->additionalbuttons[$buttontype]['formattedimage'] = $button['image'];
4180
                }
4181
            }
4182
 
4183
            if (isset($button['linkattributes']['class'])) {
4184
                $class = $button['linkattributes']['class'] . ' btn';
4185
            } else {
4186
                $class = 'btn';
4187
            }
4188
            // Add the bootstrap 'btn' class for formatting.
4189
            $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
4190
                array('class' => $class));
4191
        }
4192
    }
4193
 
4194
    /**
4195
     * Export for template.
4196
     *
4197
     * @param renderer_base $output Renderer.
4198
     * @return array
4199
     */
4200
    public function export_for_template(renderer_base $output): array {
4201
        // Heading.
4202
        $headingtext = isset($this->heading) ? $this->heading : $output->get_page()->heading;
4203
        $heading = $output->heading($headingtext, $this->headinglevel, "h2 mb-0");
4204
 
4205
        // Buttons.
4206
        if (isset($this->additionalbuttons)) {
4207
            $additionalbuttons = [];
4208
            foreach ($this->additionalbuttons as $button) {
4209
                if (!isset($button->page)) {
4210
                    // Include js for messaging.
4211
                    if ($button['buttontype'] === 'togglecontact') {
4212
                        \core_message\helper::togglecontact_requirejs();
4213
                    }
4214
                    if ($button['buttontype'] === 'message') {
4215
                        \core_message\helper::messageuser_requirejs();
4216
                    }
4217
                }
4218
                foreach ($button['linkattributes'] as $key => $value) {
4219
                    $button['attributes'][] = ['name' => $key, 'value' => $value];
4220
                }
4221
                $additionalbuttons[] = $button;
4222
            }
4223
        }
4224
 
4225
        return [
4226
            'heading' => $heading,
4227
            'headinglevel' => $this->headinglevel,
4228
            'imagedata' => $this->imagedata,
4229
            'prefix' => $this->prefix,
4230
            'hasadditionalbuttons' => !empty($additionalbuttons),
4231
            'additionalbuttons' => $additionalbuttons ?? [],
4232
        ];
4233
    }
4234
}
4235
 
4236
/**
4237
 * Stores tabs list
4238
 *
4239
 * Example how to print a single line tabs:
4240
 * $rows = array(
4241
 *    new tabobject(...),
4242
 *    new tabobject(...)
4243
 * );
4244
 * echo $OUTPUT->tabtree($rows, $selectedid);
4245
 *
4246
 * Multiple row tabs may not look good on some devices but if you want to use them
4247
 * you can specify ->subtree for the active tabobject.
4248
 *
4249
 * @copyright 2013 Marina Glancy
4250
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4251
 * @since Moodle 2.5
4252
 * @package core
4253
 * @category output
4254
 */
4255
class tabtree extends tabobject {
4256
    /**
4257
     * Constuctor
4258
     *
4259
     * It is highly recommended to call constructor when list of tabs is already
4260
     * populated, this way you ensure that selected and inactive tabs are located
4261
     * and attribute level is set correctly.
4262
     *
4263
     * @param array $tabs array of tabs, each of them may have it's own ->subtree
4264
     * @param string|null $selected which tab to mark as selected, all parent tabs will
4265
     *     automatically be marked as activated
4266
     * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4267
     *     their level. Note that you can as weel specify tabobject::$inactive for separate instances
4268
     */
4269
    public function __construct($tabs, $selected = null, $inactive = null) {
4270
        $this->subtree = $tabs;
4271
        if ($selected !== null) {
4272
            $this->set_selected($selected);
4273
        }
4274
        if ($inactive !== null) {
4275
            if (is_array($inactive)) {
4276
                foreach ($inactive as $id) {
4277
                    if ($tab = $this->find($id)) {
4278
                        $tab->inactive = true;
4279
                    }
4280
                }
4281
            } else if ($tab = $this->find($inactive)) {
4282
                $tab->inactive = true;
4283
            }
4284
        }
4285
        $this->set_level(0);
4286
    }
4287
 
4288
    /**
4289
     * Export for template.
4290
     *
4291
     * @param renderer_base $output Renderer.
4292
     * @return object
4293
     */
4294
    public function export_for_template(renderer_base $output) {
4295
        $tabs = [];
4296
        $secondrow = false;
4297
 
4298
        foreach ($this->subtree as $tab) {
4299
            $tabs[] = $tab->export_for_template($output);
4300
            if (!empty($tab->subtree) && ($tab->level == 0 || $tab->selected || $tab->activated)) {
4301
                $secondrow = new tabtree($tab->subtree);
4302
            }
4303
        }
4304
 
4305
        return (object) [
4306
            'tabs' => $tabs,
4307
            'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false
4308
        ];
4309
    }
4310
}
4311
 
4312
/**
4313
 * An action menu.
4314
 *
4315
 * This action menu component takes a series of primary and secondary actions.
4316
 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
4317
 * down menu.
4318
 *
4319
 * @package core
4320
 * @category output
4321
 * @copyright 2013 Sam Hemelryk
4322
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4323
 */
4324
class action_menu implements renderable, templatable {
4325
 
4326
    /**
4327
     * Top right alignment.
4328
     */
4329
    const TL = 1;
4330
 
4331
    /**
4332
     * Top right alignment.
4333
     */
4334
    const TR = 2;
4335
 
4336
    /**
4337
     * Top right alignment.
4338
     */
4339
    const BL = 3;
4340
 
4341
    /**
4342
     * Top right alignment.
4343
     */
4344
    const BR = 4;
4345
 
4346
    /**
4347
     * The instance number. This is unique to this instance of the action menu.
4348
     * @var int
4349
     */
4350
    protected $instance = 0;
4351
 
4352
    /**
4353
     * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
4354
     * @var array
4355
     */
4356
    protected $primaryactions = array();
4357
 
4358
    /**
4359
     * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
4360
     * @var array
4361
     */
4362
    protected $secondaryactions = array();
4363
 
4364
    /**
4365
     * An array of attributes added to the container of the action menu.
4366
     * Initialised with defaults during construction.
4367
     * @var array
4368
     */
4369
    public $attributes = array();
4370
    /**
4371
     * An array of attributes added to the container of the primary actions.
4372
     * Initialised with defaults during construction.
4373
     * @var array
4374
     */
4375
    public $attributesprimary = array();
4376
    /**
4377
     * An array of attributes added to the container of the secondary actions.
4378
     * Initialised with defaults during construction.
4379
     * @var array
4380
     */
4381
    public $attributessecondary = array();
4382
 
4383
    /**
4384
     * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
4385
     * @var array
4386
     */
4387
    public $actiontext = null;
4388
 
4389
    /**
4390
     * The string to use for the accessible label for the menu.
4391
     * @var array
4392
     */
4393
    public $actionlabel = null;
4394
 
4395
    /**
4396
     * An icon to use for the toggling the secondary menu (dropdown).
4397
     * @var pix_icon
4398
     */
4399
    public $actionicon;
4400
 
4401
    /**
4402
     * Any text to use for the toggling the secondary menu (dropdown).
4403
     * @var string
4404
     */
4405
    public $menutrigger = '';
4406
 
4407
    /**
4408
     * An array of attributes added to the trigger element of the secondary menu.
4409
     * @var array
4410
     */
4411
    public $triggerattributes = [];
4412
 
4413
    /**
4414
     * Any extra classes for toggling to the secondary menu.
4415
     * @var string
4416
     */
4417
    public $triggerextraclasses = '';
4418
 
4419
    /**
4420
     * Place the action menu before all other actions.
4421
     * @var bool
4422
     */
4423
    public $prioritise = false;
4424
 
4425
    /**
4426
     * Dropdown menu alignment class.
4427
     * @var string
4428
     */
4429
    public $dropdownalignment = '';
4430
 
4431
    /**
4432
     * Constructs the action menu with the given items.
4433
     *
4434
     * @param array $actions An array of actions (action_menu_link|pix_icon|string).
4435
     */
4436
    public function __construct(array $actions = array()) {
4437
        static $initialised = 0;
4438
        $this->instance = $initialised;
4439
        $initialised++;
4440
 
4441
        $this->attributes = array(
4442
            'id' => 'action-menu-'.$this->instance,
4443
            'class' => 'moodle-actionmenu',
4444
            'data-enhance' => 'moodle-core-actionmenu'
4445
        );
4446
        $this->attributesprimary = array(
4447
            'id' => 'action-menu-'.$this->instance.'-menubar',
4448
            'class' => 'menubar',
4449
        );
4450
        $this->attributessecondary = array(
4451
            'id' => 'action-menu-'.$this->instance.'-menu',
4452
            'class' => 'menu',
4453
            'data-rel' => 'menu-content',
4454
            'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
4455
            'role' => 'menu'
4456
        );
4457
        $this->dropdownalignment = 'dropdown-menu-right';
4458
        foreach ($actions as $action) {
4459
            $this->add($action);
4460
        }
4461
    }
4462
 
4463
    /**
4464
     * Sets the label for the menu trigger.
4465
     *
4466
     * @param string $label The text
4467
     */
4468
    public function set_action_label($label) {
4469
        $this->actionlabel = $label;
4470
    }
4471
 
4472
    /**
4473
     * Sets the menu trigger text.
4474
     *
4475
     * @param string $trigger The text
4476
     * @param string $extraclasses Extra classes to style the secondary menu toggle.
4477
     */
4478
    public function set_menu_trigger($trigger, $extraclasses = '') {
4479
        $this->menutrigger = $trigger;
4480
        $this->triggerextraclasses = $extraclasses;
4481
    }
4482
 
4483
    /**
4484
     * Classes for the trigger menu
4485
     */
4486
    const DEFAULT_KEBAB_TRIGGER_CLASSES = 'btn btn-icon d-flex align-items-center justify-content-center no-caret';
4487
 
4488
    /**
4489
     * Setup trigger as in the kebab menu.
4490
     *
4491
     * @param string|null $triggername
4492
     * @param core_renderer|null $output
4493
     * @param string|null $extraclasses extra classes for the trigger {@see self::set_menu_trigger()}
4494
     * @throws coding_exception
4495
     */
4496
    public function set_kebab_trigger(?string $triggername = null, ?core_renderer $output = null,
4497
        ?string $extraclasses = '') {
4498
        global $OUTPUT;
4499
        if (empty($output)) {
4500
            $output = $OUTPUT;
4501
        }
4502
        $label = $triggername ?? get_string('actions');
4503
        $triggerclasses = self::DEFAULT_KEBAB_TRIGGER_CLASSES . ' ' . $extraclasses;
4504
        $icon = $output->pix_icon('i/menu', $label);
4505
        $this->set_menu_trigger($icon, $triggerclasses);
4506
    }
4507
 
4508
    /**
4509
     * Return true if there is at least one visible link in the menu.
4510
     *
4511
     * @return bool
4512
     */
4513
    public function is_empty() {
4514
        return !count($this->primaryactions) && !count($this->secondaryactions);
4515
    }
4516
 
4517
    /**
4518
     * Initialises JS required fore the action menu.
4519
     * The JS is only required once as it manages all action menu's on the page.
4520
     *
4521
     * @param moodle_page $page
4522
     */
4523
    public function initialise_js(moodle_page $page) {
4524
        static $initialised = false;
4525
        if (!$initialised) {
4526
            $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
4527
            $initialised = true;
4528
        }
4529
    }
4530
 
4531
    /**
4532
     * Adds an action to this action menu.
4533
     *
4534
     * @param action_link|pix_icon|subpanel|string $action
4535
     */
4536
    public function add($action) {
4537
 
4538
        if ($action instanceof subpanel) {
4539
            $this->add_secondary_subpanel($action);
4540
        } else if ($action instanceof action_link) {
4541
            if ($action->primary) {
4542
                $this->add_primary_action($action);
4543
            } else {
4544
                $this->add_secondary_action($action);
4545
            }
4546
        } else if ($action instanceof pix_icon) {
4547
            $this->add_primary_action($action);
4548
        } else {
4549
            $this->add_secondary_action($action);
4550
        }
4551
    }
4552
 
4553
    /**
4554
     * Adds a secondary subpanel.
4555
     * @param subpanel $subpanel
4556
     */
4557
    public function add_secondary_subpanel(subpanel $subpanel) {
4558
        $this->secondaryactions[] = $subpanel;
4559
    }
4560
 
4561
    /**
4562
     * Adds a primary action to the action menu.
4563
     *
4564
     * @param action_menu_link|action_link|pix_icon|string $action
4565
     */
4566
    public function add_primary_action($action) {
4567
        if ($action instanceof action_link || $action instanceof pix_icon) {
4568
            $action->attributes['role'] = 'menuitem';
4569
            $action->attributes['tabindex'] = '-1';
4570
            if ($action instanceof action_menu_link) {
4571
                $action->actionmenu = $this;
4572
            }
4573
        }
4574
        $this->primaryactions[] = $action;
4575
    }
4576
 
4577
    /**
4578
     * Adds a secondary action to the action menu.
4579
     *
4580
     * @param action_link|pix_icon|string $action
4581
     */
4582
    public function add_secondary_action($action) {
4583
        if ($action instanceof action_link || $action instanceof pix_icon) {
4584
            $action->attributes['role'] = 'menuitem';
4585
            $action->attributes['tabindex'] = '-1';
4586
            if ($action instanceof action_menu_link) {
4587
                $action->actionmenu = $this;
4588
            }
4589
        }
4590
        $this->secondaryactions[] = $action;
4591
    }
4592
 
4593
    /**
4594
     * Returns the primary actions ready to be rendered.
4595
     *
4596
     * @param core_renderer $output The renderer to use for getting icons.
4597
     * @return array
4598
     */
4599
    public function get_primary_actions(core_renderer $output = null) {
4600
        global $OUTPUT;
4601
        if ($output === null) {
4602
            $output = $OUTPUT;
4603
        }
4604
        $pixicon = $this->actionicon;
4605
        $linkclasses = array('toggle-display');
4606
 
4607
        $title = '';
4608
        if (!empty($this->menutrigger)) {
4609
            $pixicon = '<b class="caret"></b>';
4610
            $linkclasses[] = 'textmenu';
4611
        } else {
4612
            $title = new lang_string('actionsmenu', 'moodle');
4613
            $this->actionicon = new pix_icon(
4614
                't/edit_menu',
4615
                '',
4616
                'moodle',
4617
                array('class' => 'iconsmall actionmenu', 'title' => '')
4618
            );
4619
            $pixicon = $this->actionicon;
4620
        }
4621
        if ($pixicon instanceof renderable) {
4622
            $pixicon = $output->render($pixicon);
4623
            if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
4624
                $title = $pixicon->attributes['alt'];
4625
            }
4626
        }
4627
        $string = '';
4628
        if ($this->actiontext) {
4629
            $string = $this->actiontext;
4630
        }
4631
        $label = '';
4632
        if ($this->actionlabel) {
4633
            $label = $this->actionlabel;
4634
        } else {
4635
            $label = $title;
4636
        }
4637
        $actions = $this->primaryactions;
4638
        $attributes = array(
4639
            'class' => implode(' ', $linkclasses),
4640
            'title' => $title,
4641
            'aria-label' => $label,
4642
            'id' => 'action-menu-toggle-'.$this->instance,
4643
            'role' => 'menuitem',
4644
            'tabindex' => '-1',
4645
        );
4646
        $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
4647
        if ($this->prioritise) {
4648
            array_unshift($actions, $link);
4649
        } else {
4650
            $actions[] = $link;
4651
        }
4652
        return $actions;
4653
    }
4654
 
4655
    /**
4656
     * Returns the secondary actions ready to be rendered.
4657
     * @return array
4658
     */
4659
    public function get_secondary_actions() {
4660
        return $this->secondaryactions;
4661
    }
4662
 
4663
    /**
4664
     * Sets the selector that should be used to find the owning node of this menu.
4665
     * @param string $selector A CSS/YUI selector to identify the owner of the menu.
4666
     */
4667
    public function set_owner_selector($selector) {
4668
        $this->attributes['data-owner'] = $selector;
4669
    }
4670
 
4671
    /**
4672
     * Sets the alignment of the dialogue in relation to button used to toggle it.
4673
     *
4674
     * @deprecated since Moodle 4.0
4675
     *
4676
     * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4677
     * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4678
     */
4679
    public function set_alignment($dialogue, $button) {
4680
        debugging('The method action_menu::set_alignment() is deprecated, use action_menu::set_menu_left()', DEBUG_DEVELOPER);
4681
        if (isset($this->attributessecondary['data-align'])) {
4682
            // We've already got one set, lets remove the old class so as to avoid troubles.
4683
            $class = $this->attributessecondary['class'];
4684
            $search = 'align-'.$this->attributessecondary['data-align'];
4685
            $this->attributessecondary['class'] = str_replace($search, '', $class);
4686
        }
4687
        $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
4688
        $this->attributessecondary['data-align'] = $align;
4689
        $this->attributessecondary['class'] .= ' align-'.$align;
4690
    }
4691
 
4692
    /**
4693
     * Returns a string to describe the alignment.
4694
     *
4695
     * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4696
     * @return string
4697
     */
4698
    protected function get_align_string($align) {
4699
        switch ($align) {
4700
            case self::TL :
4701
                return 'tl';
4702
            case self::TR :
4703
                return 'tr';
4704
            case self::BL :
4705
                return 'bl';
4706
            case self::BR :
4707
                return 'br';
4708
            default :
4709
                return 'tl';
4710
        }
4711
    }
4712
 
4713
    /**
4714
     * Aligns the left corner of the dropdown.
4715
     *
4716
     */
4717
    public function set_menu_left() {
4718
        $this->dropdownalignment = 'dropdown-menu-left';
4719
    }
4720
 
4721
    /**
4722
     * Sets a constraint for the dialogue.
4723
     *
4724
     * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
4725
     * element the constraint identifies.
4726
     *
4727
     * This is required whenever the action menu is displayed inside any CSS element with the .no-overflow class
4728
     * (flexible_table and any of it's child classes are a likely candidate).
4729
     *
4730
     * @deprecated since Moodle 4.3
4731
     * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
4732
     */
4733
    public function set_constraint($ancestorselector) {
4734
        debugging('The method set_constraint() is deprecated. Please use the set_boundary() method instead.', DEBUG_DEVELOPER);
4735
        $this->set_boundary('window');
4736
    }
4737
 
4738
    /**
4739
     * Set the overflow constraint boundary of the dropdown menu.
4740
     * @see https://getbootstrap.com/docs/4.6/components/dropdowns/#options The 'boundary' option in the Bootstrap documentation
4741
     *
4742
     * @param string $boundary Accepts the values of 'viewport', 'window', or 'scrollParent'.
4743
     * @throws coding_exception
4744
     */
4745
    public function set_boundary(string $boundary) {
4746
        if (!in_array($boundary, ['viewport', 'window', 'scrollParent'])) {
4747
            throw new coding_exception("HTMLElement reference boundaries are not supported." .
4748
                "Accepted boundaries are 'viewport', 'window', or 'scrollParent'.", DEBUG_DEVELOPER);
4749
        }
4750
 
4751
        $this->triggerattributes['data-boundary'] = $boundary;
4752
    }
4753
 
4754
    /**
4755
     * If you call this method the action menu will be displayed but will not be enhanced.
4756
     *
4757
     * By not displaying the menu enhanced all items will be displayed in a single row.
4758
     *
4759
     * @deprecated since Moodle 3.2
4760
     */
4761
    public function do_not_enhance() {
4762
        debugging('The method action_menu::do_not_enhance() is deprecated, use a list of action_icon instead.', DEBUG_DEVELOPER);
4763
    }
4764
 
4765
    /**
4766
     * Returns true if this action menu will be enhanced.
4767
     *
4768
     * @return bool
4769
     */
4770
    public function will_be_enhanced() {
4771
        return isset($this->attributes['data-enhance']);
4772
    }
4773
 
4774
    /**
4775
     * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
4776
     *
4777
     * This property can be useful when the action menu is displayed within a parent element that is either floated
4778
     * or relatively positioned.
4779
     * In that situation the width of the menu is determined by the width of the parent element which may not be large
4780
     * enough for the menu items without them wrapping.
4781
     * This disables the wrapping so that the menu takes on the width of the longest item.
4782
     *
4783
     * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
4784
     */
4785
    public function set_nowrap_on_items($value = true) {
4786
        $class = 'nowrap-items';
4787
        if (!empty($this->attributes['class'])) {
4788
            $pos = strpos($this->attributes['class'], $class);
4789
            if ($value === true && $pos === false) {
4790
                // The value is true and the class has not been set yet. Add it.
4791
                $this->attributes['class'] .= ' '.$class;
4792
            } else if ($value === false && $pos !== false) {
4793
                // The value is false and the class has been set. Remove it.
4794
                $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class));
4795
            }
4796
        } else if ($value) {
4797
            // The value is true and the class has not been set yet. Add it.
4798
            $this->attributes['class'] = $class;
4799
        }
4800
    }
4801
 
4802
    /**
4803
     * Add classes to the action menu for an easier styling.
4804
     *
4805
     * @param string $class The class to add to attributes.
4806
     */
4807
    public function set_additional_classes(string $class = '') {
4808
        if (!empty($this->attributes['class'])) {
4809
            $this->attributes['class'] .= " ".$class;
4810
        } else {
4811
            $this->attributes['class'] = $class;
4812
        }
4813
    }
4814
 
4815
    /**
4816
     * Export for template.
4817
     *
4818
     * @param renderer_base $output The renderer.
4819
     * @return stdClass
4820
     */
4821
    public function export_for_template(renderer_base $output) {
4822
        $data = new stdClass();
4823
        // Assign a role of menubar to this action menu when:
4824
        // - it contains 2 or more primary actions; or
4825
        // - if it contains a primary action and secondary actions.
4826
        if (count($this->primaryactions) > 1 || (!empty($this->primaryactions) && !empty($this->secondaryactions))) {
4827
            $this->attributes['role'] = 'menubar';
4828
        }
4829
        $attributes = $this->attributes;
4830
 
4831
        $data->instance = $this->instance;
4832
 
4833
        $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
4834
        unset($attributes['class']);
4835
 
4836
        $data->attributes = array_map(function($key, $value) {
4837
            return [ 'name' => $key, 'value' => $value ];
4838
        }, array_keys($attributes), $attributes);
4839
 
4840
        $data->primary = $this->export_primary_actions_for_template($output);
4841
        $data->secondary = $this->export_secondary_actions_for_template($output);
4842
        $data->dropdownalignment = $this->dropdownalignment;
4843
 
4844
        return $data;
4845
    }
4846
 
4847
    /**
4848
     * Export the primary actions for the template.
4849
     * @param renderer_base $output
4850
     * @return stdClass
4851
     */
4852
    protected function export_primary_actions_for_template(renderer_base $output): stdClass {
4853
        $attributes = $this->attributes;
4854
        $attributesprimary = $this->attributesprimary;
4855
 
4856
        $primary = new stdClass();
4857
        $primary->title = '';
4858
        $primary->prioritise = $this->prioritise;
4859
 
4860
        $primary->classes = isset($attributesprimary['class']) ? $attributesprimary['class'] : '';
4861
        unset($attributesprimary['class']);
4862
 
4863
        $primary->attributes = array_map(function ($key, $value) {
4864
            return ['name' => $key, 'value' => $value];
4865
        }, array_keys($attributesprimary), $attributesprimary);
4866
        $primary->triggerattributes = array_map(function ($key, $value) {
4867
            return ['name' => $key, 'value' => $value];
4868
        }, array_keys($this->triggerattributes), $this->triggerattributes);
4869
 
4870
        $actionicon = $this->actionicon;
4871
        if (!empty($this->menutrigger)) {
4872
            $primary->menutrigger = $this->menutrigger;
4873
            $primary->triggerextraclasses = $this->triggerextraclasses;
4874
            if ($this->actionlabel) {
4875
                $primary->title = $this->actionlabel;
4876
            } else if ($this->actiontext) {
4877
                $primary->title = $this->actiontext;
4878
            } else {
4879
                $primary->title = strip_tags($this->menutrigger);
4880
            }
4881
        } else {
4882
            $primary->title = get_string('actionsmenu');
4883
            $iconattributes = ['class' => 'iconsmall actionmenu', 'title' => $primary->title];
4884
            $actionicon = new pix_icon('t/edit_menu', '', 'moodle', $iconattributes);
4885
        }
4886
 
4887
        // If the menu trigger is within the menubar, assign a role of menuitem. Otherwise, assign as a button.
4888
        $primary->triggerrole = 'button';
4889
        if (isset($attributes['role']) && $attributes['role'] === 'menubar') {
4890
            $primary->triggerrole = 'menuitem';
4891
        }
4892
 
4893
        if ($actionicon instanceof pix_icon) {
4894
            $primary->icon = $actionicon->export_for_pix();
4895
            if (!empty($actionicon->attributes['alt'])) {
4896
                $primary->title = $actionicon->attributes['alt'];
4897
            }
4898
        } else {
4899
            $primary->iconraw = $actionicon ? $output->render($actionicon) : '';
4900
        }
4901
 
4902
        $primary->actiontext = $this->actiontext ? (string) $this->actiontext : '';
4903
        $primary->items = array_map(function ($item) use ($output) {
4904
            $data = (object) [];
4905
            if ($item instanceof action_menu_link) {
4906
                $data->actionmenulink = $item->export_for_template($output);
4907
            } else if ($item instanceof action_menu_filler) {
4908
                $data->actionmenufiller = $item->export_for_template($output);
4909
            } else if ($item instanceof action_link) {
4910
                $data->actionlink = $item->export_for_template($output);
4911
            } else if ($item instanceof pix_icon) {
4912
                $data->pixicon = $item->export_for_template($output);
4913
            } else {
4914
                $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4915
            }
4916
            return $data;
4917
        }, $this->primaryactions);
4918
        return $primary;
4919
    }
4920
 
4921
    /**
4922
     * Export the secondary actions for the template.
4923
     * @param renderer_base $output
4924
     * @return stdClass
4925
     */
4926
    protected function export_secondary_actions_for_template(renderer_base $output): stdClass {
4927
        $attributessecondary = $this->attributessecondary;
4928
        $secondary = new stdClass();
4929
        $secondary->classes = isset($attributessecondary['class']) ? $attributessecondary['class'] : '';
4930
        unset($attributessecondary['class']);
4931
 
4932
        $secondary->attributes = array_map(function ($key, $value) {
4933
            return ['name' => $key, 'value' => $value];
4934
        }, array_keys($attributessecondary), $attributessecondary);
4935
        $secondary->items = array_map(function ($item) use ($output) {
4936
            $data = (object) [
4937
                'simpleitem' => true,
4938
            ];
4939
            if ($item instanceof action_menu_link) {
4940
                $data->actionmenulink = $item->export_for_template($output);
4941
                $data->simpleitem = false;
4942
            } else if ($item instanceof action_menu_filler) {
4943
                $data->actionmenufiller = $item->export_for_template($output);
4944
                $data->simpleitem = false;
4945
            } else if ($item instanceof subpanel) {
4946
                $data->subpanel = $item->export_for_template($output);
4947
                $data->simpleitem = false;
4948
            } else if ($item instanceof action_link) {
4949
                $data->actionlink = $item->export_for_template($output);
4950
            } else if ($item instanceof pix_icon) {
4951
                $data->pixicon = $item->export_for_template($output);
4952
            } else {
4953
                $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4954
            }
4955
            return $data;
4956
        }, $this->secondaryactions);
4957
        return $secondary;
4958
    }
4959
}
4960
 
4961
/**
4962
 * An action menu filler
4963
 *
4964
 * @package core
4965
 * @category output
4966
 * @copyright 2013 Andrew Nicols
4967
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4968
 */
4969
class action_menu_filler extends action_link implements renderable {
4970
 
4971
    /**
4972
     * True if this is a primary action. False if not.
4973
     * @var bool
4974
     */
4975
    public $primary = true;
4976
 
4977
    /**
4978
     * Constructs the object.
4979
     */
4980
    public function __construct() {
4981
        $this->attributes['id'] = html_writer::random_id('action_link');
4982
    }
4983
}
4984
 
4985
/**
4986
 * An action menu action
4987
 *
4988
 * @package core
4989
 * @category output
4990
 * @copyright 2013 Sam Hemelryk
4991
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4992
 */
4993
class action_menu_link extends action_link implements renderable {
4994
 
4995
    /**
4996
     * True if this is a primary action. False if not.
4997
     * @var bool
4998
     */
4999
    public $primary = true;
5000
 
5001
    /**
5002
     * The action menu this link has been added to.
5003
     * @var action_menu
5004
     */
5005
    public $actionmenu = null;
5006
 
5007
    /**
5008
     * The number of instances of this action menu link (and its subclasses).
5009
     *
5010
     * @deprecated since Moodle 4.4.
5011
     * @var int
5012
     */
5013
    protected static $instance = 1;
5014
 
5015
    /**
5016
     * Constructs the object.
5017
     *
5018
     * @param moodle_url $url The URL for the action.
5019
     * @param pix_icon|null $icon The icon to represent the action.
5020
     * @param string $text The text to represent the action.
5021
     * @param bool $primary Whether this is a primary action or not.
5022
     * @param array $attributes Any attribtues associated with the action.
5023
     */
5024
    public function __construct(moodle_url $url, ?pix_icon $icon, $text, $primary = true, array $attributes = array()) {
5025
        parent::__construct($url, $text, null, $attributes, $icon);
5026
        $this->primary = (bool)$primary;
5027
        $this->add_class('menu-action');
5028
        $this->attributes['role'] = 'menuitem';
5029
    }
5030
 
5031
    /**
5032
     * Export for template.
5033
     *
5034
     * @param renderer_base $output The renderer.
5035
     * @return stdClass
5036
     */
5037
    public function export_for_template(renderer_base $output) {
5038
        $data = parent::export_for_template($output);
5039
 
5040
        // Ignore what the parent did with the attributes, except for ID and class.
5041
        $data->attributes = [];
5042
        $attributes = $this->attributes;
5043
        unset($attributes['id']);
5044
        unset($attributes['class']);
5045
 
5046
        // Handle text being a renderable.
5047
        if ($this->text instanceof renderable) {
5048
            $data->text = $this->render($this->text);
5049
        }
5050
 
5051
        $data->showtext = (!$this->icon || $this->primary === false);
5052
 
5053
        $data->icon = null;
5054
        if ($this->icon) {
5055
            $icon = $this->icon;
5056
            if ($this->primary || !$this->actionmenu->will_be_enhanced()) {
5057
                $attributes['title'] = $data->text;
5058
            }
5059
            $data->icon = $icon ? $icon->export_for_pix() : null;
5060
        }
5061
 
5062
        $data->disabled = !empty($attributes['disabled']);
5063
        unset($attributes['disabled']);
5064
 
5065
        $data->attributes = array_map(function($key, $value) {
5066
            return [
5067
                'name' => $key,
5068
                'value' => $value
5069
            ];
5070
        }, array_keys($attributes), $attributes);
5071
 
5072
        return $data;
5073
    }
5074
}
5075
 
5076
/**
5077
 * A primary action menu action
5078
 *
5079
 * @package core
5080
 * @category output
5081
 * @copyright 2013 Sam Hemelryk
5082
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5083
 */
5084
class action_menu_link_primary extends action_menu_link {
5085
    /**
5086
     * Constructs the object.
5087
     *
5088
     * @param moodle_url $url
5089
     * @param pix_icon|null $icon
5090
     * @param string $text
5091
     * @param array $attributes
5092
     */
5093
    public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) {
5094
        parent::__construct($url, $icon, $text, true, $attributes);
5095
    }
5096
}
5097
 
5098
/**
5099
 * A secondary action menu action
5100
 *
5101
 * @package core
5102
 * @category output
5103
 * @copyright 2013 Sam Hemelryk
5104
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5105
 */
5106
class action_menu_link_secondary extends action_menu_link {
5107
    /**
5108
     * Constructs the object.
5109
     *
5110
     * @param moodle_url $url
5111
     * @param pix_icon|null $icon
5112
     * @param string $text
5113
     * @param array $attributes
5114
     */
5115
    public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) {
5116
        parent::__construct($url, $icon, $text, false, $attributes);
5117
    }
5118
}
5119
 
5120
/**
5121
 * Represents a set of preferences groups.
5122
 *
5123
 * @package core
5124
 * @category output
5125
 * @copyright 2015 Frédéric Massart - FMCorz.net
5126
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5127
 */
5128
class preferences_groups implements renderable {
5129
 
5130
    /**
5131
     * Array of preferences_group.
5132
     * @var array
5133
     */
5134
    public $groups;
5135
 
5136
    /**
5137
     * Constructor.
5138
     * @param array $groups of preferences_group
5139
     */
5140
    public function __construct($groups) {
5141
        $this->groups = $groups;
5142
    }
5143
 
5144
}
5145
 
5146
/**
5147
 * Represents a group of preferences page link.
5148
 *
5149
 * @package core
5150
 * @category output
5151
 * @copyright 2015 Frédéric Massart - FMCorz.net
5152
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5153
 */
5154
class preferences_group implements renderable {
5155
 
5156
    /**
5157
     * Title of the group.
5158
     * @var string
5159
     */
5160
    public $title;
5161
 
5162
    /**
5163
     * Array of navigation_node.
5164
     * @var array
5165
     */
5166
    public $nodes;
5167
 
5168
    /**
5169
     * Constructor.
5170
     * @param string $title The title.
5171
     * @param array $nodes of navigation_node.
5172
     */
5173
    public function __construct($title, $nodes) {
5174
        $this->title = $title;
5175
        $this->nodes = $nodes;
5176
    }
5177
}
5178
 
5179
/**
5180
 * Progress bar class.
5181
 *
5182
 * Manages the display of a progress bar.
5183
 *
5184
 * To use this class.
5185
 * - construct
5186
 * - call create (or use the 3rd param to the constructor)
5187
 * - call update or update_full() or update() repeatedly
5188
 *
5189
 * @copyright 2008 jamiesensei
5190
 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5191
 * @package core
5192
 * @category output
5193
 */
5194
class progress_bar implements renderable, templatable {
5195
    /** @var string html id */
5196
    private $html_id;
5197
    /** @var int total width */
5198
    private $width;
5199
    /** @var int last percentage printed */
5200
    private $percent = 0;
5201
    /** @var int time when last printed */
5202
    private $lastupdate = 0;
5203
    /** @var int when did we start printing this */
5204
    private $time_start = 0;
5205
 
5206
    /**
5207
     * Constructor
5208
     *
5209
     * Prints JS code if $autostart true.
5210
     *
5211
     * @param string $htmlid The container ID.
5212
     * @param int $width The suggested width.
5213
     * @param bool $autostart Whether to start the progress bar right away.
5214
     */
5215
    public function __construct($htmlid = '', $width = 500, $autostart = false) {
5216
        if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
5217
            debugging('progress_bar used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', DEBUG_DEVELOPER);
5218
        }
5219
 
5220
        if (!empty($htmlid)) {
5221
            $this->html_id  = $htmlid;
5222
        } else {
5223
            $this->html_id  = 'pbar_'.uniqid();
5224
        }
5225
 
5226
        $this->width = $width;
5227
 
5228
        if ($autostart) {
5229
            $this->create();
5230
        }
5231
    }
5232
 
5233
    /**
5234
     * Getter for ID
5235
     * @return string id
5236
     */
5237
    public function get_id(): string {
5238
        return $this->html_id;
5239
    }
5240
 
5241
    /**
5242
     * Create a new progress bar, this function will output html.
5243
     *
5244
     * @return void Echo's output
5245
     */
5246
    public function create() {
5247
        global $OUTPUT;
5248
 
5249
        $this->time_start = microtime(true);
5250
 
5251
        flush();
5252
        echo $OUTPUT->render($this);
5253
        flush();
5254
    }
5255
 
5256
    /**
5257
     * Update the progress bar.
5258
     *
5259
     * @param int $percent From 1-100.
5260
     * @param string $msg The message.
5261
     * @return void Echo's output
5262
     * @throws coding_exception
5263
     */
5264
    private function _update($percent, $msg) {
5265
        global $OUTPUT;
5266
 
5267
        if (empty($this->time_start)) {
5268
            throw new coding_exception('You must call create() (or use the $autostart ' .
5269
                'argument to the constructor) before you try updating the progress bar.');
5270
        }
5271
 
5272
        $estimate = $this->estimate($percent);
5273
 
5274
        if ($estimate === null) {
5275
            // Always do the first and last updates.
5276
        } else if ($estimate == 0) {
5277
            // Always do the last updates.
5278
        } else if ($this->lastupdate + 20 < time()) {
5279
            // We must update otherwise browser would time out.
5280
        } else if (round($this->percent, 2) === round($percent, 2)) {
5281
            // No significant change, no need to update anything.
5282
            return;
5283
        }
5284
 
5285
        $estimatemsg = '';
5286
        if ($estimate != 0 && is_numeric($estimate)) {
5287
            // Err on the conservative side and also avoid showing 'now' as the estimate.
5288
            $estimatemsg = format_time(ceil($estimate));
5289
        }
5290
 
5291
        $this->percent = $percent;
5292
        $this->lastupdate = microtime(true);
5293
 
5294
        echo $OUTPUT->render_progress_bar_update($this->html_id, $this->percent, $msg, $estimatemsg);
5295
        flush();
5296
    }
5297
 
5298
    /**
5299
     * Estimate how much time it is going to take.
5300
     *
5301
     * @param int $pt From 1-100.
5302
     * @return mixed Null (unknown), or int.
5303
     */
5304
    private function estimate($pt) {
5305
        if ($this->lastupdate == 0) {
5306
            return null;
5307
        }
5308
        if ($pt < 0.00001) {
5309
            return null; // We do not know yet how long it will take.
5310
        }
5311
        if ($pt > 99.99999) {
5312
            return 0; // Nearly done, right?
5313
        }
5314
        $consumed = microtime(true) - $this->time_start;
5315
        if ($consumed < 0.001) {
5316
            return null;
5317
        }
5318
 
5319
        return (100 - $pt) * ($consumed / $pt);
5320
    }
5321
 
5322
    /**
5323
     * Update progress bar according percent.
5324
     *
5325
     * @param int $percent From 1-100.
5326
     * @param string $msg The message needed to be shown.
5327
     */
5328
    public function update_full($percent, $msg) {
5329
        $percent = max(min($percent, 100), 0);
5330
        $this->_update($percent, $msg);
5331
    }
5332
 
5333
    /**
5334
     * Update progress bar according the number of tasks.
5335
     *
5336
     * @param int $cur Current task number.
5337
     * @param int $total Total task number.
5338
     * @param string $msg The message needed to be shown.
5339
     */
5340
    public function update($cur, $total, $msg) {
5341
        $percent = ($cur / $total) * 100;
5342
        $this->update_full($percent, $msg);
5343
    }
5344
 
5345
    /**
5346
     * Restart the progress bar.
5347
     */
5348
    public function restart() {
5349
        $this->percent    = 0;
5350
        $this->lastupdate = 0;
5351
        $this->time_start = 0;
5352
    }
5353
 
5354
    /**
5355
     * Export for template.
5356
     *
5357
     * @param  renderer_base $output The renderer.
5358
     * @return array
5359
     */
5360
    public function export_for_template(renderer_base $output) {
5361
        return [
5362
            'id' => $this->html_id,
5363
            'width' => $this->width,
5364
        ];
5365
    }
5366
}