Merge branch 'MDL-78457' of https://github.com/paulholden/moodle
[moodle.git] / lib / outputcomponents.php
blobea031e1b0dceeeab5e5ba1fbf32e64b90c2ea05f
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 array
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 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 $attributes['alt'] = $alt;
1845 return self::empty_tag('img', $attributes);
1849 * Generates random html element id.
1851 * @staticvar int $counter
1852 * @staticvar type $uniq
1853 * @param string $base A string fragment that will be included in the random ID.
1854 * @return string A unique ID
1856 public static function random_id($base='random') {
1857 static $counter = 0;
1858 static $uniq;
1860 if (!isset($uniq)) {
1861 $uniq = uniqid();
1864 $counter++;
1865 return $base.$uniq.$counter;
1869 * Generates a simple html link
1871 * @param string|moodle_url $url The URL
1872 * @param string $text The text
1873 * @param array $attributes HTML attributes
1874 * @return string HTML fragment
1876 public static function link($url, $text, array $attributes = null) {
1877 $attributes = (array)$attributes;
1878 $attributes['href'] = $url;
1879 return self::tag('a', $text, $attributes);
1883 * Generates a simple checkbox with optional label
1885 * @param string $name The name of the checkbox
1886 * @param string $value The value of the checkbox
1887 * @param bool $checked Whether the checkbox is checked
1888 * @param string $label The label for the checkbox
1889 * @param array $attributes Any attributes to apply to the checkbox
1890 * @param array $labelattributes Any attributes to apply to the label, if present
1891 * @return string html fragment
1893 public static function checkbox($name, $value, $checked = true, $label = '',
1894 array $attributes = null, array $labelattributes = null) {
1895 $attributes = (array) $attributes;
1896 $output = '';
1898 if ($label !== '' and !is_null($label)) {
1899 if (empty($attributes['id'])) {
1900 $attributes['id'] = self::random_id('checkbox_');
1903 $attributes['type'] = 'checkbox';
1904 $attributes['value'] = $value;
1905 $attributes['name'] = $name;
1906 $attributes['checked'] = $checked ? 'checked' : null;
1908 $output .= self::empty_tag('input', $attributes);
1910 if ($label !== '' and !is_null($label)) {
1911 $labelattributes = (array) $labelattributes;
1912 $labelattributes['for'] = $attributes['id'];
1913 $output .= self::tag('label', $label, $labelattributes);
1916 return $output;
1920 * Generates a simple select yes/no form field
1922 * @param string $name name of select element
1923 * @param bool $selected
1924 * @param array $attributes - html select element attributes
1925 * @return string HTML fragment
1927 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1928 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1929 return self::select($options, $name, $selected, null, $attributes);
1933 * Generates a simple select form field
1935 * Note this function does HTML escaping on the optgroup labels, but not on the choice labels.
1937 * @param array $options associative array value=>label ex.:
1938 * array(1=>'One, 2=>Two)
1939 * it is also possible to specify optgroup as complex label array ex.:
1940 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1941 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1942 * @param string $name name of select element
1943 * @param string|array $selected value or array of values depending on multiple attribute
1944 * @param array|bool $nothing add nothing selected option, or false of not added
1945 * @param array $attributes html select element attributes
1946 * @return string HTML fragment
1948 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1949 $attributes = (array)$attributes;
1950 if (is_array($nothing)) {
1951 foreach ($nothing as $k=>$v) {
1952 if ($v === 'choose' or $v === 'choosedots') {
1953 $nothing[$k] = get_string('choosedots');
1956 $options = $nothing + $options; // keep keys, do not override
1958 } else if (is_string($nothing) and $nothing !== '') {
1959 // BC
1960 $options = array(''=>$nothing) + $options;
1963 // we may accept more values if multiple attribute specified
1964 $selected = (array)$selected;
1965 foreach ($selected as $k=>$v) {
1966 $selected[$k] = (string)$v;
1969 if (!isset($attributes['id'])) {
1970 $id = 'menu'.$name;
1971 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1972 $id = str_replace('[', '', $id);
1973 $id = str_replace(']', '', $id);
1974 $attributes['id'] = $id;
1977 if (!isset($attributes['class'])) {
1978 $class = 'menu'.$name;
1979 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1980 $class = str_replace('[', '', $class);
1981 $class = str_replace(']', '', $class);
1982 $attributes['class'] = $class;
1984 $attributes['class'] = 'select custom-select ' . $attributes['class']; // Add 'select' selector always.
1986 $attributes['name'] = $name;
1988 if (!empty($attributes['disabled'])) {
1989 $attributes['disabled'] = 'disabled';
1990 } else {
1991 unset($attributes['disabled']);
1994 $output = '';
1995 foreach ($options as $value=>$label) {
1996 if (is_array($label)) {
1997 // ignore key, it just has to be unique
1998 $output .= self::select_optgroup(key($label), current($label), $selected);
1999 } else {
2000 $output .= self::select_option($label, $value, $selected);
2003 return self::tag('select', $output, $attributes);
2007 * Returns HTML to display a select box option.
2009 * @param string $label The label to display as the option.
2010 * @param string|int $value The value the option represents
2011 * @param array $selected An array of selected options
2012 * @return string HTML fragment
2014 private static function select_option($label, $value, array $selected) {
2015 $attributes = array();
2016 $value = (string)$value;
2017 if (in_array($value, $selected, true)) {
2018 $attributes['selected'] = 'selected';
2020 $attributes['value'] = $value;
2021 return self::tag('option', $label, $attributes);
2025 * Returns HTML to display a select box option group.
2027 * @param string $groupname The label to use for the group
2028 * @param array $options The options in the group
2029 * @param array $selected An array of selected values.
2030 * @return string HTML fragment.
2032 private static function select_optgroup($groupname, $options, array $selected) {
2033 if (empty($options)) {
2034 return '';
2036 $attributes = array('label'=>$groupname);
2037 $output = '';
2038 foreach ($options as $value=>$label) {
2039 $output .= self::select_option($label, $value, $selected);
2041 return self::tag('optgroup', $output, $attributes);
2045 * This is a shortcut for making an hour selector menu.
2047 * @param string $type The type of selector (years, months, days, hours, minutes)
2048 * @param string $name fieldname
2049 * @param int $currenttime A default timestamp in GMT
2050 * @param int $step minute spacing
2051 * @param array $attributes - html select element attributes
2052 * @param float|int|string $timezone the timezone to use to calculate the time
2053 * {@link https://moodledev.io/docs/apis/subsystems/time#timezone}
2054 * @return string HTML fragment
2056 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null, $timezone = 99) {
2057 global $OUTPUT;
2059 if (!$currenttime) {
2060 $currenttime = time();
2062 $calendartype = \core_calendar\type_factory::get_calendar_instance();
2063 $currentdate = $calendartype->timestamp_to_date_array($currenttime, $timezone);
2065 $userdatetype = $type;
2066 $timeunits = array();
2068 switch ($type) {
2069 case 'years':
2070 $timeunits = $calendartype->get_years();
2071 $userdatetype = 'year';
2072 break;
2073 case 'months':
2074 $timeunits = $calendartype->get_months();
2075 $userdatetype = 'month';
2076 $currentdate['month'] = (int)$currentdate['mon'];
2077 break;
2078 case 'days':
2079 $timeunits = $calendartype->get_days();
2080 $userdatetype = 'mday';
2081 break;
2082 case 'hours':
2083 for ($i=0; $i<=23; $i++) {
2084 $timeunits[$i] = sprintf("%02d",$i);
2086 break;
2087 case 'minutes':
2088 if ($step != 1) {
2089 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
2092 for ($i=0; $i<=59; $i+=$step) {
2093 $timeunits[$i] = sprintf("%02d",$i);
2095 break;
2096 default:
2097 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
2100 $attributes = (array) $attributes;
2101 $data = (object) [
2102 'name' => $name,
2103 'id' => !empty($attributes['id']) ? $attributes['id'] : self::random_id('ts_'),
2104 'label' => get_string(substr($type, 0, -1), 'form'),
2105 'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) {
2106 return [
2107 'name' => $timeunits[$value],
2108 'value' => $value,
2109 'selected' => $currentdate[$userdatetype] == $value
2111 }, array_keys($timeunits)),
2114 unset($attributes['id']);
2115 unset($attributes['name']);
2116 $data->attributes = array_map(function($name) use ($attributes) {
2117 return [
2118 'name' => $name,
2119 'value' => $attributes[$name]
2121 }, array_keys($attributes));
2123 return $OUTPUT->render_from_template('core/select_time', $data);
2127 * Shortcut for quick making of lists
2129 * Note: 'list' is a reserved keyword ;-)
2131 * @param array $items
2132 * @param array $attributes
2133 * @param string $tag ul or ol
2134 * @return string
2136 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
2137 $output = html_writer::start_tag($tag, $attributes)."\n";
2138 foreach ($items as $item) {
2139 $output .= html_writer::tag('li', $item)."\n";
2141 $output .= html_writer::end_tag($tag);
2142 return $output;
2146 * Returns hidden input fields created from url parameters.
2148 * @param moodle_url $url
2149 * @param array $exclude list of excluded parameters
2150 * @return string HTML fragment
2152 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
2153 $exclude = (array)$exclude;
2154 $params = $url->params();
2155 foreach ($exclude as $key) {
2156 unset($params[$key]);
2159 $output = '';
2160 foreach ($params as $key => $value) {
2161 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
2162 $output .= self::empty_tag('input', $attributes)."\n";
2164 return $output;
2168 * Generate a script tag containing the the specified code.
2170 * @param string $jscode the JavaScript code
2171 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
2172 * @return string HTML, the code wrapped in <script> tags.
2174 public static function script($jscode, $url=null) {
2175 if ($jscode) {
2176 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n") . "\n";
2178 } else if ($url) {
2179 return self::tag('script', '', ['src' => $url]) . "\n";
2181 } else {
2182 return '';
2187 * Renders HTML table
2189 * This method may modify the passed instance by adding some default properties if they are not set yet.
2190 * If this is not what you want, you should make a full clone of your data before passing them to this
2191 * method. In most cases this is not an issue at all so we do not clone by default for performance
2192 * and memory consumption reasons.
2194 * @param html_table $table data to be rendered
2195 * @return string HTML code
2197 public static function table(html_table $table) {
2198 // prepare table data and populate missing properties with reasonable defaults
2199 if (!empty($table->align)) {
2200 foreach ($table->align as $key => $aa) {
2201 if ($aa) {
2202 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
2203 } else {
2204 $table->align[$key] = null;
2208 if (!empty($table->size)) {
2209 foreach ($table->size as $key => $ss) {
2210 if ($ss) {
2211 $table->size[$key] = 'width:'. $ss .';';
2212 } else {
2213 $table->size[$key] = null;
2217 if (!empty($table->wrap)) {
2218 foreach ($table->wrap as $key => $ww) {
2219 if ($ww) {
2220 $table->wrap[$key] = 'white-space:nowrap;';
2221 } else {
2222 $table->wrap[$key] = '';
2226 if (!empty($table->head)) {
2227 foreach ($table->head as $key => $val) {
2228 if (!isset($table->align[$key])) {
2229 $table->align[$key] = null;
2231 if (!isset($table->size[$key])) {
2232 $table->size[$key] = null;
2234 if (!isset($table->wrap[$key])) {
2235 $table->wrap[$key] = null;
2240 if (empty($table->attributes['class'])) {
2241 $table->attributes['class'] = 'generaltable';
2243 if (!empty($table->tablealign)) {
2244 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
2247 // explicitly assigned properties override those defined via $table->attributes
2248 $table->attributes['class'] = trim($table->attributes['class']);
2249 $attributes = array_merge($table->attributes, array(
2250 'id' => $table->id,
2251 'width' => $table->width,
2252 'summary' => $table->summary,
2253 'cellpadding' => $table->cellpadding,
2254 'cellspacing' => $table->cellspacing,
2256 $output = html_writer::start_tag('table', $attributes) . "\n";
2258 $countcols = 0;
2260 // Output a caption if present.
2261 if (!empty($table->caption)) {
2262 $captionattributes = array();
2263 if ($table->captionhide) {
2264 $captionattributes['class'] = 'accesshide';
2266 $output .= html_writer::tag(
2267 'caption',
2268 $table->caption,
2269 $captionattributes
2273 if (!empty($table->head)) {
2274 $countcols = count($table->head);
2276 $output .= html_writer::start_tag('thead', array()) . "\n";
2277 $output .= html_writer::start_tag('tr', array()) . "\n";
2278 $keys = array_keys($table->head);
2279 $lastkey = end($keys);
2281 foreach ($table->head as $key => $heading) {
2282 // Convert plain string headings into html_table_cell objects
2283 if (!($heading instanceof html_table_cell)) {
2284 $headingtext = $heading;
2285 $heading = new html_table_cell();
2286 $heading->text = $headingtext;
2287 $heading->header = true;
2290 if ($heading->header !== false) {
2291 $heading->header = true;
2294 $tagtype = 'td';
2295 if ($heading->header && (string)$heading->text != '') {
2296 $tagtype = 'th';
2299 $heading->attributes['class'] .= ' header c' . $key;
2300 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
2301 $heading->colspan = $table->headspan[$key];
2302 $countcols += $table->headspan[$key] - 1;
2305 if ($key == $lastkey) {
2306 $heading->attributes['class'] .= ' lastcol';
2308 if (isset($table->colclasses[$key])) {
2309 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
2311 $heading->attributes['class'] = trim($heading->attributes['class']);
2312 $attributes = array_merge($heading->attributes, [
2313 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
2314 'colspan' => $heading->colspan,
2317 if ($tagtype == 'th') {
2318 $attributes['scope'] = !empty($heading->scope) ? $heading->scope : 'col';
2321 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
2323 $output .= html_writer::end_tag('tr') . "\n";
2324 $output .= html_writer::end_tag('thead') . "\n";
2326 if (empty($table->data)) {
2327 // For valid XHTML strict every table must contain either a valid tr
2328 // or a valid tbody... both of which must contain a valid td
2329 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
2330 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
2331 $output .= html_writer::end_tag('tbody');
2335 if (!empty($table->data)) {
2336 $keys = array_keys($table->data);
2337 $lastrowkey = end($keys);
2338 $output .= html_writer::start_tag('tbody', array());
2340 foreach ($table->data as $key => $row) {
2341 if (($row === 'hr') && ($countcols)) {
2342 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
2343 } else {
2344 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
2345 if (!($row instanceof html_table_row)) {
2346 $newrow = new html_table_row();
2348 foreach ($row as $cell) {
2349 if (!($cell instanceof html_table_cell)) {
2350 $cell = new html_table_cell($cell);
2352 $newrow->cells[] = $cell;
2354 $row = $newrow;
2357 if (isset($table->rowclasses[$key])) {
2358 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
2361 if ($key == $lastrowkey) {
2362 $row->attributes['class'] .= ' lastrow';
2365 // Explicitly assigned properties should override those defined in the attributes.
2366 $row->attributes['class'] = trim($row->attributes['class']);
2367 $trattributes = array_merge($row->attributes, array(
2368 'id' => $row->id,
2369 'style' => $row->style,
2371 $output .= html_writer::start_tag('tr', $trattributes) . "\n";
2372 $keys2 = array_keys($row->cells);
2373 $lastkey = end($keys2);
2375 $gotlastkey = false; //flag for sanity checking
2376 foreach ($row->cells as $key => $cell) {
2377 if ($gotlastkey) {
2378 //This should never happen. Why do we have a cell after the last cell?
2379 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
2382 if (!($cell instanceof html_table_cell)) {
2383 $mycell = new html_table_cell();
2384 $mycell->text = $cell;
2385 $cell = $mycell;
2388 if (($cell->header === true) && empty($cell->scope)) {
2389 $cell->scope = 'row';
2392 if (isset($table->colclasses[$key])) {
2393 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
2396 $cell->attributes['class'] .= ' cell c' . $key;
2397 if ($key == $lastkey) {
2398 $cell->attributes['class'] .= ' lastcol';
2399 $gotlastkey = true;
2401 $tdstyle = '';
2402 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
2403 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
2404 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
2405 $cell->attributes['class'] = trim($cell->attributes['class']);
2406 $tdattributes = array_merge($cell->attributes, array(
2407 'style' => $tdstyle . $cell->style,
2408 'colspan' => $cell->colspan,
2409 'rowspan' => $cell->rowspan,
2410 'id' => $cell->id,
2411 'abbr' => $cell->abbr,
2412 'scope' => $cell->scope,
2414 $tagtype = 'td';
2415 if ($cell->header === true) {
2416 $tagtype = 'th';
2418 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
2421 $output .= html_writer::end_tag('tr') . "\n";
2423 $output .= html_writer::end_tag('tbody') . "\n";
2425 $output .= html_writer::end_tag('table') . "\n";
2427 if ($table->responsive) {
2428 return self::div($output, 'table-responsive');
2431 return $output;
2435 * Renders form element label
2437 * By default, the label is suffixed with a label separator defined in the
2438 * current language pack (colon by default in the English lang pack).
2439 * Adding the colon can be explicitly disabled if needed. Label separators
2440 * are put outside the label tag itself so they are not read by
2441 * screenreaders (accessibility).
2443 * Parameter $for explicitly associates the label with a form control. When
2444 * set, the value of this attribute must be the same as the value of
2445 * the id attribute of the form control in the same document. When null,
2446 * the label being defined is associated with the control inside the label
2447 * element.
2449 * @param string $text content of the label tag
2450 * @param string|null $for id of the element this label is associated with, null for no association
2451 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
2452 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
2453 * @return string HTML of the label element
2455 public static function label($text, $for, $colonize = true, array $attributes=array()) {
2456 if (!is_null($for)) {
2457 $attributes = array_merge($attributes, array('for' => $for));
2459 $text = trim($text ?? '');
2460 $label = self::tag('label', $text, $attributes);
2462 // TODO MDL-12192 $colonize disabled for now yet
2463 // if (!empty($text) and $colonize) {
2464 // // the $text may end with the colon already, though it is bad string definition style
2465 // $colon = get_string('labelsep', 'langconfig');
2466 // if (!empty($colon)) {
2467 // $trimmed = trim($colon);
2468 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
2469 // //debugging('The label text should not end with colon or other label separator,
2470 // // please fix the string definition.', DEBUG_DEVELOPER);
2471 // } else {
2472 // $label .= $colon;
2473 // }
2474 // }
2475 // }
2477 return $label;
2481 * Combines a class parameter with other attributes. Aids in code reduction
2482 * because the class parameter is very frequently used.
2484 * If the class attribute is specified both in the attributes and in the
2485 * class parameter, the two values are combined with a space between.
2487 * @param string $class Optional CSS class (or classes as space-separated list)
2488 * @param array $attributes Optional other attributes as array
2489 * @return array Attributes (or null if still none)
2491 private static function add_class($class = '', array $attributes = null) {
2492 if ($class !== '') {
2493 $classattribute = array('class' => $class);
2494 if ($attributes) {
2495 if (array_key_exists('class', $attributes)) {
2496 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
2497 } else {
2498 $attributes = $classattribute + $attributes;
2500 } else {
2501 $attributes = $classattribute;
2504 return $attributes;
2508 * Creates a <div> tag. (Shortcut function.)
2510 * @param string $content HTML content of tag
2511 * @param string $class Optional CSS class (or classes as space-separated list)
2512 * @param array $attributes Optional other attributes as array
2513 * @return string HTML code for div
2515 public static function div($content, $class = '', array $attributes = null) {
2516 return self::tag('div', $content, self::add_class($class, $attributes));
2520 * Starts a <div> tag. (Shortcut function.)
2522 * @param string $class Optional CSS class (or classes as space-separated list)
2523 * @param array $attributes Optional other attributes as array
2524 * @return string HTML code for open div tag
2526 public static function start_div($class = '', array $attributes = null) {
2527 return self::start_tag('div', self::add_class($class, $attributes));
2531 * Ends a <div> tag. (Shortcut function.)
2533 * @return string HTML code for close div tag
2535 public static function end_div() {
2536 return self::end_tag('div');
2540 * Creates a <span> tag. (Shortcut function.)
2542 * @param string $content HTML content of tag
2543 * @param string $class Optional CSS class (or classes as space-separated list)
2544 * @param array $attributes Optional other attributes as array
2545 * @return string HTML code for span
2547 public static function span($content, $class = '', array $attributes = null) {
2548 return self::tag('span', $content, self::add_class($class, $attributes));
2552 * Starts a <span> tag. (Shortcut function.)
2554 * @param string $class Optional CSS class (or classes as space-separated list)
2555 * @param array $attributes Optional other attributes as array
2556 * @return string HTML code for open span tag
2558 public static function start_span($class = '', array $attributes = null) {
2559 return self::start_tag('span', self::add_class($class, $attributes));
2563 * Ends a <span> tag. (Shortcut function.)
2565 * @return string HTML code for close span tag
2567 public static function end_span() {
2568 return self::end_tag('span');
2573 * Simple javascript output class
2575 * @copyright 2010 Petr Skoda
2576 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2577 * @since Moodle 2.0
2578 * @package core
2579 * @category output
2581 class js_writer {
2584 * Returns javascript code calling the function
2586 * @param string $function function name, can be complex like Y.Event.purgeElement
2587 * @param array $arguments parameters
2588 * @param int $delay execution delay in seconds
2589 * @return string JS code fragment
2591 public static function function_call($function, array $arguments = null, $delay=0) {
2592 if ($arguments) {
2593 $arguments = array_map('json_encode', convert_to_array($arguments));
2594 $arguments = implode(', ', $arguments);
2595 } else {
2596 $arguments = '';
2598 $js = "$function($arguments);";
2600 if ($delay) {
2601 $delay = $delay * 1000; // in miliseconds
2602 $js = "setTimeout(function() { $js }, $delay);";
2604 return $js . "\n";
2608 * Special function which adds Y as first argument of function call.
2610 * @param string $function The function to call
2611 * @param array $extraarguments Any arguments to pass to it
2612 * @return string Some JS code
2614 public static function function_call_with_Y($function, array $extraarguments = null) {
2615 if ($extraarguments) {
2616 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
2617 $arguments = 'Y, ' . implode(', ', $extraarguments);
2618 } else {
2619 $arguments = 'Y';
2621 return "$function($arguments);\n";
2625 * Returns JavaScript code to initialise a new object
2627 * @param string $var If it is null then no var is assigned the new object.
2628 * @param string $class The class to initialise an object for.
2629 * @param array $arguments An array of args to pass to the init method.
2630 * @param array $requirements Any modules required for this class.
2631 * @param int $delay The delay before initialisation. 0 = no delay.
2632 * @return string Some JS code
2634 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
2635 if (is_array($arguments)) {
2636 $arguments = array_map('json_encode', convert_to_array($arguments));
2637 $arguments = implode(', ', $arguments);
2640 if ($var === null) {
2641 $js = "new $class(Y, $arguments);";
2642 } else if (strpos($var, '.')!==false) {
2643 $js = "$var = new $class(Y, $arguments);";
2644 } else {
2645 $js = "var $var = new $class(Y, $arguments);";
2648 if ($delay) {
2649 $delay = $delay * 1000; // in miliseconds
2650 $js = "setTimeout(function() { $js }, $delay);";
2653 if (count($requirements) > 0) {
2654 $requirements = implode("', '", $requirements);
2655 $js = "Y.use('$requirements', function(Y){ $js });";
2657 return $js."\n";
2661 * Returns code setting value to variable
2663 * @param string $name
2664 * @param mixed $value json serialised value
2665 * @param bool $usevar add var definition, ignored for nested properties
2666 * @return string JS code fragment
2668 public static function set_variable($name, $value, $usevar = true) {
2669 $output = '';
2671 if ($usevar) {
2672 if (strpos($name, '.')) {
2673 $output .= '';
2674 } else {
2675 $output .= 'var ';
2679 $output .= "$name = ".json_encode($value).";";
2681 return $output;
2685 * Writes event handler attaching code
2687 * @param array|string $selector standard YUI selector for elements, may be
2688 * array or string, element id is in the form "#idvalue"
2689 * @param string $event A valid DOM event (click, mousedown, change etc.)
2690 * @param string $function The name of the function to call
2691 * @param array $arguments An optional array of argument parameters to pass to the function
2692 * @return string JS code fragment
2694 public static function event_handler($selector, $event, $function, array $arguments = null) {
2695 $selector = json_encode($selector);
2696 $output = "Y.on('$event', $function, $selector, null";
2697 if (!empty($arguments)) {
2698 $output .= ', ' . json_encode($arguments);
2700 return $output . ");\n";
2705 * Holds all the information required to render a <table> by {@link core_renderer::table()}
2707 * Example of usage:
2708 * $t = new html_table();
2709 * ... // set various properties of the object $t as described below
2710 * echo html_writer::table($t);
2712 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
2713 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2714 * @since Moodle 2.0
2715 * @package core
2716 * @category output
2718 class html_table {
2721 * @var string Value to use for the id attribute of the table
2723 public $id = null;
2726 * @var array Attributes of HTML attributes for the <table> element
2728 public $attributes = array();
2731 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
2732 * For more control over the rendering of the headers, an array of html_table_cell objects
2733 * can be passed instead of an array of strings.
2735 * Example of usage:
2736 * $t->head = array('Student', 'Grade');
2738 public $head;
2741 * @var array An array that can be used to make a heading span multiple columns.
2742 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
2743 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
2745 * Example of usage:
2746 * $t->headspan = array(2,1);
2748 public $headspan;
2751 * @var array An array of column alignments.
2752 * The value is used as CSS 'text-align' property. Therefore, possible
2753 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
2754 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
2756 * Examples of usage:
2757 * $t->align = array(null, 'right');
2758 * or
2759 * $t->align[1] = 'right';
2761 public $align;
2764 * @var array The value is used as CSS 'size' property.
2766 * Examples of usage:
2767 * $t->size = array('50%', '50%');
2768 * or
2769 * $t->size[1] = '120px';
2771 public $size;
2774 * @var array An array of wrapping information.
2775 * The only possible value is 'nowrap' that sets the
2776 * CSS property 'white-space' to the value 'nowrap' in the given column.
2778 * Example of usage:
2779 * $t->wrap = array(null, 'nowrap');
2781 public $wrap;
2784 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2785 * $head specified, the string 'hr' (for horizontal ruler) can be used
2786 * instead of an array of cells data resulting in a divider rendered.
2788 * Example of usage with array of arrays:
2789 * $row1 = array('Harry Potter', '76 %');
2790 * $row2 = array('Hermione Granger', '100 %');
2791 * $t->data = array($row1, $row2);
2793 * Example with array of html_table_row objects: (used for more fine-grained control)
2794 * $cell1 = new html_table_cell();
2795 * $cell1->text = 'Harry Potter';
2796 * $cell1->colspan = 2;
2797 * $row1 = new html_table_row();
2798 * $row1->cells[] = $cell1;
2799 * $cell2 = new html_table_cell();
2800 * $cell2->text = 'Hermione Granger';
2801 * $cell3 = new html_table_cell();
2802 * $cell3->text = '100 %';
2803 * $row2 = new html_table_row();
2804 * $row2->cells = array($cell2, $cell3);
2805 * $t->data = array($row1, $row2);
2807 public $data = [];
2810 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2811 * @var string Width of the table, percentage of the page preferred.
2813 public $width = null;
2816 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2817 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2819 public $tablealign = null;
2822 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2823 * @var int Padding on each cell, in pixels
2825 public $cellpadding = null;
2828 * @var int Spacing between cells, in pixels
2829 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2831 public $cellspacing = null;
2834 * @var array Array of classes to add to particular rows, space-separated string.
2835 * Class 'lastrow' is added automatically for the last row in the table.
2837 * Example of usage:
2838 * $t->rowclasses[9] = 'tenth'
2840 public $rowclasses;
2843 * @var array An array of classes to add to every cell in a particular column,
2844 * space-separated string. Class 'cell' is added automatically by the renderer.
2845 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2846 * respectively. Class 'lastcol' is added automatically for all last cells
2847 * in a row.
2849 * Example of usage:
2850 * $t->colclasses = array(null, 'grade');
2852 public $colclasses;
2855 * @var string Description of the contents for screen readers.
2857 * The "summary" attribute on the "table" element is not supported in HTML5.
2858 * Consider describing the structure of the table in a "caption" element or in a "figure" element containing the table;
2859 * or, simplify the structure of the table so that no description is needed.
2861 * @deprecated since Moodle 3.9.
2863 public $summary;
2866 * @var string Caption for the table, typically a title.
2868 * Example of usage:
2869 * $t->caption = "TV Guide";
2871 public $caption;
2874 * @var bool Whether to hide the table's caption from sighted users.
2876 * Example of usage:
2877 * $t->caption = "TV Guide";
2878 * $t->captionhide = true;
2880 public $captionhide = false;
2882 /** @var bool Whether to make the table to be scrolled horizontally with ease. Make table responsive across all viewports. */
2883 public $responsive = true;
2885 /** @var string class name to add to this html table. */
2886 public $class;
2889 * Constructor
2891 public function __construct() {
2892 $this->attributes['class'] = '';
2897 * Component representing a table row.
2899 * @copyright 2009 Nicolas Connault
2900 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2901 * @since Moodle 2.0
2902 * @package core
2903 * @category output
2905 class html_table_row {
2908 * @var string Value to use for the id attribute of the row.
2910 public $id = null;
2913 * @var array Array of html_table_cell objects
2915 public $cells = array();
2918 * @var string Value to use for the style attribute of the table row
2920 public $style = null;
2923 * @var array Attributes of additional HTML attributes for the <tr> element
2925 public $attributes = array();
2928 * Constructor
2929 * @param array $cells
2931 public function __construct(array $cells=null) {
2932 $this->attributes['class'] = '';
2933 $cells = (array)$cells;
2934 foreach ($cells as $cell) {
2935 if ($cell instanceof html_table_cell) {
2936 $this->cells[] = $cell;
2937 } else {
2938 $this->cells[] = new html_table_cell($cell);
2945 * Component representing a table cell.
2947 * @copyright 2009 Nicolas Connault
2948 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2949 * @since Moodle 2.0
2950 * @package core
2951 * @category output
2953 class html_table_cell {
2956 * @var string Value to use for the id attribute of the cell.
2958 public $id = null;
2961 * @var string The contents of the cell.
2963 public $text;
2966 * @var string Abbreviated version of the contents of the cell.
2968 public $abbr = null;
2971 * @var int Number of columns this cell should span.
2973 public $colspan = null;
2976 * @var int Number of rows this cell should span.
2978 public $rowspan = null;
2981 * @var string Defines a way to associate header cells and data cells in a table.
2983 public $scope = null;
2986 * @var bool Whether or not this cell is a header cell.
2988 public $header = null;
2991 * @var string Value to use for the style attribute of the table cell
2993 public $style = null;
2996 * @var array Attributes of additional HTML attributes for the <td> element
2998 public $attributes = array();
3001 * Constructs a table cell
3003 * @param string $text
3005 public function __construct($text = null) {
3006 $this->text = $text;
3007 $this->attributes['class'] = '';
3012 * Component representing a paging bar.
3014 * @copyright 2009 Nicolas Connault
3015 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3016 * @since Moodle 2.0
3017 * @package core
3018 * @category output
3020 class paging_bar implements renderable, templatable {
3023 * @var int The maximum number of pagelinks to display.
3025 public $maxdisplay = 18;
3028 * @var int The total number of entries to be pages through..
3030 public $totalcount;
3033 * @var int The page you are currently viewing.
3035 public $page;
3038 * @var int The number of entries that should be shown per page.
3040 public $perpage;
3043 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
3044 * an equals sign and the page number.
3045 * If this is a moodle_url object then the pagevar param will be replaced by
3046 * the page no, for each page.
3048 public $baseurl;
3051 * @var string This is the variable name that you use for the pagenumber in your
3052 * code (ie. 'tablepage', 'blogpage', etc)
3054 public $pagevar;
3057 * @var string A HTML link representing the "previous" page.
3059 public $previouslink = null;
3062 * @var string A HTML link representing the "next" page.
3064 public $nextlink = null;
3067 * @var string A HTML link representing the first page.
3069 public $firstlink = null;
3072 * @var string A HTML link representing the last page.
3074 public $lastlink = null;
3077 * @var array An array of strings. One of them is just a string: the current page
3079 public $pagelinks = array();
3082 * Constructor paging_bar with only the required params.
3084 * @param int $totalcount The total number of entries available to be paged through
3085 * @param int $page The page you are currently viewing
3086 * @param int $perpage The number of entries that should be shown per page
3087 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3088 * @param string $pagevar name of page parameter that holds the page number
3090 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3091 $this->totalcount = $totalcount;
3092 $this->page = $page;
3093 $this->perpage = $perpage;
3094 $this->baseurl = $baseurl;
3095 $this->pagevar = $pagevar;
3099 * Prepares the paging bar for output.
3101 * This method validates the arguments set up for the paging bar and then
3102 * produces fragments of HTML to assist display later on.
3104 * @param renderer_base $output
3105 * @param moodle_page $page
3106 * @param string $target
3107 * @throws coding_exception
3109 public function prepare(renderer_base $output, moodle_page $page, $target) {
3110 if (!isset($this->totalcount) || is_null($this->totalcount)) {
3111 throw new coding_exception('paging_bar requires a totalcount value.');
3113 if (!isset($this->page) || is_null($this->page)) {
3114 throw new coding_exception('paging_bar requires a page value.');
3116 if (empty($this->perpage)) {
3117 throw new coding_exception('paging_bar requires a perpage value.');
3119 if (empty($this->baseurl)) {
3120 throw new coding_exception('paging_bar requires a baseurl value.');
3123 if ($this->totalcount > $this->perpage) {
3124 $pagenum = $this->page - 1;
3126 if ($this->page > 0) {
3127 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
3130 if ($this->perpage > 0) {
3131 $lastpage = ceil($this->totalcount / $this->perpage);
3132 } else {
3133 $lastpage = 1;
3136 if ($this->page > round(($this->maxdisplay/3)*2)) {
3137 $currpage = $this->page - round($this->maxdisplay/3);
3139 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
3140 } else {
3141 $currpage = 0;
3144 $displaycount = $displaypage = 0;
3146 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3147 $displaypage = $currpage + 1;
3149 if ($this->page == $currpage) {
3150 $this->pagelinks[] = html_writer::span($displaypage, 'current-page');
3151 } else {
3152 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
3153 $this->pagelinks[] = $pagelink;
3156 $displaycount++;
3157 $currpage++;
3160 if ($currpage < $lastpage) {
3161 $lastpageactual = $lastpage - 1;
3162 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
3165 $pagenum = $this->page + 1;
3167 if ($pagenum != $lastpage) {
3168 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
3174 * Export for template.
3176 * @param renderer_base $output The renderer.
3177 * @return stdClass
3179 public function export_for_template(renderer_base $output) {
3180 $data = new stdClass();
3181 $data->previous = null;
3182 $data->next = null;
3183 $data->first = null;
3184 $data->last = null;
3185 $data->label = get_string('page');
3186 $data->pages = [];
3187 $data->haspages = $this->totalcount > $this->perpage;
3188 $data->pagesize = $this->perpage;
3190 if (!$data->haspages) {
3191 return $data;
3194 if ($this->page > 0) {
3195 $data->previous = [
3196 'page' => $this->page,
3197 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page - 1]))->out(false)
3201 $currpage = 0;
3202 if ($this->page > round(($this->maxdisplay / 3) * 2)) {
3203 $currpage = $this->page - round($this->maxdisplay / 3);
3204 $data->first = [
3205 'page' => 1,
3206 'url' => (new moodle_url($this->baseurl, [$this->pagevar => 0]))->out(false)
3210 $lastpage = 1;
3211 if ($this->perpage > 0) {
3212 $lastpage = ceil($this->totalcount / $this->perpage);
3215 $displaycount = 0;
3216 $displaypage = 0;
3217 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3218 $displaypage = $currpage + 1;
3220 $iscurrent = $this->page == $currpage;
3221 $link = new moodle_url($this->baseurl, [$this->pagevar => $currpage]);
3223 $data->pages[] = [
3224 'page' => $displaypage,
3225 'active' => $iscurrent,
3226 'url' => $iscurrent ? null : $link->out(false)
3229 $displaycount++;
3230 $currpage++;
3233 if ($currpage < $lastpage) {
3234 $data->last = [
3235 'page' => $lastpage,
3236 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $lastpage - 1]))->out(false)
3240 if ($this->page + 1 != $lastpage) {
3241 $data->next = [
3242 'page' => $this->page + 2,
3243 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page + 1]))->out(false)
3247 return $data;
3252 * Component representing initials bar.
3254 * @copyright 2017 Ilya Tregubov
3255 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3256 * @since Moodle 3.3
3257 * @package core
3258 * @category output
3260 class initials_bar implements renderable, templatable {
3263 * @var string Currently selected letter.
3265 public $current;
3268 * @var string Class name to add to this initial bar.
3270 public $class;
3273 * @var string The name to put in front of this initial bar.
3275 public $title;
3278 * @var string URL parameter name for this initial.
3280 public $urlvar;
3283 * @var moodle_url URL object.
3285 public $url;
3288 * @var array An array of letters in the alphabet.
3290 public $alpha;
3293 * @var bool Omit links if we are doing a mini render.
3295 public $minirender;
3298 * Constructor initials_bar with only the required params.
3300 * @param string $current the currently selected letter.
3301 * @param string $class class name to add to this initial bar.
3302 * @param string $title the name to put in front of this initial bar.
3303 * @param string $urlvar URL parameter name for this initial.
3304 * @param string $url URL object.
3305 * @param array $alpha of letters in the alphabet.
3306 * @param bool $minirender Return a trimmed down view of the initials bar.
3308 public function __construct($current, $class, $title, $urlvar, $url, $alpha = null, bool $minirender = false) {
3309 $this->current = $current;
3310 $this->class = $class;
3311 $this->title = $title;
3312 $this->urlvar = $urlvar;
3313 $this->url = $url;
3314 $this->alpha = $alpha;
3315 $this->minirender = $minirender;
3319 * Export for template.
3321 * @param renderer_base $output The renderer.
3322 * @return stdClass
3324 public function export_for_template(renderer_base $output) {
3325 $data = new stdClass();
3327 if ($this->alpha == null) {
3328 $this->alpha = explode(',', get_string('alphabet', 'langconfig'));
3331 if ($this->current == 'all') {
3332 $this->current = '';
3335 // We want to find a letter grouping size which suits the language so
3336 // find the largest group size which is less than 15 chars.
3337 // The choice of 15 chars is the largest number of chars that reasonably
3338 // fits on the smallest supported screen size. By always using a max number
3339 // of groups which is a factor of 2, we always get nice wrapping, and the
3340 // last row is always the shortest.
3341 $groupsize = count($this->alpha);
3342 $groups = 1;
3343 while ($groupsize > 15) {
3344 $groups *= 2;
3345 $groupsize = ceil(count($this->alpha) / $groups);
3348 $groupsizelimit = 0;
3349 $groupnumber = 0;
3350 foreach ($this->alpha as $letter) {
3351 if ($groupsizelimit++ > 0 && $groupsizelimit % $groupsize == 1) {
3352 $groupnumber++;
3354 $groupletter = new stdClass();
3355 $groupletter->name = $letter;
3356 if (!$this->minirender) {
3357 $groupletter->url = $this->url->out(false, array($this->urlvar => $letter));
3358 } else {
3359 $groupletter->input = $letter;
3361 if ($letter == $this->current) {
3362 $groupletter->selected = $this->current;
3364 if (!isset($data->group[$groupnumber])) {
3365 $data->group[$groupnumber] = new stdClass();
3367 $data->group[$groupnumber]->letter[] = $groupletter;
3370 $data->class = $this->class;
3371 $data->title = $this->title;
3372 if (!$this->minirender) {
3373 $data->url = $this->url->out(false, array($this->urlvar => ''));
3374 } else {
3375 $data->input = 'ALL';
3377 $data->current = $this->current;
3378 $data->all = get_string('all');
3380 return $data;
3385 * This class represents how a block appears on a page.
3387 * During output, each block instance is asked to return a block_contents object,
3388 * those are then passed to the $OUTPUT->block function for display.
3390 * contents should probably be generated using a moodle_block_..._renderer.
3392 * Other block-like things that need to appear on the page, for example the
3393 * add new block UI, are also represented as block_contents objects.
3395 * @copyright 2009 Tim Hunt
3396 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3397 * @since Moodle 2.0
3398 * @package core
3399 * @category output
3401 class block_contents {
3403 /** Used when the block cannot be collapsed **/
3404 const NOT_HIDEABLE = 0;
3406 /** Used when the block can be collapsed but currently is not **/
3407 const VISIBLE = 1;
3409 /** Used when the block has been collapsed **/
3410 const HIDDEN = 2;
3413 * @var int Used to set $skipid.
3415 protected static $idcounter = 1;
3418 * @var int All the blocks (or things that look like blocks) printed on
3419 * a page are given a unique number that can be used to construct id="" attributes.
3420 * This is set automatically be the {@link prepare()} method.
3421 * Do not try to set it manually.
3423 public $skipid;
3426 * @var int If this is the contents of a real block, this should be set
3427 * to the block_instance.id. Otherwise this should be set to 0.
3429 public $blockinstanceid = 0;
3432 * @var int If this is a real block instance, and there is a corresponding
3433 * block_position.id for the block on this page, this should be set to that id.
3434 * Otherwise it should be 0.
3436 public $blockpositionid = 0;
3439 * @var array An array of attribute => value pairs that are put on the outer div of this
3440 * block. {@link $id} and {@link $classes} attributes should be set separately.
3442 public $attributes;
3445 * @var string The title of this block. If this came from user input, it should already
3446 * have had format_string() processing done on it. This will be output inside
3447 * <h2> tags. Please do not cause invalid XHTML.
3449 public $title = '';
3452 * @var string The label to use when the block does not, or will not have a visible title.
3453 * You should never set this as well as title... it will just be ignored.
3455 public $arialabel = '';
3458 * @var string HTML for the content
3460 public $content = '';
3463 * @var array An alternative to $content, it you want a list of things with optional icons.
3465 public $footer = '';
3468 * @var string Any small print that should appear under the block to explain
3469 * to the teacher about the block, for example 'This is a sticky block that was
3470 * added in the system context.'
3472 public $annotation = '';
3475 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
3476 * the user can toggle whether this block is visible.
3478 public $collapsible = self::NOT_HIDEABLE;
3481 * Set this to true if the block is dockable.
3482 * @var bool
3484 public $dockable = false;
3487 * @var array A (possibly empty) array of editing controls. Each element of
3488 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
3489 * $icon is the icon name. Fed to $OUTPUT->image_url.
3491 public $controls = array();
3495 * Create new instance of block content
3496 * @param array $attributes
3498 public function __construct(array $attributes = null) {
3499 $this->skipid = self::$idcounter;
3500 self::$idcounter += 1;
3502 if ($attributes) {
3503 // standard block
3504 $this->attributes = $attributes;
3505 } else {
3506 // simple "fake" blocks used in some modules and "Add new block" block
3507 $this->attributes = array('class'=>'block');
3512 * Add html class to block
3514 * @param string $class
3516 public function add_class($class) {
3517 $this->attributes['class'] .= ' '.$class;
3521 * Check if the block is a fake block.
3523 * @return boolean
3525 public function is_fake() {
3526 return isset($this->attributes['data-block']) && $this->attributes['data-block'] == '_fake';
3532 * This class represents a target for where a block can go when it is being moved.
3534 * This needs to be rendered as a form with the given hidden from fields, and
3535 * clicking anywhere in the form should submit it. The form action should be
3536 * $PAGE->url.
3538 * @copyright 2009 Tim Hunt
3539 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3540 * @since Moodle 2.0
3541 * @package core
3542 * @category output
3544 class block_move_target {
3547 * @var moodle_url Move url
3549 public $url;
3552 * Constructor
3553 * @param moodle_url $url
3555 public function __construct(moodle_url $url) {
3556 $this->url = $url;
3561 * Custom menu item
3563 * This class is used to represent one item within a custom menu that may or may
3564 * not have children.
3566 * @copyright 2010 Sam Hemelryk
3567 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3568 * @since Moodle 2.0
3569 * @package core
3570 * @category output
3572 class custom_menu_item implements renderable, templatable {
3575 * @var string The text to show for the item
3577 protected $text;
3580 * @var moodle_url The link to give the icon if it has no children
3582 protected $url;
3585 * @var string A title to apply to the item. By default the text
3587 protected $title;
3590 * @var int A sort order for the item, not necessary if you order things in
3591 * the CFG var.
3593 protected $sort;
3596 * @var custom_menu_item A reference to the parent for this item or NULL if
3597 * it is a top level item
3599 protected $parent;
3602 * @var array A array in which to store children this item has.
3604 protected $children = array();
3607 * @var int A reference to the sort var of the last child that was added
3609 protected $lastsort = 0;
3611 /** @var array Array of other HTML attributes for the custom menu item. */
3612 protected $attributes = [];
3615 * Constructs the new custom menu item
3617 * @param string $text
3618 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
3619 * @param string $title A title to apply to this item [Optional]
3620 * @param int $sort A sort or to use if we need to sort differently [Optional]
3621 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
3622 * belongs to, only if the child has a parent. [Optional]
3623 * @param array $attributes Array of other HTML attributes for the custom menu item.
3625 public function __construct($text, moodle_url $url = null, $title = null, $sort = null, custom_menu_item $parent = null,
3626 array $attributes = []) {
3628 // Use class setter method for text to ensure it's always a string type.
3629 $this->set_text($text);
3631 $this->url = $url;
3632 $this->title = $title;
3633 $this->sort = (int)$sort;
3634 $this->parent = $parent;
3635 $this->attributes = $attributes;
3639 * Adds a custom menu item as a child of this node given its properties.
3641 * @param string $text
3642 * @param moodle_url $url
3643 * @param string $title
3644 * @param int $sort
3645 * @param array $attributes Array of other HTML attributes for the custom menu item.
3646 * @return custom_menu_item
3648 public function add($text, moodle_url $url = null, $title = null, $sort = null, $attributes = []) {
3649 $key = count($this->children);
3650 if (empty($sort)) {
3651 $sort = $this->lastsort + 1;
3653 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this, $attributes);
3654 $this->lastsort = (int)$sort;
3655 return $this->children[$key];
3659 * Removes a custom menu item that is a child or descendant to the current menu.
3661 * Returns true if child was found and removed.
3663 * @param custom_menu_item $menuitem
3664 * @return bool
3666 public function remove_child(custom_menu_item $menuitem) {
3667 $removed = false;
3668 if (($key = array_search($menuitem, $this->children)) !== false) {
3669 unset($this->children[$key]);
3670 $this->children = array_values($this->children);
3671 $removed = true;
3672 } else {
3673 foreach ($this->children as $child) {
3674 if ($removed = $child->remove_child($menuitem)) {
3675 break;
3679 return $removed;
3683 * Returns the text for this item
3684 * @return string
3686 public function get_text() {
3687 return $this->text;
3691 * Returns the url for this item
3692 * @return moodle_url
3694 public function get_url() {
3695 return $this->url;
3699 * Returns the title for this item
3700 * @return string
3702 public function get_title() {
3703 return $this->title;
3707 * Sorts and returns the children for this item
3708 * @return array
3710 public function get_children() {
3711 $this->sort();
3712 return $this->children;
3716 * Gets the sort order for this child
3717 * @return int
3719 public function get_sort_order() {
3720 return $this->sort;
3724 * Gets the parent this child belong to
3725 * @return custom_menu_item
3727 public function get_parent() {
3728 return $this->parent;
3732 * Sorts the children this item has
3734 public function sort() {
3735 usort($this->children, array('custom_menu','sort_custom_menu_items'));
3739 * Returns true if this item has any children
3740 * @return bool
3742 public function has_children() {
3743 return (count($this->children) > 0);
3747 * Sets the text for the node
3748 * @param string $text
3750 public function set_text($text) {
3751 $this->text = (string)$text;
3755 * Sets the title for the node
3756 * @param string $title
3758 public function set_title($title) {
3759 $this->title = (string)$title;
3763 * Sets the url for the node
3764 * @param moodle_url $url
3766 public function set_url(moodle_url $url) {
3767 $this->url = $url;
3771 * Export this data so it can be used as the context for a mustache template.
3773 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
3774 * @return array
3776 public function export_for_template(renderer_base $output) {
3777 $syscontext = context_system::instance();
3779 $context = new stdClass();
3780 $context->moremenuid = uniqid();
3781 $context->text = \core_external\util::format_string($this->text, $syscontext->id);
3782 $context->url = $this->url ? $this->url->out() : null;
3783 // No need for the title if it's the same with text.
3784 if ($this->text !== $this->title) {
3785 // Show the title attribute only if it's different from the text.
3786 $context->title = \core_external\util::format_string($this->title, $syscontext->id);
3788 $context->sort = $this->sort;
3789 if (!empty($this->attributes)) {
3790 $context->attributes = $this->attributes;
3792 $context->children = array();
3793 if (preg_match("/^#+$/", $this->text)) {
3794 $context->divider = true;
3796 $context->haschildren = !empty($this->children) && (count($this->children) > 0);
3797 foreach ($this->children as $child) {
3798 $child = $child->export_for_template($output);
3799 array_push($context->children, $child);
3802 return $context;
3807 * Custom menu class
3809 * This class is used to operate a custom menu that can be rendered for the page.
3810 * The custom menu is built using $CFG->custommenuitems and is a structured collection
3811 * of custom_menu_item nodes that can be rendered by the core renderer.
3813 * To configure the custom menu:
3814 * Settings: Administration > Appearance > Advanced theme settings
3816 * @copyright 2010 Sam Hemelryk
3817 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3818 * @since Moodle 2.0
3819 * @package core
3820 * @category output
3822 class custom_menu extends custom_menu_item {
3825 * @var string The language we should render for, null disables multilang support.
3827 protected $currentlanguage = null;
3830 * Creates the custom menu
3832 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
3833 * @param string $currentlanguage the current language code, null disables multilang support
3835 public function __construct($definition = '', $currentlanguage = null) {
3836 $this->currentlanguage = $currentlanguage;
3837 parent::__construct('root'); // create virtual root element of the menu
3838 if (!empty($definition)) {
3839 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
3844 * Overrides the children of this custom menu. Useful when getting children
3845 * from $CFG->custommenuitems
3847 * @param array $children
3849 public function override_children(array $children) {
3850 $this->children = array();
3851 foreach ($children as $child) {
3852 if ($child instanceof custom_menu_item) {
3853 $this->children[] = $child;
3859 * Converts a string into a structured array of custom_menu_items which can
3860 * then be added to a custom menu.
3862 * Structure:
3863 * text|url|title|langs
3864 * The number of hyphens at the start determines the depth of the item. The
3865 * languages are optional, comma separated list of languages the line is for.
3867 * Example structure:
3868 * First level first item|http://www.moodle.com/
3869 * -Second level first item|http://www.moodle.com/partners/
3870 * -Second level second item|http://www.moodle.com/hq/
3871 * --Third level first item|http://www.moodle.com/jobs/
3872 * -Second level third item|http://www.moodle.com/development/
3873 * First level second item|http://www.moodle.com/feedback/
3874 * First level third item
3875 * English only|http://moodle.com|English only item|en
3876 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
3879 * @static
3880 * @param string $text the menu items definition
3881 * @param string $language the language code, null disables multilang support
3882 * @return array
3884 public static function convert_text_to_menu_nodes($text, $language = null) {
3885 $root = new custom_menu();
3886 $lastitem = $root;
3887 $lastdepth = 0;
3888 $hiddenitems = array();
3889 $lines = explode("\n", $text);
3890 foreach ($lines as $linenumber => $line) {
3891 $line = trim($line);
3892 if (strlen($line) == 0) {
3893 continue;
3895 // Parse item settings.
3896 $itemtext = null;
3897 $itemurl = null;
3898 $itemtitle = null;
3899 $itemvisible = true;
3900 $settings = explode('|', $line);
3901 foreach ($settings as $i => $setting) {
3902 $setting = trim($setting);
3903 if ($setting !== '') {
3904 switch ($i) {
3905 case 0: // Menu text.
3906 $itemtext = ltrim($setting, '-');
3907 break;
3908 case 1: // URL.
3909 try {
3910 $itemurl = new moodle_url($setting);
3911 } catch (moodle_exception $exception) {
3912 // We're not actually worried about this, we don't want to mess up the display
3913 // just for a wrongly entered URL.
3914 $itemurl = null;
3916 break;
3917 case 2: // Title attribute.
3918 $itemtitle = $setting;
3919 break;
3920 case 3: // Language.
3921 if (!empty($language)) {
3922 $itemlanguages = array_map('trim', explode(',', $setting));
3923 $itemvisible &= in_array($language, $itemlanguages);
3925 break;
3929 // Get depth of new item.
3930 preg_match('/^(\-*)/', $line, $match);
3931 $itemdepth = strlen($match[1]) + 1;
3932 // Find parent item for new item.
3933 while (($lastdepth - $itemdepth) >= 0) {
3934 $lastitem = $lastitem->get_parent();
3935 $lastdepth--;
3937 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1);
3938 $lastdepth++;
3939 if (!$itemvisible) {
3940 $hiddenitems[] = $lastitem;
3943 foreach ($hiddenitems as $item) {
3944 $item->parent->remove_child($item);
3946 return $root->get_children();
3950 * Sorts two custom menu items
3952 * This function is designed to be used with the usort method
3953 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
3955 * @static
3956 * @param custom_menu_item $itema
3957 * @param custom_menu_item $itemb
3958 * @return int
3960 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
3961 $itema = $itema->get_sort_order();
3962 $itemb = $itemb->get_sort_order();
3963 if ($itema == $itemb) {
3964 return 0;
3966 return ($itema > $itemb) ? +1 : -1;
3971 * Stores one tab
3973 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3974 * @package core
3976 class tabobject implements renderable, templatable {
3977 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
3978 var $id;
3979 /** @var moodle_url|string link */
3980 var $link;
3981 /** @var string text on the tab */
3982 var $text;
3983 /** @var string title under the link, by defaul equals to text */
3984 var $title;
3985 /** @var bool whether to display a link under the tab name when it's selected */
3986 var $linkedwhenselected = false;
3987 /** @var bool whether the tab is inactive */
3988 var $inactive = false;
3989 /** @var bool indicates that this tab's child is selected */
3990 var $activated = false;
3991 /** @var bool indicates that this tab is selected */
3992 var $selected = false;
3993 /** @var array stores children tabobjects */
3994 var $subtree = array();
3995 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
3996 var $level = 1;
3999 * Constructor
4001 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
4002 * @param string|moodle_url $link
4003 * @param string $text text on the tab
4004 * @param string $title title under the link, by defaul equals to text
4005 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
4007 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
4008 $this->id = $id;
4009 $this->link = $link;
4010 $this->text = $text;
4011 $this->title = $title ? $title : $text;
4012 $this->linkedwhenselected = $linkedwhenselected;
4016 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
4018 * @param string $selected the id of the selected tab (whatever row it's on),
4019 * if null marks all tabs as unselected
4020 * @return bool whether this tab is selected or contains selected tab in its subtree
4022 protected function set_selected($selected) {
4023 if ((string)$selected === (string)$this->id) {
4024 $this->selected = true;
4025 // This tab is selected. No need to travel through subtree.
4026 return true;
4028 foreach ($this->subtree as $subitem) {
4029 if ($subitem->set_selected($selected)) {
4030 // This tab has child that is selected. Mark it as activated. No need to check other children.
4031 $this->activated = true;
4032 return true;
4035 return false;
4039 * Travels through tree and finds a tab with specified id
4041 * @param string $id
4042 * @return tabtree|null
4044 public function find($id) {
4045 if ((string)$this->id === (string)$id) {
4046 return $this;
4048 foreach ($this->subtree as $tab) {
4049 if ($obj = $tab->find($id)) {
4050 return $obj;
4053 return null;
4057 * Allows to mark each tab's level in the tree before rendering.
4059 * @param int $level
4061 protected function set_level($level) {
4062 $this->level = $level;
4063 foreach ($this->subtree as $tab) {
4064 $tab->set_level($level + 1);
4069 * Export for template.
4071 * @param renderer_base $output Renderer.
4072 * @return object
4074 public function export_for_template(renderer_base $output) {
4075 if ($this->inactive || ($this->selected && !$this->linkedwhenselected) || $this->activated) {
4076 $link = null;
4077 } else {
4078 $link = $this->link;
4080 $active = $this->activated || $this->selected;
4082 return (object) [
4083 'id' => $this->id,
4084 'link' => is_object($link) ? $link->out(false) : $link,
4085 'text' => $this->text,
4086 'title' => $this->title,
4087 'inactive' => !$active && $this->inactive,
4088 'active' => $active,
4089 'level' => $this->level,
4096 * Renderable for the main page header.
4098 * @package core
4099 * @category output
4100 * @since 2.9
4101 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
4102 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4104 class context_header implements renderable {
4107 * @var string $heading Main heading.
4109 public $heading;
4111 * @var int $headinglevel Main heading 'h' tag level.
4113 public $headinglevel;
4115 * @var string|null $imagedata HTML code for the picture in the page header.
4117 public $imagedata;
4119 * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
4120 * array elements - title => alternate text for the image, or if no image is available the button text.
4121 * url => Link for the button to head to. Should be a moodle_url.
4122 * image => location to the image, or name of the image in /pix/t/{image name}.
4123 * linkattributes => additional attributes for the <a href> element.
4124 * page => page object. Don't include if the image is an external image.
4126 public $additionalbuttons;
4128 * @var string $prefix A string that is before the title.
4130 public $prefix;
4133 * Constructor.
4135 * @param string $heading Main heading data.
4136 * @param int $headinglevel Main heading 'h' tag level.
4137 * @param string|null $imagedata HTML code for the picture in the page header.
4138 * @param string $additionalbuttons Buttons for the header e.g. Messaging button for the user header.
4139 * @param string $prefix Text that precedes the heading.
4141 public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null, $prefix = null) {
4143 $this->heading = $heading;
4144 $this->headinglevel = $headinglevel;
4145 $this->imagedata = $imagedata;
4146 $this->additionalbuttons = $additionalbuttons;
4147 // If we have buttons then format them.
4148 if (isset($this->additionalbuttons)) {
4149 $this->format_button_images();
4151 $this->prefix = $prefix;
4155 * Adds an array element for a formatted image.
4157 protected function format_button_images() {
4159 foreach ($this->additionalbuttons as $buttontype => $button) {
4160 $page = $button['page'];
4161 // If no image is provided then just use the title.
4162 if (!isset($button['image'])) {
4163 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['title'];
4164 } else {
4165 // Check to see if this is an internal Moodle icon.
4166 $internalimage = $page->theme->resolve_image_location('t/' . $button['image'], 'moodle');
4167 if ($internalimage) {
4168 $this->additionalbuttons[$buttontype]['formattedimage'] = 't/' . $button['image'];
4169 } else {
4170 // Treat as an external image.
4171 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['image'];
4175 if (isset($button['linkattributes']['class'])) {
4176 $class = $button['linkattributes']['class'] . ' btn';
4177 } else {
4178 $class = 'btn';
4180 // Add the bootstrap 'btn' class for formatting.
4181 $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
4182 array('class' => $class));
4188 * Stores tabs list
4190 * Example how to print a single line tabs:
4191 * $rows = array(
4192 * new tabobject(...),
4193 * new tabobject(...)
4194 * );
4195 * echo $OUTPUT->tabtree($rows, $selectedid);
4197 * Multiple row tabs may not look good on some devices but if you want to use them
4198 * you can specify ->subtree for the active tabobject.
4200 * @copyright 2013 Marina Glancy
4201 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4202 * @since Moodle 2.5
4203 * @package core
4204 * @category output
4206 class tabtree extends tabobject {
4208 * Constuctor
4210 * It is highly recommended to call constructor when list of tabs is already
4211 * populated, this way you ensure that selected and inactive tabs are located
4212 * and attribute level is set correctly.
4214 * @param array $tabs array of tabs, each of them may have it's own ->subtree
4215 * @param string|null $selected which tab to mark as selected, all parent tabs will
4216 * automatically be marked as activated
4217 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4218 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
4220 public function __construct($tabs, $selected = null, $inactive = null) {
4221 $this->subtree = $tabs;
4222 if ($selected !== null) {
4223 $this->set_selected($selected);
4225 if ($inactive !== null) {
4226 if (is_array($inactive)) {
4227 foreach ($inactive as $id) {
4228 if ($tab = $this->find($id)) {
4229 $tab->inactive = true;
4232 } else if ($tab = $this->find($inactive)) {
4233 $tab->inactive = true;
4236 $this->set_level(0);
4240 * Export for template.
4242 * @param renderer_base $output Renderer.
4243 * @return object
4245 public function export_for_template(renderer_base $output) {
4246 $tabs = [];
4247 $secondrow = false;
4249 foreach ($this->subtree as $tab) {
4250 $tabs[] = $tab->export_for_template($output);
4251 if (!empty($tab->subtree) && ($tab->level == 0 || $tab->selected || $tab->activated)) {
4252 $secondrow = new tabtree($tab->subtree);
4256 return (object) [
4257 'tabs' => $tabs,
4258 'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false
4264 * An action menu.
4266 * This action menu component takes a series of primary and secondary actions.
4267 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
4268 * down menu.
4270 * @package core
4271 * @category output
4272 * @copyright 2013 Sam Hemelryk
4273 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4275 class action_menu implements renderable, templatable {
4278 * Top right alignment.
4280 const TL = 1;
4283 * Top right alignment.
4285 const TR = 2;
4288 * Top right alignment.
4290 const BL = 3;
4293 * Top right alignment.
4295 const BR = 4;
4298 * The instance number. This is unique to this instance of the action menu.
4299 * @var int
4301 protected $instance = 0;
4304 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
4305 * @var array
4307 protected $primaryactions = array();
4310 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
4311 * @var array
4313 protected $secondaryactions = array();
4316 * An array of attributes added to the container of the action menu.
4317 * Initialised with defaults during construction.
4318 * @var array
4320 public $attributes = array();
4322 * An array of attributes added to the container of the primary actions.
4323 * Initialised with defaults during construction.
4324 * @var array
4326 public $attributesprimary = array();
4328 * An array of attributes added to the container of the secondary actions.
4329 * Initialised with defaults during construction.
4330 * @var array
4332 public $attributessecondary = array();
4335 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
4336 * @var array
4338 public $actiontext = null;
4341 * The string to use for the accessible label for the menu.
4342 * @var array
4344 public $actionlabel = null;
4347 * An icon to use for the toggling the secondary menu (dropdown).
4348 * @var pix_icon
4350 public $actionicon;
4353 * Any text to use for the toggling the secondary menu (dropdown).
4354 * @var string
4356 public $menutrigger = '';
4359 * An array of attributes added to the trigger element of the secondary menu.
4360 * @var array
4362 public $triggerattributes = [];
4365 * Any extra classes for toggling to the secondary menu.
4366 * @var string
4368 public $triggerextraclasses = '';
4371 * Place the action menu before all other actions.
4372 * @var bool
4374 public $prioritise = false;
4377 * Dropdown menu alignment class.
4378 * @var string
4380 public $dropdownalignment = '';
4383 * Constructs the action menu with the given items.
4385 * @param array $actions An array of actions (action_menu_link|pix_icon|string).
4387 public function __construct(array $actions = array()) {
4388 static $initialised = 0;
4389 $this->instance = $initialised;
4390 $initialised++;
4392 $this->attributes = array(
4393 'id' => 'action-menu-'.$this->instance,
4394 'class' => 'moodle-actionmenu',
4395 'data-enhance' => 'moodle-core-actionmenu'
4397 $this->attributesprimary = array(
4398 'id' => 'action-menu-'.$this->instance.'-menubar',
4399 'class' => 'menubar',
4401 $this->attributessecondary = array(
4402 'id' => 'action-menu-'.$this->instance.'-menu',
4403 'class' => 'menu',
4404 'data-rel' => 'menu-content',
4405 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
4406 'role' => 'menu'
4408 $this->dropdownalignment = 'dropdown-menu-right';
4409 foreach ($actions as $action) {
4410 $this->add($action);
4415 * Sets the label for the menu trigger.
4417 * @param string $label The text
4419 public function set_action_label($label) {
4420 $this->actionlabel = $label;
4424 * Sets the menu trigger text.
4426 * @param string $trigger The text
4427 * @param string $extraclasses Extra classes to style the secondary menu toggle.
4429 public function set_menu_trigger($trigger, $extraclasses = '') {
4430 $this->menutrigger = $trigger;
4431 $this->triggerextraclasses = $extraclasses;
4435 * Classes for the trigger menu
4437 const DEFAULT_KEBAB_TRIGGER_CLASSES = 'btn btn-icon d-flex align-items-center justify-content-center no-caret';
4440 * Setup trigger as in the kebab menu.
4442 * @param string|null $triggername
4443 * @param core_renderer|null $output
4444 * @param string|null $extraclasses extra classes for the trigger {@see self::set_menu_trigger()}
4445 * @throws coding_exception
4447 public function set_kebab_trigger(?string $triggername = null, ?core_renderer $output = null,
4448 ?string $extraclasses = '') {
4449 global $OUTPUT;
4450 if (empty($output)) {
4451 $output = $OUTPUT;
4453 $label = $triggername ?? get_string('actions');
4454 $triggerclasses = self::DEFAULT_KEBAB_TRIGGER_CLASSES . ' ' . $extraclasses;
4455 $icon = $output->pix_icon('i/menu', $label);
4456 $this->set_menu_trigger($icon, $triggerclasses);
4460 * Return true if there is at least one visible link in the menu.
4462 * @return bool
4464 public function is_empty() {
4465 return !count($this->primaryactions) && !count($this->secondaryactions);
4469 * Initialises JS required fore the action menu.
4470 * The JS is only required once as it manages all action menu's on the page.
4472 * @param moodle_page $page
4474 public function initialise_js(moodle_page $page) {
4475 static $initialised = false;
4476 if (!$initialised) {
4477 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
4478 $initialised = true;
4483 * Adds an action to this action menu.
4485 * @param action_menu_link|pix_icon|subpanel|string $action
4487 public function add($action) {
4489 if ($action instanceof subpanel) {
4490 $this->add_secondary_subpanel($action);
4491 } else if ($action instanceof action_link) {
4492 if ($action->primary) {
4493 $this->add_primary_action($action);
4494 } else {
4495 $this->add_secondary_action($action);
4497 } else if ($action instanceof pix_icon) {
4498 $this->add_primary_action($action);
4499 } else {
4500 $this->add_secondary_action($action);
4505 * Adds a secondary subpanel.
4506 * @param subpanel $subpanel
4508 public function add_secondary_subpanel(subpanel $subpanel) {
4509 $this->secondaryactions[] = $subpanel;
4513 * Adds a primary action to the action menu.
4515 * @param action_menu_link|action_link|pix_icon|string $action
4517 public function add_primary_action($action) {
4518 if ($action instanceof action_link || $action instanceof pix_icon) {
4519 $action->attributes['role'] = 'menuitem';
4520 $action->attributes['tabindex'] = '-1';
4521 if ($action instanceof action_menu_link) {
4522 $action->actionmenu = $this;
4525 $this->primaryactions[] = $action;
4529 * Adds a secondary action to the action menu.
4531 * @param action_link|pix_icon|string $action
4533 public function add_secondary_action($action) {
4534 if ($action instanceof action_link || $action instanceof pix_icon) {
4535 $action->attributes['role'] = 'menuitem';
4536 $action->attributes['tabindex'] = '-1';
4537 if ($action instanceof action_menu_link) {
4538 $action->actionmenu = $this;
4541 $this->secondaryactions[] = $action;
4545 * Returns the primary actions ready to be rendered.
4547 * @param core_renderer $output The renderer to use for getting icons.
4548 * @return array
4550 public function get_primary_actions(core_renderer $output = null) {
4551 global $OUTPUT;
4552 if ($output === null) {
4553 $output = $OUTPUT;
4555 $pixicon = $this->actionicon;
4556 $linkclasses = array('toggle-display');
4558 $title = '';
4559 if (!empty($this->menutrigger)) {
4560 $pixicon = '<b class="caret"></b>';
4561 $linkclasses[] = 'textmenu';
4562 } else {
4563 $title = new lang_string('actionsmenu', 'moodle');
4564 $this->actionicon = new pix_icon(
4565 't/edit_menu',
4567 'moodle',
4568 array('class' => 'iconsmall actionmenu', 'title' => '')
4570 $pixicon = $this->actionicon;
4572 if ($pixicon instanceof renderable) {
4573 $pixicon = $output->render($pixicon);
4574 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
4575 $title = $pixicon->attributes['alt'];
4578 $string = '';
4579 if ($this->actiontext) {
4580 $string = $this->actiontext;
4582 $label = '';
4583 if ($this->actionlabel) {
4584 $label = $this->actionlabel;
4585 } else {
4586 $label = $title;
4588 $actions = $this->primaryactions;
4589 $attributes = array(
4590 'class' => implode(' ', $linkclasses),
4591 'title' => $title,
4592 'aria-label' => $label,
4593 'id' => 'action-menu-toggle-'.$this->instance,
4594 'role' => 'menuitem',
4595 'tabindex' => '-1',
4597 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
4598 if ($this->prioritise) {
4599 array_unshift($actions, $link);
4600 } else {
4601 $actions[] = $link;
4603 return $actions;
4607 * Returns the secondary actions ready to be rendered.
4608 * @return array
4610 public function get_secondary_actions() {
4611 return $this->secondaryactions;
4615 * Sets the selector that should be used to find the owning node of this menu.
4616 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
4618 public function set_owner_selector($selector) {
4619 $this->attributes['data-owner'] = $selector;
4623 * Sets the alignment of the dialogue in relation to button used to toggle it.
4625 * @deprecated since Moodle 4.0
4627 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4628 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4630 public function set_alignment($dialogue, $button) {
4631 debugging('The method action_menu::set_alignment() is deprecated, use action_menu::set_menu_left()', DEBUG_DEVELOPER);
4632 if (isset($this->attributessecondary['data-align'])) {
4633 // We've already got one set, lets remove the old class so as to avoid troubles.
4634 $class = $this->attributessecondary['class'];
4635 $search = 'align-'.$this->attributessecondary['data-align'];
4636 $this->attributessecondary['class'] = str_replace($search, '', $class);
4638 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
4639 $this->attributessecondary['data-align'] = $align;
4640 $this->attributessecondary['class'] .= ' align-'.$align;
4644 * Returns a string to describe the alignment.
4646 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4647 * @return string
4649 protected function get_align_string($align) {
4650 switch ($align) {
4651 case self::TL :
4652 return 'tl';
4653 case self::TR :
4654 return 'tr';
4655 case self::BL :
4656 return 'bl';
4657 case self::BR :
4658 return 'br';
4659 default :
4660 return 'tl';
4665 * Aligns the left corner of the dropdown.
4668 public function set_menu_left() {
4669 $this->dropdownalignment = 'dropdown-menu-left';
4673 * Sets a constraint for the dialogue.
4675 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
4676 * element the constraint identifies.
4678 * This is required whenever the action menu is displayed inside any CSS element with the .no-overflow class
4679 * (flexible_table and any of it's child classes are a likely candidate).
4681 * @deprecated since Moodle 4.3
4682 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
4684 public function set_constraint($ancestorselector) {
4685 debugging('The method set_constraint() is deprecated. Please use the set_boundary() method instead.', DEBUG_DEVELOPER);
4686 $this->set_boundary('window');
4690 * Set the overflow constraint boundary of the dropdown menu.
4691 * @see https://getbootstrap.com/docs/4.6/components/dropdowns/#options The 'boundary' option in the Bootstrap documentation
4693 * @param string $boundary Accepts the values of 'viewport', 'window', or 'scrollParent'.
4694 * @throws coding_exception
4696 public function set_boundary(string $boundary) {
4697 if (!in_array($boundary, ['viewport', 'window', 'scrollParent'])) {
4698 throw new coding_exception("HTMLElement reference boundaries are not supported." .
4699 "Accepted boundaries are 'viewport', 'window', or 'scrollParent'.", DEBUG_DEVELOPER);
4702 $this->triggerattributes['data-boundary'] = $boundary;
4706 * If you call this method the action menu will be displayed but will not be enhanced.
4708 * By not displaying the menu enhanced all items will be displayed in a single row.
4710 * @deprecated since Moodle 3.2
4712 public function do_not_enhance() {
4713 debugging('The method action_menu::do_not_enhance() is deprecated, use a list of action_icon instead.', DEBUG_DEVELOPER);
4717 * Returns true if this action menu will be enhanced.
4719 * @return bool
4721 public function will_be_enhanced() {
4722 return isset($this->attributes['data-enhance']);
4726 * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
4728 * This property can be useful when the action menu is displayed within a parent element that is either floated
4729 * or relatively positioned.
4730 * In that situation the width of the menu is determined by the width of the parent element which may not be large
4731 * enough for the menu items without them wrapping.
4732 * This disables the wrapping so that the menu takes on the width of the longest item.
4734 * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
4736 public function set_nowrap_on_items($value = true) {
4737 $class = 'nowrap-items';
4738 if (!empty($this->attributes['class'])) {
4739 $pos = strpos($this->attributes['class'], $class);
4740 if ($value === true && $pos === false) {
4741 // The value is true and the class has not been set yet. Add it.
4742 $this->attributes['class'] .= ' '.$class;
4743 } else if ($value === false && $pos !== false) {
4744 // The value is false and the class has been set. Remove it.
4745 $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class));
4747 } else if ($value) {
4748 // The value is true and the class has not been set yet. Add it.
4749 $this->attributes['class'] = $class;
4754 * Add classes to the action menu for an easier styling.
4756 * @param string $class The class to add to attributes.
4758 public function set_additional_classes(string $class = '') {
4759 if (!empty($this->attributes['class'])) {
4760 $this->attributes['class'] .= " ".$class;
4761 } else {
4762 $this->attributes['class'] = $class;
4767 * Export for template.
4769 * @param renderer_base $output The renderer.
4770 * @return stdClass
4772 public function export_for_template(renderer_base $output) {
4773 $data = new stdClass();
4774 // Assign a role of menubar to this action menu when:
4775 // - it contains 2 or more primary actions; or
4776 // - if it contains a primary action and secondary actions.
4777 if (count($this->primaryactions) > 1 || (!empty($this->primaryactions) && !empty($this->secondaryactions))) {
4778 $this->attributes['role'] = 'menubar';
4780 $attributes = $this->attributes;
4782 $data->instance = $this->instance;
4784 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
4785 unset($attributes['class']);
4787 $data->attributes = array_map(function($key, $value) {
4788 return [ 'name' => $key, 'value' => $value ];
4789 }, array_keys($attributes), $attributes);
4791 $data->primary = $this->export_primary_actions_for_template($output);
4792 $data->secondary = $this->export_secondary_actions_for_template($output);
4793 $data->dropdownalignment = $this->dropdownalignment;
4795 return $data;
4799 * Export the primary actions for the template.
4800 * @param renderer_base $output
4801 * @return stdClass
4803 protected function export_primary_actions_for_template(renderer_base $output): stdClass {
4804 $attributes = $this->attributes;
4805 $attributesprimary = $this->attributesprimary;
4807 $primary = new stdClass();
4808 $primary->title = '';
4809 $primary->prioritise = $this->prioritise;
4811 $primary->classes = isset($attributesprimary['class']) ? $attributesprimary['class'] : '';
4812 unset($attributesprimary['class']);
4814 $primary->attributes = array_map(function ($key, $value) {
4815 return ['name' => $key, 'value' => $value];
4816 }, array_keys($attributesprimary), $attributesprimary);
4817 $primary->triggerattributes = array_map(function ($key, $value) {
4818 return ['name' => $key, 'value' => $value];
4819 }, array_keys($this->triggerattributes), $this->triggerattributes);
4821 $actionicon = $this->actionicon;
4822 if (!empty($this->menutrigger)) {
4823 $primary->menutrigger = $this->menutrigger;
4824 $primary->triggerextraclasses = $this->triggerextraclasses;
4825 if ($this->actionlabel) {
4826 $primary->title = $this->actionlabel;
4827 } else if ($this->actiontext) {
4828 $primary->title = $this->actiontext;
4829 } else {
4830 $primary->title = strip_tags($this->menutrigger);
4832 } else {
4833 $primary->title = get_string('actionsmenu');
4834 $iconattributes = ['class' => 'iconsmall actionmenu', 'title' => $primary->title];
4835 $actionicon = new pix_icon('t/edit_menu', '', 'moodle', $iconattributes);
4838 // If the menu trigger is within the menubar, assign a role of menuitem. Otherwise, assign as a button.
4839 $primary->triggerrole = 'button';
4840 if (isset($attributes['role']) && $attributes['role'] === 'menubar') {
4841 $primary->triggerrole = 'menuitem';
4844 if ($actionicon instanceof pix_icon) {
4845 $primary->icon = $actionicon->export_for_pix();
4846 if (!empty($actionicon->attributes['alt'])) {
4847 $primary->title = $actionicon->attributes['alt'];
4849 } else {
4850 $primary->iconraw = $actionicon ? $output->render($actionicon) : '';
4853 $primary->actiontext = $this->actiontext ? (string) $this->actiontext : '';
4854 $primary->items = array_map(function ($item) use ($output) {
4855 $data = (object) [];
4856 if ($item instanceof action_menu_link) {
4857 $data->actionmenulink = $item->export_for_template($output);
4858 } else if ($item instanceof action_menu_filler) {
4859 $data->actionmenufiller = $item->export_for_template($output);
4860 } else if ($item instanceof action_link) {
4861 $data->actionlink = $item->export_for_template($output);
4862 } else if ($item instanceof pix_icon) {
4863 $data->pixicon = $item->export_for_template($output);
4864 } else {
4865 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4867 return $data;
4868 }, $this->primaryactions);
4869 return $primary;
4873 * Export the secondary actions for the template.
4874 * @param renderer_base $output
4875 * @return stdClass
4877 protected function export_secondary_actions_for_template(renderer_base $output): stdClass {
4878 $attributessecondary = $this->attributessecondary;
4879 $secondary = new stdClass();
4880 $secondary->classes = isset($attributessecondary['class']) ? $attributessecondary['class'] : '';
4881 unset($attributessecondary['class']);
4883 $secondary->attributes = array_map(function ($key, $value) {
4884 return ['name' => $key, 'value' => $value];
4885 }, array_keys($attributessecondary), $attributessecondary);
4886 $secondary->items = array_map(function ($item) use ($output) {
4887 $data = (object) [
4888 'simpleitem' => true,
4890 if ($item instanceof action_menu_link) {
4891 $data->actionmenulink = $item->export_for_template($output);
4892 $data->simpleitem = false;
4893 } else if ($item instanceof action_menu_filler) {
4894 $data->actionmenufiller = $item->export_for_template($output);
4895 $data->simpleitem = false;
4896 } else if ($item instanceof subpanel) {
4897 $data->subpanel = $item->export_for_template($output);
4898 $data->simpleitem = false;
4899 } else if ($item instanceof action_link) {
4900 $data->actionlink = $item->export_for_template($output);
4901 } else if ($item instanceof pix_icon) {
4902 $data->pixicon = $item->export_for_template($output);
4903 } else {
4904 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4906 return $data;
4907 }, $this->secondaryactions);
4908 return $secondary;
4913 * An action menu filler
4915 * @package core
4916 * @category output
4917 * @copyright 2013 Andrew Nicols
4918 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4920 class action_menu_filler extends action_link implements renderable {
4923 * True if this is a primary action. False if not.
4924 * @var bool
4926 public $primary = true;
4929 * Constructs the object.
4931 public function __construct() {
4932 $this->attributes['id'] = html_writer::random_id('action_link');
4937 * An action menu action
4939 * @package core
4940 * @category output
4941 * @copyright 2013 Sam Hemelryk
4942 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4944 class action_menu_link extends action_link implements renderable {
4947 * True if this is a primary action. False if not.
4948 * @var bool
4950 public $primary = true;
4953 * The action menu this link has been added to.
4954 * @var action_menu
4956 public $actionmenu = null;
4959 * The number of instances of this action menu link (and its subclasses).
4961 * @deprecated since Moodle 4.4.
4962 * @var int
4964 protected static $instance = 1;
4967 * Constructs the object.
4969 * @param moodle_url $url The URL for the action.
4970 * @param pix_icon|null $icon The icon to represent the action.
4971 * @param string $text The text to represent the action.
4972 * @param bool $primary Whether this is a primary action or not.
4973 * @param array $attributes Any attribtues associated with the action.
4975 public function __construct(moodle_url $url, ?pix_icon $icon, $text, $primary = true, array $attributes = array()) {
4976 parent::__construct($url, $text, null, $attributes, $icon);
4977 $this->primary = (bool)$primary;
4978 $this->add_class('menu-action');
4979 $this->attributes['role'] = 'menuitem';
4983 * Export for template.
4985 * @param renderer_base $output The renderer.
4986 * @return stdClass
4988 public function export_for_template(renderer_base $output) {
4989 $data = parent::export_for_template($output);
4991 // Ignore what the parent did with the attributes, except for ID and class.
4992 $data->attributes = [];
4993 $attributes = $this->attributes;
4994 unset($attributes['id']);
4995 unset($attributes['class']);
4997 // Handle text being a renderable.
4998 if ($this->text instanceof renderable) {
4999 $data->text = $this->render($this->text);
5002 $data->showtext = (!$this->icon || $this->primary === false);
5004 $data->icon = null;
5005 if ($this->icon) {
5006 $icon = $this->icon;
5007 if ($this->primary || !$this->actionmenu->will_be_enhanced()) {
5008 $attributes['title'] = $data->text;
5010 $data->icon = $icon ? $icon->export_for_pix() : null;
5013 $data->disabled = !empty($attributes['disabled']);
5014 unset($attributes['disabled']);
5016 $data->attributes = array_map(function($key, $value) {
5017 return [
5018 'name' => $key,
5019 'value' => $value
5021 }, array_keys($attributes), $attributes);
5023 return $data;
5028 * A primary action menu action
5030 * @package core
5031 * @category output
5032 * @copyright 2013 Sam Hemelryk
5033 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5035 class action_menu_link_primary extends action_menu_link {
5037 * Constructs the object.
5039 * @param moodle_url $url
5040 * @param pix_icon|null $icon
5041 * @param string $text
5042 * @param array $attributes
5044 public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) {
5045 parent::__construct($url, $icon, $text, true, $attributes);
5050 * A secondary action menu action
5052 * @package core
5053 * @category output
5054 * @copyright 2013 Sam Hemelryk
5055 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5057 class action_menu_link_secondary extends action_menu_link {
5059 * Constructs the object.
5061 * @param moodle_url $url
5062 * @param pix_icon|null $icon
5063 * @param string $text
5064 * @param array $attributes
5066 public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) {
5067 parent::__construct($url, $icon, $text, false, $attributes);
5072 * Represents a set of preferences groups.
5074 * @package core
5075 * @category output
5076 * @copyright 2015 Frédéric Massart - FMCorz.net
5077 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5079 class preferences_groups implements renderable {
5082 * Array of preferences_group.
5083 * @var array
5085 public $groups;
5088 * Constructor.
5089 * @param array $groups of preferences_group
5091 public function __construct($groups) {
5092 $this->groups = $groups;
5098 * Represents a group of preferences page link.
5100 * @package core
5101 * @category output
5102 * @copyright 2015 Frédéric Massart - FMCorz.net
5103 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5105 class preferences_group implements renderable {
5108 * Title of the group.
5109 * @var string
5111 public $title;
5114 * Array of navigation_node.
5115 * @var array
5117 public $nodes;
5120 * Constructor.
5121 * @param string $title The title.
5122 * @param array $nodes of navigation_node.
5124 public function __construct($title, $nodes) {
5125 $this->title = $title;
5126 $this->nodes = $nodes;
5131 * Progress bar class.
5133 * Manages the display of a progress bar.
5135 * To use this class.
5136 * - construct
5137 * - call create (or use the 3rd param to the constructor)
5138 * - call update or update_full() or update() repeatedly
5140 * @copyright 2008 jamiesensei
5141 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5142 * @package core
5143 * @category output
5145 class progress_bar implements renderable, templatable {
5146 /** @var string html id */
5147 private $html_id;
5148 /** @var int total width */
5149 private $width;
5150 /** @var int last percentage printed */
5151 private $percent = 0;
5152 /** @var int time when last printed */
5153 private $lastupdate = 0;
5154 /** @var int when did we start printing this */
5155 private $time_start = 0;
5158 * Constructor
5160 * Prints JS code if $autostart true.
5162 * @param string $htmlid The container ID.
5163 * @param int $width The suggested width.
5164 * @param bool $autostart Whether to start the progress bar right away.
5166 public function __construct($htmlid = '', $width = 500, $autostart = false) {
5167 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
5168 debugging('progress_bar used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', DEBUG_DEVELOPER);
5171 if (!empty($htmlid)) {
5172 $this->html_id = $htmlid;
5173 } else {
5174 $this->html_id = 'pbar_'.uniqid();
5177 $this->width = $width;
5179 if ($autostart) {
5180 $this->create();
5185 * Getter for ID
5186 * @return string id
5188 public function get_id(): string {
5189 return $this->html_id;
5193 * Create a new progress bar, this function will output html.
5195 * @return void Echo's output
5197 public function create() {
5198 global $OUTPUT;
5200 $this->time_start = microtime(true);
5202 flush();
5203 echo $OUTPUT->render($this);
5204 flush();
5208 * Update the progress bar.
5210 * @param int $percent From 1-100.
5211 * @param string $msg The message.
5212 * @return void Echo's output
5213 * @throws coding_exception
5215 private function _update($percent, $msg) {
5216 global $OUTPUT;
5218 if (empty($this->time_start)) {
5219 throw new coding_exception('You must call create() (or use the $autostart ' .
5220 'argument to the constructor) before you try updating the progress bar.');
5223 $estimate = $this->estimate($percent);
5225 if ($estimate === null) {
5226 // Always do the first and last updates.
5227 } else if ($estimate == 0) {
5228 // Always do the last updates.
5229 } else if ($this->lastupdate + 20 < time()) {
5230 // We must update otherwise browser would time out.
5231 } else if (round($this->percent, 2) === round($percent, 2)) {
5232 // No significant change, no need to update anything.
5233 return;
5236 $estimatemsg = '';
5237 if ($estimate != 0 && is_numeric($estimate)) {
5238 // Err on the conservative side and also avoid showing 'now' as the estimate.
5239 $estimatemsg = format_time(ceil($estimate));
5242 $this->percent = $percent;
5243 $this->lastupdate = microtime(true);
5245 echo $OUTPUT->render_progress_bar_update($this->html_id, $this->percent, $msg, $estimatemsg);
5246 flush();
5250 * Estimate how much time it is going to take.
5252 * @param int $pt From 1-100.
5253 * @return mixed Null (unknown), or int.
5255 private function estimate($pt) {
5256 if ($this->lastupdate == 0) {
5257 return null;
5259 if ($pt < 0.00001) {
5260 return null; // We do not know yet how long it will take.
5262 if ($pt > 99.99999) {
5263 return 0; // Nearly done, right?
5265 $consumed = microtime(true) - $this->time_start;
5266 if ($consumed < 0.001) {
5267 return null;
5270 return (100 - $pt) * ($consumed / $pt);
5274 * Update progress bar according percent.
5276 * @param int $percent From 1-100.
5277 * @param string $msg The message needed to be shown.
5279 public function update_full($percent, $msg) {
5280 $percent = max(min($percent, 100), 0);
5281 $this->_update($percent, $msg);
5285 * Update progress bar according the number of tasks.
5287 * @param int $cur Current task number.
5288 * @param int $total Total task number.
5289 * @param string $msg The message needed to be shown.
5291 public function update($cur, $total, $msg) {
5292 $percent = ($cur / $total) * 100;
5293 $this->update_full($percent, $msg);
5297 * Restart the progress bar.
5299 public function restart() {
5300 $this->percent = 0;
5301 $this->lastupdate = 0;
5302 $this->time_start = 0;
5306 * Export for template.
5308 * @param renderer_base $output The renderer.
5309 * @return array
5311 public function export_for_template(renderer_base $output) {
5312 return [
5313 'id' => $this->html_id,
5314 'width' => $this->width,