Merge branch 'MDL-81457-main' of https://github.com/andrewnicols/moodle
[moodle.git] / lib / outputcomponents.php
blob50db844c528c3464b6d4268e8f39c29de92acdfb
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.
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/>.
17 /**
18 * Classes representing HTML elements, used by $OUTPUT methods
20 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
21 * for an overview.
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
29 use core\output\local\action_menu\subpanel;
31 defined('MOODLE_INTERNAL') || die();
33 /**
34 * Interface marking other classes as suitable for renderer_base::render()
36 * @copyright 2010 Petr Skoda (skodak) info@skodak.org
37 * @package core
38 * @category output
40 interface renderable {
41 // intentionally empty
44 /**
45 * Interface marking other classes having the ability to export their data for use by templates.
47 * @copyright 2015 Damyon Wiese
48 * @package core
49 * @category output
50 * @since 2.9
52 interface templatable {
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).
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
63 public function export_for_template(renderer_base $output);
66 /**
67 * Data structure representing a file picker.
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
75 class file_picker implements renderable {
77 /**
78 * @var stdClass An object containing options for the file picker
80 public $options;
82 /**
83 * Constructs a file picker object.
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)
95 * @param stdClass $options An object containing options for the file picker.
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
110 foreach ($defaults as $key=>$value) {
111 if (empty($options->$key)) {
112 $options->$key = $value;
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);
124 } else {
125 $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
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());
132 // initilise options, getting files in root path
133 $this->options = initialise_filepicker($options);
135 // copying other options
136 foreach ($options as $name=>$value) {
137 if (!isset($this->options->$name)) {
138 $this->options->$name = $value;
145 * Data structure representing a user picture.
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
153 class user_picture implements renderable {
155 * @var stdClass A user object with at least fields all columns specified
156 * in $fields array constant set.
158 public $user;
161 * @var int The course id. Used when constructing the link to the user's
162 * profile, page course id used if not specified.
164 public $courseid;
167 * @var bool Add course profile link to image
169 public $link = true;
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.
175 public $size = 35;
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.
181 public $alttext = true;
184 * @var bool Whether or not to open the link in a popup window.
186 public $popup = false;
189 * @var string Image class attribute
191 public $class = 'userpicture';
194 * @var bool Whether to be visible to screen readers.
196 public $visibletoscreenreaders = true;
199 * @var bool Whether to include the fullname in the user picture link.
201 public $includefullname = false;
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.
207 public $includetoken = false;
210 * User picture constructor.
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.
215 public function __construct(stdClass $user) {
216 global $DB;
218 if (empty($user->id)) {
219 throw new coding_exception('User id is required when printing user avatar image.');
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;
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);
242 * Returns a list of required user fields, useful when fetching required user info from db.
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.
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
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);
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);
267 // Maintain legacy behaviour where the field list was done with 'implode' and no spaces.
268 $selects = str_replace(', ', ',', $selects);
269 return $selects;
273 * Extract the aliased user fields from a given record
275 * Given a record that was previously obtained using {@link self::fields()} with aliases,
276 * this method extracts user related unaliased fields.
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
284 public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
286 if (empty($idalias)) {
287 $idalias = 'id';
290 $return = new stdClass();
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};
297 } else {
298 if (property_exists($record, $fieldprefix.$field)) {
299 $return->{$field} = $record->{$fieldprefix.$field};
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;
309 $return->{$e} = $record->{$fieldprefix.$e};
313 return $return;
317 * Works out the URL for the users picture.
319 * This method is recommended as it avoids costly redirects of user pictures
320 * if requests are made for non-existent files etc.
322 * @param moodle_page $page
323 * @param renderer_base $renderer
324 * @return moodle_url
326 public function get_url(moodle_page $page, renderer_base $renderer = null) {
327 global $CFG;
329 if (is_null($renderer)) {
330 $renderer = $page->get_renderer('core');
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;
352 $defaulturl = $renderer->image_url('u/'.$filename); // default image
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;
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;
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;
379 $contextid = $context->id;
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.'/';
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;
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;
402 // Hash the users email address
403 $md5 = md5(strtolower(trim($this->user->email)));
404 // Build a gravatar URL with what we know.
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';
414 } else {
415 $gravatardefault = $CFG->gravatardefaulturl;
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));
427 return $defaulturl;
432 * Data structure representing a help icon.
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
440 class help_icon implements renderable, templatable {
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.
447 public $identifier;
450 * @var string Component name, the same as in get_string()
452 public $component;
455 * @var string Extra descriptive text next to the icon
457 public $linktext = null;
460 * @var mixed An object, string or number that can be used within translation strings
462 public $a = null;
465 * Constructor
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
474 public function __construct($identifier, $component, $a = null) {
475 $this->identifier = $identifier;
476 $this->component = $component;
477 $this->a = $a;
481 * Verifies that both help strings exists, shows debug warnings if not
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]");
488 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
489 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
494 * Export this data so it can be used as the context for a mustache template.
496 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
497 * @return stdClass
499 public function export_for_template(renderer_base $output) {
500 global $CFG;
502 $title = get_string($this->identifier, $this->component, $this->a);
504 if (empty($this->linktext)) {
505 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
506 } else {
507 $alt = get_string('helpwiththis');
510 $data = get_formatted_help_string($this->identifier, $this->component, false, $this->a);
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"));
517 $options = [
518 'component' => $this->component,
519 'identifier' => $this->identifier,
520 'lang' => current_language()
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;
528 $data->url = (new moodle_url('/help.php', $options))->out(false);
529 $data->ltr = !right_to_left();
530 return $data;
536 * Data structure representing an icon font.
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
543 class pix_icon_font implements templatable {
546 * @var pix_icon $pixicon The original icon.
548 private $pixicon = null;
551 * @var string $key The mapped key.
553 private $key;
556 * @var bool $mapped The icon could not be mapped.
558 private $mapped;
561 * Constructor
563 * @param pix_icon $pixicon The original icon
565 public function __construct(pix_icon $pixicon) {
566 global $PAGE;
568 $this->pixicon = $pixicon;
569 $this->mapped = false;
570 $iconsystem = \core\output\icon_system::instance();
572 $this->key = $iconsystem->remap_icon_name($pixicon->pix, $pixicon->component);
573 if (!empty($this->key)) {
574 $this->mapped = true;
579 * Return true if this pix_icon was successfully mapped to an icon font.
581 * @return bool
583 public function is_mapped() {
584 return $this->mapped;
588 * Export this data so it can be used as the context for a mustache template.
590 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
591 * @return array
593 public function export_for_template(renderer_base $output) {
595 $pixdata = $this->pixicon->export_for_template($output);
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;
602 $data = array(
603 'extraclasses' => $pixdata['extraclasses'],
604 'title' => $title,
605 'alt' => $alt,
606 'key' => $this->key
609 return $data;
614 * Data structure representing an icon subtype.
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
621 class pix_icon_fontawesome extends pix_icon_font {
626 * Data structure representing an icon.
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
634 class pix_icon implements renderable, templatable {
637 * @var string The icon name
639 var $pix;
642 * @var string The component the icon belongs to.
644 var $component;
647 * @var array An array of attributes to use on the icon
649 var $attributes = array();
652 * Constructor
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
659 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
660 global $PAGE;
662 $this->pix = $pix;
663 $this->component = $component;
664 $this->attributes = (array)$attributes;
666 if (empty($this->attributes['class'])) {
667 $this->attributes['class'] = '';
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';
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;
679 // If there is no title, set it to the attribute.
680 if (!isset($this->attributes['title'])) {
681 $this->attributes['title'] = $this->attributes['alt'];
683 } else {
684 unset($this->attributes['alt']);
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']);
693 // Hide icons from screen readers that have no alt.
694 if (empty($this->attributes['alt'])) {
695 $this->attributes['aria-hidden'] = 'true';
700 * Export this data so it can be used as the context for a mustache template.
702 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
703 * @return array
705 public function export_for_template(renderer_base $output) {
706 $attributes = $this->attributes;
707 $extraclasses = '';
709 foreach ($attributes as $key => $item) {
710 if ($key == 'class') {
711 $extraclasses = $item;
712 unset($attributes[$key]);
713 break;
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);
722 $title = isset($attributes['title']) ? $attributes['title'] : '';
723 if (empty($title)) {
724 $title = isset($attributes['alt']) ? $attributes['alt'] : '';
726 $data = array(
727 'attributes' => $templatecontext,
728 'extraclasses' => $extraclasses
731 return $data;
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.
738 * @return array
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'] : '';
745 return [
746 'key' => $this->pix,
747 'component' => $this->component,
748 'title' => (string) $title,
754 * Data structure representing an activity icon.
756 * The difference is that activity icons will always render with the standard icon system (no font icons).
758 * @copyright 2017 Damyon Wiese
759 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
760 * @package core
762 class image_icon extends pix_icon {
766 * Data structure representing an emoticon image
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
774 class pix_emoticon extends pix_icon implements renderable {
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
783 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
784 if (empty($attributes['class'])) {
785 $attributes['class'] = 'emoticon';
787 parent::__construct($pix, $alt, $component, $attributes);
792 * Data structure representing a simple form with only one button.
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
800 class single_button implements renderable {
803 * Possible button types. From boostrap.
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
815 * Possible button types - Primary.
817 const BUTTON_PRIMARY = 'primary';
819 * Possible button types - Secondary.
821 const BUTTON_SECONDARY = 'secondary';
823 * Possible button types - Danger.
825 const BUTTON_DANGER = 'danger';
827 * Possible button types - Success.
829 const BUTTON_SUCCESS = 'success';
831 * Possible button types - Warning.
833 const BUTTON_WARNING = 'warning';
835 * Possible button types - Info.
837 const BUTTON_INFO = 'info';
840 * @var moodle_url Target url
842 public $url;
845 * @var string Button label
847 public $label;
850 * @var string Form submit method post or get
852 public $method = 'post';
855 * @var string Wrapping div class
857 public $class = 'singlebutton';
860 * @var string Type of button (from defined types). Used for styling.
862 protected $type;
865 * @var bool True if button is primary button. Used for styling.
866 * @deprecated since Moodle 4.2
868 private $primary = false;
871 * @var bool True if button disabled, false if normal
873 public $disabled = false;
876 * @var string Button tooltip
878 public $tooltip = null;
881 * @var string Form id
883 public $formid;
886 * @var array List of attached actions
888 public $actions = array();
891 * @var array $params URL Params
893 public $params;
896 * @var string Action id
898 public $actionid;
901 * @var array
903 protected $attributes = [];
906 * Constructor
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
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;
921 $this->url = clone($url);
922 $this->label = $label;
923 $this->method = $method;
924 $this->type = $type;
925 $this->attributes = $attributes;
929 * Shortcut for adding a JS confirm dialog when the button is clicked.
930 * The message must be a yes/no question.
932 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
934 public function add_confirm_action($confirmmessage) {
935 $this->add_action(new confirm_action($confirmmessage));
939 * Add action to the button.
940 * @param component_action $action
942 public function add_action(component_action $action) {
943 $this->actions[] = $action;
947 * Sets an attribute for the HTML button tag.
949 * @param string $name The attribute name
950 * @param mixed $value The value
951 * @return null
953 public function set_attribute($name, $value) {
954 $this->attributes[$name] = $value;
958 * Magic setter method.
960 * This method manages access to some properties and will display deprecation message when accessing 'primary' property.
962 * @param string $name
963 * @param mixed $value
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;
981 * Magic method getter.
983 * This method manages access to some properties and will display deprecation message when accessing 'primary' property.
985 * @param string $name
986 * @return mixed
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;
1001 * Export data.
1003 * @param renderer_base $output Renderer.
1004 * @return stdClass
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();
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];
1024 // Form parameters.
1025 $actionurl = new moodle_url($this->url);
1026 if ($this->method === 'post') {
1027 $actionurl->param('sesskey', sesskey());
1029 $data->params = $actionurl->export_params_for_template();
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);
1038 return $data;
1044 * Simple form with just one select field that gets submitted automatically.
1046 * If JS not enabled small go button is printed too.
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
1054 class single_select implements renderable, templatable {
1057 * @var moodle_url Target url - includes hidden fields
1059 var $url;
1062 * @var string Name of the select element.
1064 var $name;
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')))
1072 var $options;
1075 * @var string Selected option
1077 var $selected;
1080 * @var array Nothing selected
1082 var $nothing;
1085 * @var array Extra select field attributes
1087 var $attributes = array();
1090 * @var string Button label
1092 var $label = '';
1095 * @var array Button label's attributes
1097 var $labelattributes = array();
1100 * @var string Form submit method post or get
1102 var $method = 'get';
1105 * @var string Wrapping div class
1107 var $class = 'singleselect';
1110 * @var bool True if button disabled, false if normal
1112 var $disabled = false;
1115 * @var string Button tooltip
1117 var $tooltip = null;
1120 * @var string Form id
1122 var $formid = null;
1125 * @var help_icon The help icon for this element.
1127 var $helpicon = null;
1129 /** @var component_action[] component action. */
1130 public $actions = [];
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
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;
1151 * Shortcut for adding a JS confirm dialog when the button is clicked.
1152 * The message must be a yes/no question.
1154 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
1156 public function add_confirm_action($confirmmessage) {
1157 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
1161 * Add action to the button.
1163 * @param component_action $action
1165 public function add_action(component_action $action) {
1166 $this->actions[] = $action;
1170 * Adds help icon.
1172 * @deprecated since Moodle 2.0
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().');
1179 * Adds help icon.
1181 * @param string $identifier The keyword that defines a help page
1182 * @param string $component
1184 public function set_help_icon($identifier, $component = 'moodle') {
1185 $this->helpicon = new help_icon($identifier, $component);
1189 * Sets select's label
1191 * @param string $label
1192 * @param array $attributes (optional)
1194 public function set_label($label, $attributes = array()) {
1195 $this->label = $label;
1196 $this->labelattributes = $attributes;
1201 * Export data.
1203 * @param renderer_base $output Renderer.
1204 * @return stdClass
1206 public function export_for_template(renderer_base $output) {
1207 $attributes = $this->attributes;
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');
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']);
1228 // Map the attributes.
1229 $data->attributes = array_map(function($key) use ($attributes) {
1230 return ['name' => $key, 'value' => $attributes[$key]];
1231 }, array_keys($attributes));
1233 // Form parameters.
1234 $actionurl = new moodle_url($this->url);
1235 if ($this->method === 'post') {
1236 $actionurl->param('sesskey', sesskey());
1238 $data->params = $actionurl->export_params_for_template();
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;
1253 $hasnothing = true;
1254 $nothingkey = key($this->nothing);
1256 if ($hasnothing) {
1257 $options = $nothing + $this->options;
1258 } else {
1259 $options = $this->options;
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),
1273 if ($hasnothing && $nothingkey === $optvalue) {
1274 $option['ignore'] = 'data-ignore';
1277 $sublist[] = $option;
1279 $data->options[] = [
1280 'name' => $optgroupname,
1281 'optgroup' => true,
1282 'options' => $sublist
1285 } else {
1286 $option = [
1287 'value' => $value,
1288 'name' => $options[$value],
1289 'selected' => strval($this->selected) === strval($value),
1290 'optgroup' => false
1293 if ($hasnothing && $nothingkey === $value) {
1294 $option['ignore'] = 'data-ignore';
1297 $data->options[] = $option;
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];
1310 // Help icon.
1311 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1313 return $data;
1318 * Simple URL selection widget description.
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
1326 class url_select implements renderable, templatable {
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')))
1333 var $urls;
1336 * @var string Selected option
1338 var $selected;
1341 * @var array Nothing selected
1343 var $nothing;
1346 * @var array Extra select field attributes
1348 var $attributes = array();
1351 * @var string Button label
1353 var $label = '';
1356 * @var array Button label's attributes
1358 var $labelattributes = array();
1361 * @var string Wrapping div class
1363 var $class = 'urlselect';
1366 * @var bool True if button disabled, false if normal
1368 var $disabled = false;
1371 * @var string Button tooltip
1373 var $tooltip = null;
1376 * @var string Form id
1378 var $formid = null;
1381 * @var help_icon The help icon for this element.
1383 var $helpicon = null;
1386 * @var string If set, makes button visible with given name for button
1388 var $showbutton = null;
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')
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;
1408 * Adds help icon.
1410 * @deprecated since Moodle 2.0
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().');
1417 * Adds help icon.
1419 * @param string $identifier The keyword that defines a help page
1420 * @param string $component
1422 public function set_help_icon($identifier, $component = 'moodle') {
1423 $this->helpicon = new help_icon($identifier, $component);
1427 * Sets select's label
1429 * @param string $label
1430 * @param array $attributes (optional)
1432 public function set_label($label, $attributes = array()) {
1433 $this->label = $label;
1434 $this->labelattributes = $attributes;
1438 * Clean a URL.
1440 * @param string $value The URL.
1441 * @return string The cleaned URL.
1443 protected function clean_url($value) {
1444 global $CFG;
1446 if (empty($value)) {
1447 // Nothing.
1449 } else if (strpos($value, $CFG->wwwroot . '/') === 0) {
1450 $value = str_replace($CFG->wwwroot, '', $value);
1452 } else if (strpos($value, '/') !== 0) {
1453 debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER);
1456 return $value;
1460 * Flatten the options for Mustache.
1462 * This also cleans the URLs.
1464 * @param array $options The options.
1465 * @param array $nothing The nothing option.
1466 * @return array
1468 protected function flatten_options($options, $nothing) {
1469 $flattened = [];
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' => []
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,
1491 } else {
1492 $cleanedvalue = $this->clean_url($value);
1493 $flattened[$cleanedvalue] = [
1494 'name' => $option,
1495 'value' => $cleanedvalue,
1496 'selected' => $this->selected == $value,
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;
1509 // Make non-associative array.
1510 foreach ($flattened as $key => $value) {
1511 if (!empty($value['options'])) {
1512 $flattened[$key]['options'] = array_values($value['options']);
1515 $flattened = array_values($flattened);
1517 return $flattened;
1521 * Export for template.
1523 * @param renderer_base $output Renderer.
1524 * @return stdClass
1526 public function export_for_template(renderer_base $output) {
1527 $attributes = $this->attributes;
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);
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']);
1546 $data->showbutton = $this->showbutton;
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;
1560 $data->options = $this->flatten_options($this->urls, $nothing);
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];
1571 // Help icon.
1572 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1574 // Finally all the remaining attributes.
1575 $data->attributes = [];
1576 foreach ($attributes as $key => $value) {
1577 $data->attributes[] = ['name' => $key, 'value' => $value];
1580 return $data;
1585 * Data structure describing html link with special action attached.
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
1593 class action_link implements renderable {
1596 * @var moodle_url Href url
1598 public $url;
1601 * @var string Link text HTML fragment
1603 public $text;
1606 * @var array HTML attributes
1608 public $attributes;
1611 * @var array List of actions attached to link
1613 public $actions;
1616 * @var pix_icon Optional pix icon to render with the link
1618 public $icon;
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
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');
1638 $this->attributes = (array)$attributes;
1639 if ($action) {
1640 $this->add_action($action);
1642 $this->icon = $icon;
1646 * Add action to the link.
1648 * @param component_action $action
1650 public function add_action(component_action $action) {
1651 $this->actions[] = $action;
1655 * Adds a CSS class to this action link object
1656 * @param string $class
1658 public function add_class($class) {
1659 if (empty($this->attributes['class'])) {
1660 $this->attributes['class'] = $class;
1661 } else {
1662 $this->attributes['class'] .= ' ' . $class;
1667 * Returns true if the specified class has been added to this link.
1668 * @param string $class
1669 * @return bool
1671 public function has_class($class) {
1672 return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
1676 * Return the rendered HTML for the icon. Useful for rendering action links in a template.
1677 * @return string
1679 public function get_icon_html() {
1680 global $OUTPUT;
1681 if (!$this->icon) {
1682 return '';
1684 return $OUTPUT->render($this->icon);
1688 * Export for template.
1690 * @param renderer_base $output The renderer.
1691 * @return stdClass
1693 public function export_for_template(renderer_base $output) {
1694 $data = new stdClass();
1695 $attributes = $this->attributes;
1697 $data->id = $attributes['id'];
1698 unset($attributes['id']);
1700 $data->disabled = !empty($attributes['disabled']);
1701 unset($attributes['disabled']);
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']);
1709 $data->attributes = array_map(function($key, $value) {
1710 return [
1711 'name' => $key,
1712 'value' => $value
1714 }, array_keys($attributes), $attributes);
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);
1721 return $data;
1726 * Simple html output class
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
1734 class html_writer {
1737 * Outputs a tag with attributes and contents
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
1744 public static function tag($tagname, $contents, array $attributes = null) {
1745 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1749 * Outputs an opening tag with attributes
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
1755 public static function start_tag($tagname, array $attributes = null) {
1756 return '<' . $tagname . self::attributes($attributes) . '>';
1760 * Outputs a closing tag
1762 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1763 * @return string HTML fragment
1765 public static function end_tag($tagname) {
1766 return '</' . $tagname . '>';
1770 * Outputs an empty tag with attributes
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
1776 public static function empty_tag($tagname, array $attributes = null) {
1777 return '<' . $tagname . self::attributes($attributes) . ' />';
1781 * Outputs a tag, but only if the contents are not empty
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
1788 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1789 if ($contents === '' || is_null($contents)) {
1790 return '';
1792 return self::tag($tagname, $contents, $attributes);
1796 * Outputs a HTML attribute and value
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
1802 public static function attribute($name, $value) {
1803 if ($value instanceof moodle_url) {
1804 return ' ' . $name . '="' . $value->out() . '"';
1807 // special case, we do not want these in output
1808 if ($value === null) {
1809 return '';
1812 // no sloppy trimming here!
1813 return ' ' . $name . '="' . s($value) . '"';
1817 * Outputs a list of HTML attributes and values
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
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);
1829 return $output;
1833 * Generates a simple image tag with attributes.
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
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);
1853 return self::empty_tag('img', $attributes);
1857 * Generates random html element id.
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
1864 public static function random_id($base='random') {
1865 static $counter = 0;
1866 static $uniq;
1868 if (!isset($uniq)) {
1869 $uniq = uniqid();
1872 $counter++;
1873 return $base.$uniq.$counter;
1877 * Generates a simple html link
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
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);
1891 * Generates a simple checkbox with optional label
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
1901 public static function checkbox($name, $value, $checked = true, $label = '',
1902 array $attributes = null, array $labelattributes = null) {
1903 $attributes = (array) $attributes;
1904 $output = '';
1906 if ($label !== '' and !is_null($label)) {
1907 if (empty($attributes['id'])) {
1908 $attributes['id'] = self::random_id('checkbox_');
1911 $attributes['type'] = 'checkbox';
1912 $attributes['value'] = $value;
1913 $attributes['name'] = $name;
1914 $attributes['checked'] = $checked ? 'checked' : null;
1916 $output .= self::empty_tag('input', $attributes);
1918 if ($label !== '' and !is_null($label)) {
1919 $labelattributes = (array) $labelattributes;
1920 $labelattributes['for'] = $attributes['id'];
1921 $output .= self::tag('label', $label, $labelattributes);
1924 return $output;
1928 * Generates a simple select yes/no form field
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
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);
1941 * Generates a simple select form field
1943 * Note this function does HTML escaping on the optgroup labels, but not on the choice labels.
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
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');
1964 $options = $nothing + $options; // keep keys, do not override
1966 } else if (is_string($nothing) and $nothing !== '') {
1967 // BC
1968 $options = array(''=>$nothing) + $options;
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;
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;
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;
1992 $attributes['class'] = 'select custom-select ' . $attributes['class']; // Add 'select' selector always.
1994 $attributes['name'] = $name;
1996 if (!empty($attributes['disabled'])) {
1997 $attributes['disabled'] = 'disabled';
1998 } else {
1999 unset($attributes['disabled']);
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);
2011 return self::tag('select', $output, $attributes);
2015 * Returns HTML to display a select box option.
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
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';
2028 $attributes['value'] = $value;
2029 return self::tag('option', $label, $attributes);
2033 * Returns HTML to display a select box option group.
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.
2040 private static function select_optgroup($groupname, $options, array $selected) {
2041 if (empty($options)) {
2042 return '';
2044 $attributes = array('label'=>$groupname);
2045 $output = '';
2046 foreach ($options as $value=>$label) {
2047 $output .= self::select_option($label, $value, $selected);
2049 return self::tag('optgroup', $output, $attributes);
2053 * This is a shortcut for making an hour selector menu.
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
2064 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null, $timezone = 99) {
2065 global $OUTPUT;
2067 if (!$currenttime) {
2068 $currenttime = time();
2070 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2071 $currentdate = $calendartype->timestamp_to_date_array($currenttime, $timezone);
2073 $userdatetype = $type;
2074 $timeunits = array();
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);
2094 break;
2095 case 'minutes':
2096 if ($step != 1) {
2097 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
2100 for ($i=0; $i<=59; $i+=$step) {
2101 $timeunits[$i] = sprintf("%02d",$i);
2103 break;
2104 default:
2105 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
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
2119 }, array_keys($timeunits)),
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]
2129 }, array_keys($attributes));
2131 return $OUTPUT->render_from_template('core/select_time', $data);
2135 * Shortcut for quick making of lists
2137 * Note: 'list' is a reserved keyword ;-)
2139 * @param array $items
2140 * @param array $attributes
2141 * @param string $tag ul or ol
2142 * @return string
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";
2149 $output .= html_writer::end_tag($tag);
2150 return $output;
2154 * Returns hidden input fields created from url parameters.
2156 * @param moodle_url $url
2157 * @param array $exclude list of excluded parameters
2158 * @return string HTML fragment
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]);
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";
2172 return $output;
2176 * Generate a script tag containing the the specified code.
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.
2182 public static function script($jscode, $url=null) {
2183 if ($jscode) {
2184 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n") . "\n";
2186 } else if ($url) {
2187 return self::tag('script', '', ['src' => $url]) . "\n";
2189 } else {
2190 return '';
2195 * Renders HTML table
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.
2202 * @param html_table $table data to be rendered
2203 * @return string HTML code
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;
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;
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] = '';
2234 if (!empty($table->head)) {
2235 foreach ($table->head as $key => $val) {
2236 if (!isset($table->align[$key])) {
2237 $table->align[$key] = null;
2239 if (!isset($table->size[$key])) {
2240 $table->size[$key] = null;
2242 if (!isset($table->wrap[$key])) {
2243 $table->wrap[$key] = null;
2248 if (empty($table->attributes['class'])) {
2249 $table->attributes['class'] = 'generaltable';
2251 if (!empty($table->tablealign)) {
2252 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
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,
2264 $output = html_writer::start_tag('table', $attributes) . "\n";
2266 $countcols = 0;
2268 // Output a caption if present.
2269 if (!empty($table->caption)) {
2270 $captionattributes = array();
2271 if ($table->captionhide) {
2272 $captionattributes['class'] = 'accesshide';
2274 $output .= html_writer::tag(
2275 'caption',
2276 $table->caption,
2277 $captionattributes
2281 if (!empty($table->head)) {
2282 $countcols = count($table->head);
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);
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;
2298 if ($heading->header !== false) {
2299 $heading->header = true;
2302 $tagtype = 'td';
2303 if ($heading->header && (string)$heading->text != '') {
2304 $tagtype = 'th';
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;
2313 if ($key == $lastkey) {
2314 $heading->attributes['class'] .= ' lastcol';
2316 if (isset($table->colclasses[$key])) {
2317 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
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,
2325 if ($tagtype == 'th') {
2326 $attributes['scope'] = !empty($heading->scope) ? $heading->scope : 'col';
2329 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
2331 $output .= html_writer::end_tag('tr') . "\n";
2332 $output .= html_writer::end_tag('thead') . "\n";
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');
2343 if (!empty($table->data)) {
2344 $keys = array_keys($table->data);
2345 $lastrowkey = end($keys);
2346 $output .= html_writer::start_tag('tbody', array());
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();
2356 foreach ($row as $cell) {
2357 if (!($cell instanceof html_table_cell)) {
2358 $cell = new html_table_cell($cell);
2360 $newrow->cells[] = $cell;
2362 $row = $newrow;
2365 if (isset($table->rowclasses[$key])) {
2366 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
2369 if ($key == $lastrowkey) {
2370 $row->attributes['class'] .= ' lastrow';
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,
2379 $output .= html_writer::start_tag('tr', $trattributes) . "\n";
2380 $keys2 = array_keys($row->cells);
2381 $lastkey = end($keys2);
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)");
2390 if (!($cell instanceof html_table_cell)) {
2391 $mycell = new html_table_cell();
2392 $mycell->text = $cell;
2393 $cell = $mycell;
2396 if (($cell->header === true) && empty($cell->scope)) {
2397 $cell->scope = 'row';
2400 if (isset($table->colclasses[$key])) {
2401 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
2404 $cell->attributes['class'] .= ' cell c' . $key;
2405 if ($key == $lastkey) {
2406 $cell->attributes['class'] .= ' lastcol';
2407 $gotlastkey = true;
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,
2422 $tagtype = 'td';
2423 if ($cell->header === true) {
2424 $tagtype = 'th';
2426 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
2429 $output .= html_writer::end_tag('tr') . "\n";
2431 $output .= html_writer::end_tag('tbody') . "\n";
2433 $output .= html_writer::end_tag('table') . "\n";
2435 if ($table->responsive) {
2436 return self::div($output, 'table-responsive');
2439 return $output;
2443 * Renders form element label
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).
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.
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
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));
2467 $text = trim($text ?? '');
2468 $label = self::tag('label', $text, $attributes);
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 // }
2485 return $label;
2489 * Combines a class parameter with other attributes. Aids in code reduction
2490 * because the class parameter is very frequently used.
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.
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)
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;
2508 } else {
2509 $attributes = $classattribute;
2512 return $attributes;
2516 * Creates a <div> tag. (Shortcut function.)
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
2523 public static function div($content, $class = '', array $attributes = null) {
2524 return self::tag('div', $content, self::add_class($class, $attributes));
2528 * Starts a <div> tag. (Shortcut function.)
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
2534 public static function start_div($class = '', array $attributes = null) {
2535 return self::start_tag('div', self::add_class($class, $attributes));
2539 * Ends a <div> tag. (Shortcut function.)
2541 * @return string HTML code for close div tag
2543 public static function end_div() {
2544 return self::end_tag('div');
2548 * Creates a <span> tag. (Shortcut function.)
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
2555 public static function span($content, $class = '', array $attributes = null) {
2556 return self::tag('span', $content, self::add_class($class, $attributes));
2560 * Starts a <span> tag. (Shortcut function.)
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
2566 public static function start_span($class = '', array $attributes = null) {
2567 return self::start_tag('span', self::add_class($class, $attributes));
2571 * Ends a <span> tag. (Shortcut function.)
2573 * @return string HTML code for close span tag
2575 public static function end_span() {
2576 return self::end_tag('span');
2581 * Simple javascript output class
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
2589 class js_writer {
2592 * Returns javascript code calling the function
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
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 = '';
2606 $js = "$function($arguments);";
2608 if ($delay) {
2609 $delay = $delay * 1000; // in miliseconds
2610 $js = "setTimeout(function() { $js }, $delay);";
2612 return $js . "\n";
2616 * Special function which adds Y as first argument of function call.
2618 * @param string $function The function to call
2619 * @param array $extraarguments Any arguments to pass to it
2620 * @return string Some JS code
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';
2629 return "$function($arguments);\n";
2633 * Returns JavaScript code to initialise a new object
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
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);
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);";
2656 if ($delay) {
2657 $delay = $delay * 1000; // in miliseconds
2658 $js = "setTimeout(function() { $js }, $delay);";
2661 if (count($requirements) > 0) {
2662 $requirements = implode("', '", $requirements);
2663 $js = "Y.use('$requirements', function(Y){ $js });";
2665 return $js."\n";
2669 * Returns code setting value to variable
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
2676 public static function set_variable($name, $value, $usevar = true) {
2677 $output = '';
2679 if ($usevar) {
2680 if (strpos($name, '.')) {
2681 $output .= '';
2682 } else {
2683 $output .= 'var ';
2687 $output .= "$name = ".json_encode($value).";";
2689 return $output;
2693 * Writes event handler attaching code
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
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);
2708 return $output . ");\n";
2713 * Holds all the information required to render a <table> by {@link core_renderer::table()}
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);
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
2726 class html_table {
2729 * @var string Value to use for the id attribute of the table
2731 public $id = null;
2734 * @var array Attributes of HTML attributes for the <table> element
2736 public $attributes = array();
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.
2743 * Example of usage:
2744 * $t->head = array('Student', 'Grade');
2746 public $head;
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.
2753 * Example of usage:
2754 * $t->headspan = array(2,1);
2756 public $headspan;
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.
2764 * Examples of usage:
2765 * $t->align = array(null, 'right');
2766 * or
2767 * $t->align[1] = 'right';
2769 public $align;
2772 * @var array The value is used as CSS 'size' property.
2774 * Examples of usage:
2775 * $t->size = array('50%', '50%');
2776 * or
2777 * $t->size[1] = '120px';
2779 public $size;
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.
2786 * Example of usage:
2787 * $t->wrap = array(null, 'nowrap');
2789 public $wrap;
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.
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);
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);
2815 public $data = [];
2818 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2819 * @var string Width of the table, percentage of the page preferred.
2821 public $width = null;
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).
2827 public $tablealign = null;
2830 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2831 * @var int Padding on each cell, in pixels
2833 public $cellpadding = null;
2836 * @var int Spacing between cells, in pixels
2837 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2839 public $cellspacing = null;
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.
2845 * Example of usage:
2846 * $t->rowclasses[9] = 'tenth'
2848 public $rowclasses;
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.
2857 * Example of usage:
2858 * $t->colclasses = array(null, 'grade');
2860 public $colclasses;
2863 * @var string Description of the contents for screen readers.
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.
2869 * @deprecated since Moodle 3.9.
2871 public $summary;
2874 * @var string Caption for the table, typically a title.
2876 * Example of usage:
2877 * $t->caption = "TV Guide";
2879 public $caption;
2882 * @var bool Whether to hide the table's caption from sighted users.
2884 * Example of usage:
2885 * $t->caption = "TV Guide";
2886 * $t->captionhide = true;
2888 public $captionhide = false;
2890 /** @var bool Whether to make the table to be scrolled horizontally with ease. Make table responsive across all viewports. */
2891 public $responsive = true;
2893 /** @var string class name to add to this html table. */
2894 public $class;
2897 * Constructor
2899 public function __construct() {
2900 $this->attributes['class'] = '';
2905 * Component representing a table row.
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
2913 class html_table_row {
2916 * @var string Value to use for the id attribute of the row.
2918 public $id = null;
2921 * @var array Array of html_table_cell objects
2923 public $cells = array();
2926 * @var string Value to use for the style attribute of the table row
2928 public $style = null;
2931 * @var array Attributes of additional HTML attributes for the <tr> element
2933 public $attributes = array();
2936 * Constructor
2937 * @param array $cells
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);
2953 * Component representing a table cell.
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
2961 class html_table_cell {
2964 * @var string Value to use for the id attribute of the cell.
2966 public $id = null;
2969 * @var string The contents of the cell.
2971 public $text;
2974 * @var string Abbreviated version of the contents of the cell.
2976 public $abbr = null;
2979 * @var int Number of columns this cell should span.
2981 public $colspan = null;
2984 * @var int Number of rows this cell should span.
2986 public $rowspan = null;
2989 * @var string Defines a way to associate header cells and data cells in a table.
2991 public $scope = null;
2994 * @var bool Whether or not this cell is a header cell.
2996 public $header = null;
2999 * @var string Value to use for the style attribute of the table cell
3001 public $style = null;
3004 * @var array Attributes of additional HTML attributes for the <td> element
3006 public $attributes = array();
3009 * Constructs a table cell
3011 * @param string $text
3013 public function __construct($text = null) {
3014 $this->text = $text;
3015 $this->attributes['class'] = '';
3020 * Component representing a paging bar.
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
3028 class paging_bar implements renderable, templatable {
3031 * @var int The maximum number of pagelinks to display.
3033 public $maxdisplay = 18;
3036 * @var int The total number of entries to be pages through..
3038 public $totalcount;
3041 * @var int The page you are currently viewing.
3043 public $page;
3046 * @var int The number of entries that should be shown per page.
3048 public $perpage;
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.
3056 public $baseurl;
3059 * @var string This is the variable name that you use for the pagenumber in your
3060 * code (ie. 'tablepage', 'blogpage', etc)
3062 public $pagevar;
3065 * @var string A HTML link representing the "previous" page.
3067 public $previouslink = null;
3070 * @var string A HTML link representing the "next" page.
3072 public $nextlink = null;
3075 * @var string A HTML link representing the first page.
3077 public $firstlink = null;
3080 * @var string A HTML link representing the last page.
3082 public $lastlink = null;
3085 * @var array An array of strings. One of them is just a string: the current page
3087 public $pagelinks = array();
3090 * Constructor paging_bar with only the required params.
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
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;
3107 * Prepares the paging bar for output.
3109 * This method validates the arguments set up for the paging bar and then
3110 * produces fragments of HTML to assist display later on.
3112 * @param renderer_base $output
3113 * @param moodle_page $page
3114 * @param string $target
3115 * @throws coding_exception
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.');
3121 if (!isset($this->page) || is_null($this->page)) {
3122 throw new coding_exception('paging_bar requires a page value.');
3124 if (empty($this->perpage)) {
3125 throw new coding_exception('paging_bar requires a perpage value.');
3127 if (empty($this->baseurl)) {
3128 throw new coding_exception('paging_bar requires a baseurl value.');
3131 if ($this->totalcount > $this->perpage) {
3132 $pagenum = $this->page - 1;
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'));
3138 if ($this->perpage > 0) {
3139 $lastpage = ceil($this->totalcount / $this->perpage);
3140 } else {
3141 $lastpage = 1;
3144 if ($this->page > round(($this->maxdisplay/3)*2)) {
3145 $currpage = $this->page - round($this->maxdisplay/3);
3147 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
3148 } else {
3149 $currpage = 0;
3152 $displaycount = $displaypage = 0;
3154 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3155 $displaypage = $currpage + 1;
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;
3164 $displaycount++;
3165 $currpage++;
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'));
3173 $pagenum = $this->page + 1;
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'));
3182 * Export for template.
3184 * @param renderer_base $output The renderer.
3185 * @return stdClass
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;
3198 if (!$data->haspages) {
3199 return $data;
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)
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)
3218 $lastpage = 1;
3219 if ($this->perpage > 0) {
3220 $lastpage = ceil($this->totalcount / $this->perpage);
3223 $displaycount = 0;
3224 $displaypage = 0;
3225 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3226 $displaypage = $currpage + 1;
3228 $iscurrent = $this->page == $currpage;
3229 $link = new moodle_url($this->baseurl, [$this->pagevar => $currpage]);
3231 $data->pages[] = [
3232 'page' => $displaypage,
3233 'active' => $iscurrent,
3234 'url' => $iscurrent ? null : $link->out(false)
3237 $displaycount++;
3238 $currpage++;
3241 if ($currpage < $lastpage) {
3242 $data->last = [
3243 'page' => $lastpage,
3244 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $lastpage - 1]))->out(false)
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)
3255 return $data;
3260 * Component representing initials bar.
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
3268 class initials_bar implements renderable, templatable {
3271 * @var string Currently selected letter.
3273 public $current;
3276 * @var string Class name to add to this initial bar.
3278 public $class;
3281 * @var string The name to put in front of this initial bar.
3283 public $title;
3286 * @var string URL parameter name for this initial.
3288 public $urlvar;
3291 * @var moodle_url URL object.
3293 public $url;
3296 * @var array An array of letters in the alphabet.
3298 public $alpha;
3301 * @var bool Omit links if we are doing a mini render.
3303 public $minirender;
3306 * Constructor initials_bar with only the required params.
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.
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;
3327 * Export for template.
3329 * @param renderer_base $output The renderer.
3330 * @return stdClass
3332 public function export_for_template(renderer_base $output) {
3333 $data = new stdClass();
3335 if ($this->alpha == null) {
3336 $this->alpha = explode(',', get_string('alphabet', 'langconfig'));
3339 if ($this->current == 'all') {
3340 $this->current = '';
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);
3356 $groupsizelimit = 0;
3357 $groupnumber = 0;
3358 foreach ($this->alpha as $letter) {
3359 if ($groupsizelimit++ > 0 && $groupsizelimit % $groupsize == 1) {
3360 $groupnumber++;
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;
3369 if ($letter == $this->current) {
3370 $groupletter->selected = $this->current;
3372 if (!isset($data->group[$groupnumber])) {
3373 $data->group[$groupnumber] = new stdClass();
3375 $data->group[$groupnumber]->letter[] = $groupletter;
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';
3385 $data->current = $this->current;
3386 $data->all = get_string('all');
3388 return $data;
3393 * This class represents how a block appears on a page.
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.
3398 * contents should probably be generated using a moodle_block_..._renderer.
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.
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
3409 class block_contents {
3411 /** Used when the block cannot be collapsed **/
3412 const NOT_HIDEABLE = 0;
3414 /** Used when the block can be collapsed but currently is not **/
3415 const VISIBLE = 1;
3417 /** Used when the block has been collapsed **/
3418 const HIDDEN = 2;
3421 * @var int Used to set $skipid.
3423 protected static $idcounter = 1;
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.
3431 public $skipid;
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.
3437 public $blockinstanceid = 0;
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.
3444 public $blockpositionid = 0;
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.
3450 public $attributes;
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.
3457 public $title = '';
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.
3463 public $arialabel = '';
3466 * @var string HTML for the content
3468 public $content = '';
3471 * @var array An alternative to $content, it you want a list of things with optional icons.
3473 public $footer = '';
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.'
3480 public $annotation = '';
3483 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
3484 * the user can toggle whether this block is visible.
3486 public $collapsible = self::NOT_HIDEABLE;
3489 * Set this to true if the block is dockable.
3490 * @var bool
3492 public $dockable = false;
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.
3499 public $controls = array();
3503 * Create new instance of block content
3504 * @param array $attributes
3506 public function __construct(array $attributes = null) {
3507 $this->skipid = self::$idcounter;
3508 self::$idcounter += 1;
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');
3520 * Add html class to block
3522 * @param string $class
3524 public function add_class($class) {
3525 $this->attributes['class'] .= ' '.$class;
3529 * Check if the block is a fake block.
3531 * @return boolean
3533 public function is_fake() {
3534 return isset($this->attributes['data-block']) && $this->attributes['data-block'] == '_fake';
3540 * This class represents a target for where a block can go when it is being moved.
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.
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
3552 class block_move_target {
3555 * @var moodle_url Move url
3557 public $url;
3560 * Constructor
3561 * @param moodle_url $url
3563 public function __construct(moodle_url $url) {
3564 $this->url = $url;
3569 * Custom menu item
3571 * This class is used to represent one item within a custom menu that may or may
3572 * not have children.
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
3580 class custom_menu_item implements renderable, templatable {
3583 * @var string The text to show for the item
3585 protected $text;
3588 * @var moodle_url The link to give the icon if it has no children
3590 protected $url;
3593 * @var string A title to apply to the item. By default the text
3595 protected $title;
3598 * @var int A sort order for the item, not necessary if you order things in
3599 * the CFG var.
3601 protected $sort;
3604 * @var custom_menu_item A reference to the parent for this item or NULL if
3605 * it is a top level item
3607 protected $parent;
3610 * @var array A array in which to store children this item has.
3612 protected $children = array();
3615 * @var int A reference to the sort var of the last child that was added
3617 protected $lastsort = 0;
3619 /** @var array Array of other HTML attributes for the custom menu item. */
3620 protected $attributes = [];
3623 * Constructs the new custom menu item
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.
3633 public function __construct($text, moodle_url $url = null, $title = null, $sort = null, custom_menu_item $parent = null,
3634 array $attributes = []) {
3636 // Use class setter method for text to ensure it's always a string type.
3637 $this->set_text($text);
3639 $this->url = $url;
3640 $this->title = $title;
3641 $this->sort = (int)$sort;
3642 $this->parent = $parent;
3643 $this->attributes = $attributes;
3647 * Adds a custom menu item as a child of this node given its properties.
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
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;
3661 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this, $attributes);
3662 $this->lastsort = (int)$sort;
3663 return $this->children[$key];
3667 * Removes a custom menu item that is a child or descendant to the current menu.
3669 * Returns true if child was found and removed.
3671 * @param custom_menu_item $menuitem
3672 * @return bool
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;
3687 return $removed;
3691 * Returns the text for this item
3692 * @return string
3694 public function get_text() {
3695 return $this->text;
3699 * Returns the url for this item
3700 * @return moodle_url
3702 public function get_url() {
3703 return $this->url;
3707 * Returns the title for this item
3708 * @return string
3710 public function get_title() {
3711 return $this->title;
3715 * Sorts and returns the children for this item
3716 * @return array
3718 public function get_children() {
3719 $this->sort();
3720 return $this->children;
3724 * Gets the sort order for this child
3725 * @return int
3727 public function get_sort_order() {
3728 return $this->sort;
3732 * Gets the parent this child belong to
3733 * @return custom_menu_item
3735 public function get_parent() {
3736 return $this->parent;
3740 * Sorts the children this item has
3742 public function sort() {
3743 usort($this->children, array('custom_menu','sort_custom_menu_items'));
3747 * Returns true if this item has any children
3748 * @return bool
3750 public function has_children() {
3751 return (count($this->children) > 0);
3755 * Sets the text for the node
3756 * @param string $text
3758 public function set_text($text) {
3759 $this->text = (string)$text;
3763 * Sets the title for the node
3764 * @param string $title
3766 public function set_title($title) {
3767 $this->title = (string)$title;
3771 * Sets the url for the node
3772 * @param moodle_url $url
3774 public function set_url(moodle_url $url) {
3775 $this->url = $url;
3779 * Export this data so it can be used as the context for a mustache template.
3781 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
3782 * @return stdClass
3784 public function export_for_template(renderer_base $output) {
3785 $syscontext = context_system::instance();
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);
3796 $context->sort = $this->sort;
3797 if (!empty($this->attributes)) {
3798 $context->attributes = $this->attributes;
3800 $context->children = array();
3801 if (preg_match("/^#+$/", $this->text)) {
3802 $context->divider = true;
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);
3810 return $context;
3815 * Custom menu class
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.
3821 * To configure the custom menu:
3822 * Settings: Administration > Appearance > Advanced theme settings
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
3830 class custom_menu extends custom_menu_item {
3833 * @var string The language we should render for, null disables multilang support.
3835 protected $currentlanguage = null;
3838 * Creates the custom menu
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
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));
3852 * Overrides the children of this custom menu. Useful when getting children
3853 * from $CFG->custommenuitems
3855 * @param array $children
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;
3867 * Converts a string into a structured array of custom_menu_items which can
3868 * then be added to a custom menu.
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.
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
3887 * @static
3888 * @param string $text the menu items definition
3889 * @param string $language the language code, null disables multilang support
3890 * @return array
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;
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;
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);
3933 break;
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--;
3945 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1);
3946 $lastdepth++;
3947 if (!$itemvisible) {
3948 $hiddenitems[] = $lastitem;
3951 foreach ($hiddenitems as $item) {
3952 $item->parent->remove_child($item);
3954 return $root->get_children();
3958 * Sorts two custom menu items
3960 * This function is designed to be used with the usort method
3961 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
3963 * @static
3964 * @param custom_menu_item $itema
3965 * @param custom_menu_item $itemb
3966 * @return int
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;
3974 return ($itema > $itemb) ? +1 : -1;
3979 * Stores one tab
3981 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3982 * @package core
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;
4007 * Constructor
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
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;
4024 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
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
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;
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;
4043 return false;
4047 * Travels through tree and finds a tab with specified id
4049 * @param string $id
4050 * @return tabtree|null
4052 public function find($id) {
4053 if ((string)$this->id === (string)$id) {
4054 return $this;
4056 foreach ($this->subtree as $tab) {
4057 if ($obj = $tab->find($id)) {
4058 return $obj;
4061 return null;
4065 * Allows to mark each tab's level in the tree before rendering.
4067 * @param int $level
4069 protected function set_level($level) {
4070 $this->level = $level;
4071 foreach ($this->subtree as $tab) {
4072 $tab->set_level($level + 1);
4077 * Export for template.
4079 * @param renderer_base $output Renderer.
4080 * @return object
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;
4088 $active = $this->activated || $this->selected;
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,
4104 * Renderable for the main page header.
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
4112 class context_header implements renderable {
4115 * @var string $heading Main heading.
4117 public $heading;
4119 * @var int $headinglevel Main heading 'h' tag level.
4121 public $headinglevel;
4123 * @var string|null $imagedata HTML code for the picture in the page header.
4125 public $imagedata;
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.
4134 public $additionalbuttons;
4136 * @var string $prefix A string that is before the title.
4138 public $prefix;
4141 * Constructor.
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.
4149 public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null, $prefix = null) {
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();
4159 $this->prefix = $prefix;
4163 * Adds an array element for a formatted image.
4165 protected function format_button_images() {
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'];
4183 if (isset($button['linkattributes']['class'])) {
4184 $class = $button['linkattributes']['class'] . ' btn';
4185 } else {
4186 $class = 'btn';
4188 // Add the bootstrap 'btn' class for formatting.
4189 $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
4190 array('class' => $class));
4196 * Stores tabs list
4198 * Example how to print a single line tabs:
4199 * $rows = array(
4200 * new tabobject(...),
4201 * new tabobject(...)
4202 * );
4203 * echo $OUTPUT->tabtree($rows, $selectedid);
4205 * Multiple row tabs may not look good on some devices but if you want to use them
4206 * you can specify ->subtree for the active tabobject.
4208 * @copyright 2013 Marina Glancy
4209 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4210 * @since Moodle 2.5
4211 * @package core
4212 * @category output
4214 class tabtree extends tabobject {
4216 * Constuctor
4218 * It is highly recommended to call constructor when list of tabs is already
4219 * populated, this way you ensure that selected and inactive tabs are located
4220 * and attribute level is set correctly.
4222 * @param array $tabs array of tabs, each of them may have it's own ->subtree
4223 * @param string|null $selected which tab to mark as selected, all parent tabs will
4224 * automatically be marked as activated
4225 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4226 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
4228 public function __construct($tabs, $selected = null, $inactive = null) {
4229 $this->subtree = $tabs;
4230 if ($selected !== null) {
4231 $this->set_selected($selected);
4233 if ($inactive !== null) {
4234 if (is_array($inactive)) {
4235 foreach ($inactive as $id) {
4236 if ($tab = $this->find($id)) {
4237 $tab->inactive = true;
4240 } else if ($tab = $this->find($inactive)) {
4241 $tab->inactive = true;
4244 $this->set_level(0);
4248 * Export for template.
4250 * @param renderer_base $output Renderer.
4251 * @return object
4253 public function export_for_template(renderer_base $output) {
4254 $tabs = [];
4255 $secondrow = false;
4257 foreach ($this->subtree as $tab) {
4258 $tabs[] = $tab->export_for_template($output);
4259 if (!empty($tab->subtree) && ($tab->level == 0 || $tab->selected || $tab->activated)) {
4260 $secondrow = new tabtree($tab->subtree);
4264 return (object) [
4265 'tabs' => $tabs,
4266 'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false
4272 * An action menu.
4274 * This action menu component takes a series of primary and secondary actions.
4275 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
4276 * down menu.
4278 * @package core
4279 * @category output
4280 * @copyright 2013 Sam Hemelryk
4281 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4283 class action_menu implements renderable, templatable {
4286 * Top right alignment.
4288 const TL = 1;
4291 * Top right alignment.
4293 const TR = 2;
4296 * Top right alignment.
4298 const BL = 3;
4301 * Top right alignment.
4303 const BR = 4;
4306 * The instance number. This is unique to this instance of the action menu.
4307 * @var int
4309 protected $instance = 0;
4312 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
4313 * @var array
4315 protected $primaryactions = array();
4318 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
4319 * @var array
4321 protected $secondaryactions = array();
4324 * An array of attributes added to the container of the action menu.
4325 * Initialised with defaults during construction.
4326 * @var array
4328 public $attributes = array();
4330 * An array of attributes added to the container of the primary actions.
4331 * Initialised with defaults during construction.
4332 * @var array
4334 public $attributesprimary = array();
4336 * An array of attributes added to the container of the secondary actions.
4337 * Initialised with defaults during construction.
4338 * @var array
4340 public $attributessecondary = array();
4343 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
4344 * @var array
4346 public $actiontext = null;
4349 * The string to use for the accessible label for the menu.
4350 * @var array
4352 public $actionlabel = null;
4355 * An icon to use for the toggling the secondary menu (dropdown).
4356 * @var pix_icon
4358 public $actionicon;
4361 * Any text to use for the toggling the secondary menu (dropdown).
4362 * @var string
4364 public $menutrigger = '';
4367 * An array of attributes added to the trigger element of the secondary menu.
4368 * @var array
4370 public $triggerattributes = [];
4373 * Any extra classes for toggling to the secondary menu.
4374 * @var string
4376 public $triggerextraclasses = '';
4379 * Place the action menu before all other actions.
4380 * @var bool
4382 public $prioritise = false;
4385 * Dropdown menu alignment class.
4386 * @var string
4388 public $dropdownalignment = '';
4391 * Constructs the action menu with the given items.
4393 * @param array $actions An array of actions (action_menu_link|pix_icon|string).
4395 public function __construct(array $actions = array()) {
4396 static $initialised = 0;
4397 $this->instance = $initialised;
4398 $initialised++;
4400 $this->attributes = array(
4401 'id' => 'action-menu-'.$this->instance,
4402 'class' => 'moodle-actionmenu',
4403 'data-enhance' => 'moodle-core-actionmenu'
4405 $this->attributesprimary = array(
4406 'id' => 'action-menu-'.$this->instance.'-menubar',
4407 'class' => 'menubar',
4409 $this->attributessecondary = array(
4410 'id' => 'action-menu-'.$this->instance.'-menu',
4411 'class' => 'menu',
4412 'data-rel' => 'menu-content',
4413 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
4414 'role' => 'menu'
4416 $this->dropdownalignment = 'dropdown-menu-right';
4417 foreach ($actions as $action) {
4418 $this->add($action);
4423 * Sets the label for the menu trigger.
4425 * @param string $label The text
4427 public function set_action_label($label) {
4428 $this->actionlabel = $label;
4432 * Sets the menu trigger text.
4434 * @param string $trigger The text
4435 * @param string $extraclasses Extra classes to style the secondary menu toggle.
4437 public function set_menu_trigger($trigger, $extraclasses = '') {
4438 $this->menutrigger = $trigger;
4439 $this->triggerextraclasses = $extraclasses;
4443 * Classes for the trigger menu
4445 const DEFAULT_KEBAB_TRIGGER_CLASSES = 'btn btn-icon d-flex align-items-center justify-content-center no-caret';
4448 * Setup trigger as in the kebab menu.
4450 * @param string|null $triggername
4451 * @param core_renderer|null $output
4452 * @param string|null $extraclasses extra classes for the trigger {@see self::set_menu_trigger()}
4453 * @throws coding_exception
4455 public function set_kebab_trigger(?string $triggername = null, ?core_renderer $output = null,
4456 ?string $extraclasses = '') {
4457 global $OUTPUT;
4458 if (empty($output)) {
4459 $output = $OUTPUT;
4461 $label = $triggername ?? get_string('actions');
4462 $triggerclasses = self::DEFAULT_KEBAB_TRIGGER_CLASSES . ' ' . $extraclasses;
4463 $icon = $output->pix_icon('i/menu', $label);
4464 $this->set_menu_trigger($icon, $triggerclasses);
4468 * Return true if there is at least one visible link in the menu.
4470 * @return bool
4472 public function is_empty() {
4473 return !count($this->primaryactions) && !count($this->secondaryactions);
4477 * Initialises JS required fore the action menu.
4478 * The JS is only required once as it manages all action menu's on the page.
4480 * @param moodle_page $page
4482 public function initialise_js(moodle_page $page) {
4483 static $initialised = false;
4484 if (!$initialised) {
4485 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
4486 $initialised = true;
4491 * Adds an action to this action menu.
4493 * @param action_link|pix_icon|subpanel|string $action
4495 public function add($action) {
4497 if ($action instanceof subpanel) {
4498 $this->add_secondary_subpanel($action);
4499 } else if ($action instanceof action_link) {
4500 if ($action->primary) {
4501 $this->add_primary_action($action);
4502 } else {
4503 $this->add_secondary_action($action);
4505 } else if ($action instanceof pix_icon) {
4506 $this->add_primary_action($action);
4507 } else {
4508 $this->add_secondary_action($action);
4513 * Adds a secondary subpanel.
4514 * @param subpanel $subpanel
4516 public function add_secondary_subpanel(subpanel $subpanel) {
4517 $this->secondaryactions[] = $subpanel;
4521 * Adds a primary action to the action menu.
4523 * @param action_menu_link|action_link|pix_icon|string $action
4525 public function add_primary_action($action) {
4526 if ($action instanceof action_link || $action instanceof pix_icon) {
4527 $action->attributes['role'] = 'menuitem';
4528 $action->attributes['tabindex'] = '-1';
4529 if ($action instanceof action_menu_link) {
4530 $action->actionmenu = $this;
4533 $this->primaryactions[] = $action;
4537 * Adds a secondary action to the action menu.
4539 * @param action_link|pix_icon|string $action
4541 public function add_secondary_action($action) {
4542 if ($action instanceof action_link || $action instanceof pix_icon) {
4543 $action->attributes['role'] = 'menuitem';
4544 $action->attributes['tabindex'] = '-1';
4545 if ($action instanceof action_menu_link) {
4546 $action->actionmenu = $this;
4549 $this->secondaryactions[] = $action;
4553 * Returns the primary actions ready to be rendered.
4555 * @param core_renderer $output The renderer to use for getting icons.
4556 * @return array
4558 public function get_primary_actions(core_renderer $output = null) {
4559 global $OUTPUT;
4560 if ($output === null) {
4561 $output = $OUTPUT;
4563 $pixicon = $this->actionicon;
4564 $linkclasses = array('toggle-display');
4566 $title = '';
4567 if (!empty($this->menutrigger)) {
4568 $pixicon = '<b class="caret"></b>';
4569 $linkclasses[] = 'textmenu';
4570 } else {
4571 $title = new lang_string('actionsmenu', 'moodle');
4572 $this->actionicon = new pix_icon(
4573 't/edit_menu',
4575 'moodle',
4576 array('class' => 'iconsmall actionmenu', 'title' => '')
4578 $pixicon = $this->actionicon;
4580 if ($pixicon instanceof renderable) {
4581 $pixicon = $output->render($pixicon);
4582 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
4583 $title = $pixicon->attributes['alt'];
4586 $string = '';
4587 if ($this->actiontext) {
4588 $string = $this->actiontext;
4590 $label = '';
4591 if ($this->actionlabel) {
4592 $label = $this->actionlabel;
4593 } else {
4594 $label = $title;
4596 $actions = $this->primaryactions;
4597 $attributes = array(
4598 'class' => implode(' ', $linkclasses),
4599 'title' => $title,
4600 'aria-label' => $label,
4601 'id' => 'action-menu-toggle-'.$this->instance,
4602 'role' => 'menuitem',
4603 'tabindex' => '-1',
4605 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
4606 if ($this->prioritise) {
4607 array_unshift($actions, $link);
4608 } else {
4609 $actions[] = $link;
4611 return $actions;
4615 * Returns the secondary actions ready to be rendered.
4616 * @return array
4618 public function get_secondary_actions() {
4619 return $this->secondaryactions;
4623 * Sets the selector that should be used to find the owning node of this menu.
4624 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
4626 public function set_owner_selector($selector) {
4627 $this->attributes['data-owner'] = $selector;
4631 * Sets the alignment of the dialogue in relation to button used to toggle it.
4633 * @deprecated since Moodle 4.0
4635 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4636 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4638 public function set_alignment($dialogue, $button) {
4639 debugging('The method action_menu::set_alignment() is deprecated, use action_menu::set_menu_left()', DEBUG_DEVELOPER);
4640 if (isset($this->attributessecondary['data-align'])) {
4641 // We've already got one set, lets remove the old class so as to avoid troubles.
4642 $class = $this->attributessecondary['class'];
4643 $search = 'align-'.$this->attributessecondary['data-align'];
4644 $this->attributessecondary['class'] = str_replace($search, '', $class);
4646 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
4647 $this->attributessecondary['data-align'] = $align;
4648 $this->attributessecondary['class'] .= ' align-'.$align;
4652 * Returns a string to describe the alignment.
4654 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4655 * @return string
4657 protected function get_align_string($align) {
4658 switch ($align) {
4659 case self::TL :
4660 return 'tl';
4661 case self::TR :
4662 return 'tr';
4663 case self::BL :
4664 return 'bl';
4665 case self::BR :
4666 return 'br';
4667 default :
4668 return 'tl';
4673 * Aligns the left corner of the dropdown.
4676 public function set_menu_left() {
4677 $this->dropdownalignment = 'dropdown-menu-left';
4681 * Sets a constraint for the dialogue.
4683 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
4684 * element the constraint identifies.
4686 * This is required whenever the action menu is displayed inside any CSS element with the .no-overflow class
4687 * (flexible_table and any of it's child classes are a likely candidate).
4689 * @deprecated since Moodle 4.3
4690 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
4692 public function set_constraint($ancestorselector) {
4693 debugging('The method set_constraint() is deprecated. Please use the set_boundary() method instead.', DEBUG_DEVELOPER);
4694 $this->set_boundary('window');
4698 * Set the overflow constraint boundary of the dropdown menu.
4699 * @see https://getbootstrap.com/docs/4.6/components/dropdowns/#options The 'boundary' option in the Bootstrap documentation
4701 * @param string $boundary Accepts the values of 'viewport', 'window', or 'scrollParent'.
4702 * @throws coding_exception
4704 public function set_boundary(string $boundary) {
4705 if (!in_array($boundary, ['viewport', 'window', 'scrollParent'])) {
4706 throw new coding_exception("HTMLElement reference boundaries are not supported." .
4707 "Accepted boundaries are 'viewport', 'window', or 'scrollParent'.", DEBUG_DEVELOPER);
4710 $this->triggerattributes['data-boundary'] = $boundary;
4714 * If you call this method the action menu will be displayed but will not be enhanced.
4716 * By not displaying the menu enhanced all items will be displayed in a single row.
4718 * @deprecated since Moodle 3.2
4720 public function do_not_enhance() {
4721 debugging('The method action_menu::do_not_enhance() is deprecated, use a list of action_icon instead.', DEBUG_DEVELOPER);
4725 * Returns true if this action menu will be enhanced.
4727 * @return bool
4729 public function will_be_enhanced() {
4730 return isset($this->attributes['data-enhance']);
4734 * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
4736 * This property can be useful when the action menu is displayed within a parent element that is either floated
4737 * or relatively positioned.
4738 * In that situation the width of the menu is determined by the width of the parent element which may not be large
4739 * enough for the menu items without them wrapping.
4740 * This disables the wrapping so that the menu takes on the width of the longest item.
4742 * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
4744 public function set_nowrap_on_items($value = true) {
4745 $class = 'nowrap-items';
4746 if (!empty($this->attributes['class'])) {
4747 $pos = strpos($this->attributes['class'], $class);
4748 if ($value === true && $pos === false) {
4749 // The value is true and the class has not been set yet. Add it.
4750 $this->attributes['class'] .= ' '.$class;
4751 } else if ($value === false && $pos !== false) {
4752 // The value is false and the class has been set. Remove it.
4753 $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class));
4755 } else if ($value) {
4756 // The value is true and the class has not been set yet. Add it.
4757 $this->attributes['class'] = $class;
4762 * Add classes to the action menu for an easier styling.
4764 * @param string $class The class to add to attributes.
4766 public function set_additional_classes(string $class = '') {
4767 if (!empty($this->attributes['class'])) {
4768 $this->attributes['class'] .= " ".$class;
4769 } else {
4770 $this->attributes['class'] = $class;
4775 * Export for template.
4777 * @param renderer_base $output The renderer.
4778 * @return stdClass
4780 public function export_for_template(renderer_base $output) {
4781 $data = new stdClass();
4782 // Assign a role of menubar to this action menu when:
4783 // - it contains 2 or more primary actions; or
4784 // - if it contains a primary action and secondary actions.
4785 if (count($this->primaryactions) > 1 || (!empty($this->primaryactions) && !empty($this->secondaryactions))) {
4786 $this->attributes['role'] = 'menubar';
4788 $attributes = $this->attributes;
4790 $data->instance = $this->instance;
4792 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
4793 unset($attributes['class']);
4795 $data->attributes = array_map(function($key, $value) {
4796 return [ 'name' => $key, 'value' => $value ];
4797 }, array_keys($attributes), $attributes);
4799 $data->primary = $this->export_primary_actions_for_template($output);
4800 $data->secondary = $this->export_secondary_actions_for_template($output);
4801 $data->dropdownalignment = $this->dropdownalignment;
4803 return $data;
4807 * Export the primary actions for the template.
4808 * @param renderer_base $output
4809 * @return stdClass
4811 protected function export_primary_actions_for_template(renderer_base $output): stdClass {
4812 $attributes = $this->attributes;
4813 $attributesprimary = $this->attributesprimary;
4815 $primary = new stdClass();
4816 $primary->title = '';
4817 $primary->prioritise = $this->prioritise;
4819 $primary->classes = isset($attributesprimary['class']) ? $attributesprimary['class'] : '';
4820 unset($attributesprimary['class']);
4822 $primary->attributes = array_map(function ($key, $value) {
4823 return ['name' => $key, 'value' => $value];
4824 }, array_keys($attributesprimary), $attributesprimary);
4825 $primary->triggerattributes = array_map(function ($key, $value) {
4826 return ['name' => $key, 'value' => $value];
4827 }, array_keys($this->triggerattributes), $this->triggerattributes);
4829 $actionicon = $this->actionicon;
4830 if (!empty($this->menutrigger)) {
4831 $primary->menutrigger = $this->menutrigger;
4832 $primary->triggerextraclasses = $this->triggerextraclasses;
4833 if ($this->actionlabel) {
4834 $primary->title = $this->actionlabel;
4835 } else if ($this->actiontext) {
4836 $primary->title = $this->actiontext;
4837 } else {
4838 $primary->title = strip_tags($this->menutrigger);
4840 } else {
4841 $primary->title = get_string('actionsmenu');
4842 $iconattributes = ['class' => 'iconsmall actionmenu', 'title' => $primary->title];
4843 $actionicon = new pix_icon('t/edit_menu', '', 'moodle', $iconattributes);
4846 // If the menu trigger is within the menubar, assign a role of menuitem. Otherwise, assign as a button.
4847 $primary->triggerrole = 'button';
4848 if (isset($attributes['role']) && $attributes['role'] === 'menubar') {
4849 $primary->triggerrole = 'menuitem';
4852 if ($actionicon instanceof pix_icon) {
4853 $primary->icon = $actionicon->export_for_pix();
4854 if (!empty($actionicon->attributes['alt'])) {
4855 $primary->title = $actionicon->attributes['alt'];
4857 } else {
4858 $primary->iconraw = $actionicon ? $output->render($actionicon) : '';
4861 $primary->actiontext = $this->actiontext ? (string) $this->actiontext : '';
4862 $primary->items = array_map(function ($item) use ($output) {
4863 $data = (object) [];
4864 if ($item instanceof action_menu_link) {
4865 $data->actionmenulink = $item->export_for_template($output);
4866 } else if ($item instanceof action_menu_filler) {
4867 $data->actionmenufiller = $item->export_for_template($output);
4868 } else if ($item instanceof action_link) {
4869 $data->actionlink = $item->export_for_template($output);
4870 } else if ($item instanceof pix_icon) {
4871 $data->pixicon = $item->export_for_template($output);
4872 } else {
4873 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4875 return $data;
4876 }, $this->primaryactions);
4877 return $primary;
4881 * Export the secondary actions for the template.
4882 * @param renderer_base $output
4883 * @return stdClass
4885 protected function export_secondary_actions_for_template(renderer_base $output): stdClass {
4886 $attributessecondary = $this->attributessecondary;
4887 $secondary = new stdClass();
4888 $secondary->classes = isset($attributessecondary['class']) ? $attributessecondary['class'] : '';
4889 unset($attributessecondary['class']);
4891 $secondary->attributes = array_map(function ($key, $value) {
4892 return ['name' => $key, 'value' => $value];
4893 }, array_keys($attributessecondary), $attributessecondary);
4894 $secondary->items = array_map(function ($item) use ($output) {
4895 $data = (object) [
4896 'simpleitem' => true,
4898 if ($item instanceof action_menu_link) {
4899 $data->actionmenulink = $item->export_for_template($output);
4900 $data->simpleitem = false;
4901 } else if ($item instanceof action_menu_filler) {
4902 $data->actionmenufiller = $item->export_for_template($output);
4903 $data->simpleitem = false;
4904 } else if ($item instanceof subpanel) {
4905 $data->subpanel = $item->export_for_template($output);
4906 $data->simpleitem = false;
4907 } else if ($item instanceof action_link) {
4908 $data->actionlink = $item->export_for_template($output);
4909 } else if ($item instanceof pix_icon) {
4910 $data->pixicon = $item->export_for_template($output);
4911 } else {
4912 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4914 return $data;
4915 }, $this->secondaryactions);
4916 return $secondary;
4921 * An action menu filler
4923 * @package core
4924 * @category output
4925 * @copyright 2013 Andrew Nicols
4926 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4928 class action_menu_filler extends action_link implements renderable {
4931 * True if this is a primary action. False if not.
4932 * @var bool
4934 public $primary = true;
4937 * Constructs the object.
4939 public function __construct() {
4940 $this->attributes['id'] = html_writer::random_id('action_link');
4945 * An action menu action
4947 * @package core
4948 * @category output
4949 * @copyright 2013 Sam Hemelryk
4950 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4952 class action_menu_link extends action_link implements renderable {
4955 * True if this is a primary action. False if not.
4956 * @var bool
4958 public $primary = true;
4961 * The action menu this link has been added to.
4962 * @var action_menu
4964 public $actionmenu = null;
4967 * The number of instances of this action menu link (and its subclasses).
4969 * @deprecated since Moodle 4.4.
4970 * @var int
4972 protected static $instance = 1;
4975 * Constructs the object.
4977 * @param moodle_url $url The URL for the action.
4978 * @param pix_icon|null $icon The icon to represent the action.
4979 * @param string $text The text to represent the action.
4980 * @param bool $primary Whether this is a primary action or not.
4981 * @param array $attributes Any attribtues associated with the action.
4983 public function __construct(moodle_url $url, ?pix_icon $icon, $text, $primary = true, array $attributes = array()) {
4984 parent::__construct($url, $text, null, $attributes, $icon);
4985 $this->primary = (bool)$primary;
4986 $this->add_class('menu-action');
4987 $this->attributes['role'] = 'menuitem';
4991 * Export for template.
4993 * @param renderer_base $output The renderer.
4994 * @return stdClass
4996 public function export_for_template(renderer_base $output) {
4997 $data = parent::export_for_template($output);
4999 // Ignore what the parent did with the attributes, except for ID and class.
5000 $data->attributes = [];
5001 $attributes = $this->attributes;
5002 unset($attributes['id']);
5003 unset($attributes['class']);
5005 // Handle text being a renderable.
5006 if ($this->text instanceof renderable) {
5007 $data->text = $this->render($this->text);
5010 $data->showtext = (!$this->icon || $this->primary === false);
5012 $data->icon = null;
5013 if ($this->icon) {
5014 $icon = $this->icon;
5015 if ($this->primary || !$this->actionmenu->will_be_enhanced()) {
5016 $attributes['title'] = $data->text;
5018 $data->icon = $icon ? $icon->export_for_pix() : null;
5021 $data->disabled = !empty($attributes['disabled']);
5022 unset($attributes['disabled']);
5024 $data->attributes = array_map(function($key, $value) {
5025 return [
5026 'name' => $key,
5027 'value' => $value
5029 }, array_keys($attributes), $attributes);
5031 return $data;
5036 * A primary action menu action
5038 * @package core
5039 * @category output
5040 * @copyright 2013 Sam Hemelryk
5041 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5043 class action_menu_link_primary extends action_menu_link {
5045 * Constructs the object.
5047 * @param moodle_url $url
5048 * @param pix_icon|null $icon
5049 * @param string $text
5050 * @param array $attributes
5052 public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) {
5053 parent::__construct($url, $icon, $text, true, $attributes);
5058 * A secondary action menu action
5060 * @package core
5061 * @category output
5062 * @copyright 2013 Sam Hemelryk
5063 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5065 class action_menu_link_secondary extends action_menu_link {
5067 * Constructs the object.
5069 * @param moodle_url $url
5070 * @param pix_icon|null $icon
5071 * @param string $text
5072 * @param array $attributes
5074 public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) {
5075 parent::__construct($url, $icon, $text, false, $attributes);
5080 * Represents a set of preferences groups.
5082 * @package core
5083 * @category output
5084 * @copyright 2015 Frédéric Massart - FMCorz.net
5085 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5087 class preferences_groups implements renderable {
5090 * Array of preferences_group.
5091 * @var array
5093 public $groups;
5096 * Constructor.
5097 * @param array $groups of preferences_group
5099 public function __construct($groups) {
5100 $this->groups = $groups;
5106 * Represents a group of preferences page link.
5108 * @package core
5109 * @category output
5110 * @copyright 2015 Frédéric Massart - FMCorz.net
5111 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5113 class preferences_group implements renderable {
5116 * Title of the group.
5117 * @var string
5119 public $title;
5122 * Array of navigation_node.
5123 * @var array
5125 public $nodes;
5128 * Constructor.
5129 * @param string $title The title.
5130 * @param array $nodes of navigation_node.
5132 public function __construct($title, $nodes) {
5133 $this->title = $title;
5134 $this->nodes = $nodes;
5139 * Progress bar class.
5141 * Manages the display of a progress bar.
5143 * To use this class.
5144 * - construct
5145 * - call create (or use the 3rd param to the constructor)
5146 * - call update or update_full() or update() repeatedly
5148 * @copyright 2008 jamiesensei
5149 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5150 * @package core
5151 * @category output
5153 class progress_bar implements renderable, templatable {
5154 /** @var string html id */
5155 private $html_id;
5156 /** @var int total width */
5157 private $width;
5158 /** @var int last percentage printed */
5159 private $percent = 0;
5160 /** @var int time when last printed */
5161 private $lastupdate = 0;
5162 /** @var int when did we start printing this */
5163 private $time_start = 0;
5166 * Constructor
5168 * Prints JS code if $autostart true.
5170 * @param string $htmlid The container ID.
5171 * @param int $width The suggested width.
5172 * @param bool $autostart Whether to start the progress bar right away.
5174 public function __construct($htmlid = '', $width = 500, $autostart = false) {
5175 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
5176 debugging('progress_bar used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', DEBUG_DEVELOPER);
5179 if (!empty($htmlid)) {
5180 $this->html_id = $htmlid;
5181 } else {
5182 $this->html_id = 'pbar_'.uniqid();
5185 $this->width = $width;
5187 if ($autostart) {
5188 $this->create();
5193 * Getter for ID
5194 * @return string id
5196 public function get_id(): string {
5197 return $this->html_id;
5201 * Create a new progress bar, this function will output html.
5203 * @return void Echo's output
5205 public function create() {
5206 global $OUTPUT;
5208 $this->time_start = microtime(true);
5210 flush();
5211 echo $OUTPUT->render($this);
5212 flush();
5216 * Update the progress bar.
5218 * @param int $percent From 1-100.
5219 * @param string $msg The message.
5220 * @return void Echo's output
5221 * @throws coding_exception
5223 private function _update($percent, $msg) {
5224 global $OUTPUT;
5226 if (empty($this->time_start)) {
5227 throw new coding_exception('You must call create() (or use the $autostart ' .
5228 'argument to the constructor) before you try updating the progress bar.');
5231 $estimate = $this->estimate($percent);
5233 if ($estimate === null) {
5234 // Always do the first and last updates.
5235 } else if ($estimate == 0) {
5236 // Always do the last updates.
5237 } else if ($this->lastupdate + 20 < time()) {
5238 // We must update otherwise browser would time out.
5239 } else if (round($this->percent, 2) === round($percent, 2)) {
5240 // No significant change, no need to update anything.
5241 return;
5244 $estimatemsg = '';
5245 if ($estimate != 0 && is_numeric($estimate)) {
5246 // Err on the conservative side and also avoid showing 'now' as the estimate.
5247 $estimatemsg = format_time(ceil($estimate));
5250 $this->percent = $percent;
5251 $this->lastupdate = microtime(true);
5253 echo $OUTPUT->render_progress_bar_update($this->html_id, $this->percent, $msg, $estimatemsg);
5254 flush();
5258 * Estimate how much time it is going to take.
5260 * @param int $pt From 1-100.
5261 * @return mixed Null (unknown), or int.
5263 private function estimate($pt) {
5264 if ($this->lastupdate == 0) {
5265 return null;
5267 if ($pt < 0.00001) {
5268 return null; // We do not know yet how long it will take.
5270 if ($pt > 99.99999) {
5271 return 0; // Nearly done, right?
5273 $consumed = microtime(true) - $this->time_start;
5274 if ($consumed < 0.001) {
5275 return null;
5278 return (100 - $pt) * ($consumed / $pt);
5282 * Update progress bar according percent.
5284 * @param int $percent From 1-100.
5285 * @param string $msg The message needed to be shown.
5287 public function update_full($percent, $msg) {
5288 $percent = max(min($percent, 100), 0);
5289 $this->_update($percent, $msg);
5293 * Update progress bar according the number of tasks.
5295 * @param int $cur Current task number.
5296 * @param int $total Total task number.
5297 * @param string $msg The message needed to be shown.
5299 public function update($cur, $total, $msg) {
5300 $percent = ($cur / $total) * 100;
5301 $this->update_full($percent, $msg);
5305 * Restart the progress bar.
5307 public function restart() {
5308 $this->percent = 0;
5309 $this->lastupdate = 0;
5310 $this->time_start = 0;
5314 * Export for template.
5316 * @param renderer_base $output The renderer.
5317 * @return array
5319 public function export_for_template(renderer_base $output) {
5320 return [
5321 'id' => $this->html_id,
5322 'width' => $this->width,