Merge branch 'MDL-75105_401_STABLE' of https://github.com/marxjohnson/moodle into...
[moodle.git] / lib / outputcomponents.php
blob850d4b2bb752199be427c0e7baba6be0f4a1ba36
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 defined('MOODLE_INTERNAL') || die();
31 /**
32 * Interface marking other classes as suitable for renderer_base::render()
34 * @copyright 2010 Petr Skoda (skodak) info@skodak.org
35 * @package core
36 * @category output
38 interface renderable {
39 // intentionally empty
42 /**
43 * Interface marking other classes having the ability to export their data for use by templates.
45 * @copyright 2015 Damyon Wiese
46 * @package core
47 * @category output
48 * @since 2.9
50 interface templatable {
52 /**
53 * Function to export the renderer data in a format that is suitable for a
54 * mustache template. This means:
55 * 1. No complex types - only stdClass, array, int, string, float, bool
56 * 2. Any additional info that is required for the template is pre-calculated (e.g. capability checks).
58 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
59 * @return stdClass|array
61 public function export_for_template(renderer_base $output);
64 /**
65 * Data structure representing a file picker.
67 * @copyright 2010 Dongsheng Cai
68 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
69 * @since Moodle 2.0
70 * @package core
71 * @category output
73 class file_picker implements renderable {
75 /**
76 * @var stdClass An object containing options for the file picker
78 public $options;
80 /**
81 * Constructs a file picker object.
83 * The following are possible options for the filepicker:
84 * - accepted_types (*)
85 * - return_types (FILE_INTERNAL)
86 * - env (filepicker)
87 * - client_id (uniqid)
88 * - itemid (0)
89 * - maxbytes (-1)
90 * - maxfiles (1)
91 * - buttonname (false)
93 * @param stdClass $options An object containing options for the file picker.
95 public function __construct(stdClass $options) {
96 global $CFG, $USER, $PAGE;
97 require_once($CFG->dirroot. '/repository/lib.php');
98 $defaults = array(
99 'accepted_types'=>'*',
100 'return_types'=>FILE_INTERNAL,
101 'env' => 'filepicker',
102 'client_id' => uniqid(),
103 'itemid' => 0,
104 'maxbytes'=>-1,
105 'maxfiles'=>1,
106 'buttonname'=>false
108 foreach ($defaults as $key=>$value) {
109 if (empty($options->$key)) {
110 $options->$key = $value;
114 $options->currentfile = '';
115 if (!empty($options->itemid)) {
116 $fs = get_file_storage();
117 $usercontext = context_user::instance($USER->id);
118 if (empty($options->filename)) {
119 if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
120 $file = reset($files);
122 } else {
123 $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
125 if (!empty($file)) {
126 $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
130 // initilise options, getting files in root path
131 $this->options = initialise_filepicker($options);
133 // copying other options
134 foreach ($options as $name=>$value) {
135 if (!isset($this->options->$name)) {
136 $this->options->$name = $value;
143 * Data structure representing a user picture.
145 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
146 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
147 * @since Modle 2.0
148 * @package core
149 * @category output
151 class user_picture implements renderable {
153 * @var stdClass A user object with at least fields all columns specified
154 * in $fields array constant set.
156 public $user;
159 * @var int The course id. Used when constructing the link to the user's
160 * profile, page course id used if not specified.
162 public $courseid;
165 * @var bool Add course profile link to image
167 public $link = true;
170 * @var int Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility.
171 * Recommended values (supporting user initials too): 16, 35, 64 and 100.
173 public $size = 35;
176 * @var bool Add non-blank alt-text to the image.
177 * Default true, set to false when image alt just duplicates text in screenreaders.
179 public $alttext = true;
182 * @var bool Whether or not to open the link in a popup window.
184 public $popup = false;
187 * @var string Image class attribute
189 public $class = 'userpicture';
192 * @var bool Whether to be visible to screen readers.
194 public $visibletoscreenreaders = true;
197 * @var bool Whether to include the fullname in the user picture link.
199 public $includefullname = false;
202 * @var mixed Include user authentication token. True indicates to generate a token for current user, and integer value
203 * indicates to generate a token for the user whose id is the value indicated.
205 public $includetoken = false;
208 * User picture constructor.
210 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
211 * It is recommended to add also contextid of the user for performance reasons.
213 public function __construct(stdClass $user) {
214 global $DB;
216 if (empty($user->id)) {
217 throw new coding_exception('User id is required when printing user avatar image.');
220 // only touch the DB if we are missing data and complain loudly...
221 $needrec = false;
222 foreach (\core_user\fields::get_picture_fields() as $field) {
223 if (!property_exists($user, $field)) {
224 $needrec = true;
225 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
226 .'Please use the \core_user\fields API to get the full list of required fields.', DEBUG_DEVELOPER);
227 break;
231 if ($needrec) {
232 $this->user = $DB->get_record('user', array('id' => $user->id),
233 implode(',', \core_user\fields::get_picture_fields()), MUST_EXIST);
234 } else {
235 $this->user = clone($user);
240 * Returns a list of required user fields, useful when fetching required user info from db.
242 * In some cases we have to fetch the user data together with some other information,
243 * the idalias is useful there because the id would otherwise override the main
244 * id of the result record. Please note it has to be converted back to id before rendering.
246 * @param string $tableprefix name of database table prefix in query
247 * @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)
248 * @param string $idalias alias of id field
249 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
250 * @return string
251 * @deprecated since Moodle 3.11 MDL-45242
252 * @see \core_user\fields
254 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
255 debugging('user_picture::fields() is deprecated. Please use the \core_user\fields API instead.', DEBUG_DEVELOPER);
256 $userfields = \core_user\fields::for_userpic();
257 if ($extrafields) {
258 $userfields->including(...$extrafields);
260 $selects = $userfields->get_sql($tableprefix, false, $fieldprefix, $idalias, false)->selects;
261 if ($tableprefix === '') {
262 // If no table alias is specified, don't add {user}. in front of fields.
263 $selects = str_replace('{user}.', '', $selects);
265 // Maintain legacy behaviour where the field list was done with 'implode' and no spaces.
266 $selects = str_replace(', ', ',', $selects);
267 return $selects;
271 * Extract the aliased user fields from a given record
273 * Given a record that was previously obtained using {@link self::fields()} with aliases,
274 * this method extracts user related unaliased fields.
276 * @param stdClass $record containing user picture fields
277 * @param array $extrafields extra fields included in the $record
278 * @param string $idalias alias of the id field
279 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
280 * @return stdClass object with unaliased user fields
282 public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
284 if (empty($idalias)) {
285 $idalias = 'id';
288 $return = new stdClass();
290 foreach (\core_user\fields::get_picture_fields() as $field) {
291 if ($field === 'id') {
292 if (property_exists($record, $idalias)) {
293 $return->id = $record->{$idalias};
295 } else {
296 if (property_exists($record, $fieldprefix.$field)) {
297 $return->{$field} = $record->{$fieldprefix.$field};
301 // add extra fields if not already there
302 if ($extrafields) {
303 foreach ($extrafields as $e) {
304 if ($e === 'id' or property_exists($return, $e)) {
305 continue;
307 $return->{$e} = $record->{$fieldprefix.$e};
311 return $return;
315 * Works out the URL for the users picture.
317 * This method is recommended as it avoids costly redirects of user pictures
318 * if requests are made for non-existent files etc.
320 * @param moodle_page $page
321 * @param renderer_base $renderer
322 * @return moodle_url
324 public function get_url(moodle_page $page, renderer_base $renderer = null) {
325 global $CFG;
327 if (is_null($renderer)) {
328 $renderer = $page->get_renderer('core');
331 // Sort out the filename and size. Size is only required for the gravatar
332 // implementation presently.
333 if (empty($this->size)) {
334 $filename = 'f2';
335 $size = 35;
336 } else if ($this->size === true or $this->size == 1) {
337 $filename = 'f1';
338 $size = 100;
339 } else if ($this->size > 100) {
340 $filename = 'f3';
341 $size = (int)$this->size;
342 } else if ($this->size >= 50) {
343 $filename = 'f1';
344 $size = (int)$this->size;
345 } else {
346 $filename = 'f2';
347 $size = (int)$this->size;
350 $defaulturl = $renderer->image_url('u/'.$filename); // default image
352 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
353 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
354 // Protect images if login required and not logged in;
355 // also if login is required for profile images and is not logged in or guest
356 // do not use require_login() because it is expensive and not suitable here anyway.
357 return $defaulturl;
360 // First try to detect deleted users - but do not read from database for performance reasons!
361 if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
362 // All deleted users should have email replaced by md5 hash,
363 // all active users are expected to have valid email.
364 return $defaulturl;
367 // Did the user upload a picture?
368 if ($this->user->picture > 0) {
369 if (!empty($this->user->contextid)) {
370 $contextid = $this->user->contextid;
371 } else {
372 $context = context_user::instance($this->user->id, IGNORE_MISSING);
373 if (!$context) {
374 // This must be an incorrectly deleted user, all other users have context.
375 return $defaulturl;
377 $contextid = $context->id;
380 $path = '/';
381 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
382 // We append the theme name to the file path if we have it so that
383 // in the circumstance that the profile picture is not available
384 // when the user actually requests it they still get the profile
385 // picture for the correct theme.
386 $path .= $page->theme->name.'/';
388 // Set the image URL to the URL for the uploaded file and return.
389 $url = moodle_url::make_pluginfile_url(
390 $contextid, 'user', 'icon', null, $path, $filename, false, $this->includetoken);
391 $url->param('rev', $this->user->picture);
392 return $url;
395 if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
396 // Normalise the size variable to acceptable bounds
397 if ($size < 1 || $size > 512) {
398 $size = 35;
400 // Hash the users email address
401 $md5 = md5(strtolower(trim($this->user->email)));
402 // Build a gravatar URL with what we know.
404 // Find the best default image URL we can (MDL-35669)
405 if (empty($CFG->gravatardefaulturl)) {
406 $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
407 if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
408 $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
409 } else {
410 $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
412 } else {
413 $gravatardefault = $CFG->gravatardefaulturl;
416 // If the currently requested page is https then we'll return an
417 // https gravatar page.
418 if (is_https()) {
419 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
420 } else {
421 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
425 return $defaulturl;
430 * Data structure representing a help icon.
432 * @copyright 2010 Petr Skoda (info@skodak.org)
433 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
434 * @since Moodle 2.0
435 * @package core
436 * @category output
438 class help_icon implements renderable, templatable {
441 * @var string lang pack identifier (without the "_help" suffix),
442 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
443 * must exist.
445 public $identifier;
448 * @var string Component name, the same as in get_string()
450 public $component;
453 * @var string Extra descriptive text next to the icon
455 public $linktext = null;
458 * Constructor
460 * @param string $identifier string for help page title,
461 * string with _help suffix is used for the actual help text.
462 * string with _link suffix is used to create a link to further info (if it exists)
463 * @param string $component
465 public function __construct($identifier, $component) {
466 $this->identifier = $identifier;
467 $this->component = $component;
471 * Verifies that both help strings exists, shows debug warnings if not
473 public function diag_strings() {
474 $sm = get_string_manager();
475 if (!$sm->string_exists($this->identifier, $this->component)) {
476 debugging("Help title string does not exist: [$this->identifier, $this->component]");
478 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
479 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
484 * Export this data so it can be used as the context for a mustache template.
486 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
487 * @return array
489 public function export_for_template(renderer_base $output) {
490 global $CFG;
492 $title = get_string($this->identifier, $this->component);
494 if (empty($this->linktext)) {
495 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
496 } else {
497 $alt = get_string('helpwiththis');
500 $data = get_formatted_help_string($this->identifier, $this->component, false);
502 $data->alt = $alt;
503 $data->icon = (new pix_icon('help', $alt, 'core', ['class' => 'iconhelp']))->export_for_template($output);
504 $data->linktext = $this->linktext;
505 $data->title = get_string('helpprefix2', '', trim($title, ". \t"));
507 $options = [
508 'component' => $this->component,
509 'identifier' => $this->identifier,
510 'lang' => current_language()
513 // Debugging feature lets you display string identifier and component.
514 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
515 $options['strings'] = 1;
518 $data->url = (new moodle_url('/help.php', $options))->out(false);
519 $data->ltr = !right_to_left();
520 return $data;
526 * Data structure representing an icon font.
528 * @copyright 2016 Damyon Wiese
529 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
530 * @package core
531 * @category output
533 class pix_icon_font implements templatable {
536 * @var pix_icon $pixicon The original icon.
538 private $pixicon = null;
541 * @var string $key The mapped key.
543 private $key;
546 * @var bool $mapped The icon could not be mapped.
548 private $mapped;
551 * Constructor
553 * @param pix_icon $pixicon The original icon
555 public function __construct(pix_icon $pixicon) {
556 global $PAGE;
558 $this->pixicon = $pixicon;
559 $this->mapped = false;
560 $iconsystem = \core\output\icon_system::instance();
562 $this->key = $iconsystem->remap_icon_name($pixicon->pix, $pixicon->component);
563 if (!empty($this->key)) {
564 $this->mapped = true;
569 * Return true if this pix_icon was successfully mapped to an icon font.
571 * @return bool
573 public function is_mapped() {
574 return $this->mapped;
578 * Export this data so it can be used as the context for a mustache template.
580 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
581 * @return array
583 public function export_for_template(renderer_base $output) {
585 $pixdata = $this->pixicon->export_for_template($output);
587 $title = isset($this->pixicon->attributes['title']) ? $this->pixicon->attributes['title'] : '';
588 $alt = isset($this->pixicon->attributes['alt']) ? $this->pixicon->attributes['alt'] : '';
589 if (empty($title)) {
590 $title = $alt;
592 $data = array(
593 'extraclasses' => $pixdata['extraclasses'],
594 'title' => $title,
595 'alt' => $alt,
596 'key' => $this->key
599 return $data;
604 * Data structure representing an icon subtype.
606 * @copyright 2016 Damyon Wiese
607 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
608 * @package core
609 * @category output
611 class pix_icon_fontawesome extends pix_icon_font {
616 * Data structure representing an icon.
618 * @copyright 2010 Petr Skoda
619 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
620 * @since Moodle 2.0
621 * @package core
622 * @category output
624 class pix_icon implements renderable, templatable {
627 * @var string The icon name
629 var $pix;
632 * @var string The component the icon belongs to.
634 var $component;
637 * @var array An array of attributes to use on the icon
639 var $attributes = array();
642 * Constructor
644 * @param string $pix short icon name
645 * @param string $alt The alt text to use for the icon
646 * @param string $component component name
647 * @param array $attributes html attributes
649 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
650 global $PAGE;
652 $this->pix = $pix;
653 $this->component = $component;
654 $this->attributes = (array)$attributes;
656 if (empty($this->attributes['class'])) {
657 $this->attributes['class'] = '';
660 // Set an additional class for big icons so that they can be styled properly.
661 if (substr($pix, 0, 2) === 'b/') {
662 $this->attributes['class'] .= ' iconsize-big';
665 // If the alt is empty, don't place it in the attributes, otherwise it will override parent alt text.
666 if (!is_null($alt)) {
667 $this->attributes['alt'] = $alt;
669 // If there is no title, set it to the attribute.
670 if (!isset($this->attributes['title'])) {
671 $this->attributes['title'] = $this->attributes['alt'];
673 } else {
674 unset($this->attributes['alt']);
677 if (empty($this->attributes['title'])) {
678 // Remove the title attribute if empty, we probably want to use the parent node's title
679 // and some browsers might overwrite it with an empty title.
680 unset($this->attributes['title']);
683 // Hide icons from screen readers that have no alt.
684 if (empty($this->attributes['alt'])) {
685 $this->attributes['aria-hidden'] = 'true';
690 * Export this data so it can be used as the context for a mustache template.
692 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
693 * @return array
695 public function export_for_template(renderer_base $output) {
696 $attributes = $this->attributes;
697 $extraclasses = '';
699 foreach ($attributes as $key => $item) {
700 if ($key == 'class') {
701 $extraclasses = $item;
702 unset($attributes[$key]);
703 break;
707 $attributes['src'] = $output->image_url($this->pix, $this->component)->out(false);
708 $templatecontext = array();
709 foreach ($attributes as $name => $value) {
710 $templatecontext[] = array('name' => $name, 'value' => $value);
712 $title = isset($attributes['title']) ? $attributes['title'] : '';
713 if (empty($title)) {
714 $title = isset($attributes['alt']) ? $attributes['alt'] : '';
716 $data = array(
717 'attributes' => $templatecontext,
718 'extraclasses' => $extraclasses
721 return $data;
725 * Much simpler version of export that will produce the data required to render this pix with the
726 * pix helper in a mustache tag.
728 * @return array
730 public function export_for_pix() {
731 $title = isset($this->attributes['title']) ? $this->attributes['title'] : '';
732 if (empty($title)) {
733 $title = isset($this->attributes['alt']) ? $this->attributes['alt'] : '';
735 return [
736 'key' => $this->pix,
737 'component' => $this->component,
738 'title' => (string) $title,
744 * Data structure representing an activity icon.
746 * The difference is that activity icons will always render with the standard icon system (no font icons).
748 * @copyright 2017 Damyon Wiese
749 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
750 * @package core
752 class image_icon extends pix_icon {
756 * Data structure representing an emoticon image
758 * @copyright 2010 David Mudrak
759 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
760 * @since Moodle 2.0
761 * @package core
762 * @category output
764 class pix_emoticon extends pix_icon implements renderable {
767 * Constructor
768 * @param string $pix short icon name
769 * @param string $alt alternative text
770 * @param string $component emoticon image provider
771 * @param array $attributes explicit HTML attributes
773 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
774 if (empty($attributes['class'])) {
775 $attributes['class'] = 'emoticon';
777 parent::__construct($pix, $alt, $component, $attributes);
782 * Data structure representing a simple form with only one button.
784 * @copyright 2009 Petr Skoda
785 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
786 * @since Moodle 2.0
787 * @package core
788 * @category output
790 class single_button implements renderable {
793 * @var moodle_url Target url
795 public $url;
798 * @var string Button label
800 public $label;
803 * @var string Form submit method post or get
805 public $method = 'post';
808 * @var string Wrapping div class
810 public $class = 'singlebutton';
813 * @var bool True if button is primary button. Used for styling.
815 public $primary = false;
818 * @var bool True if button disabled, false if normal
820 public $disabled = false;
823 * @var string Button tooltip
825 public $tooltip = null;
828 * @var string Form id
830 public $formid;
833 * @var array List of attached actions
835 public $actions = array();
838 * @var array $params URL Params
840 public $params;
843 * @var string Action id
845 public $actionid;
848 * @var array
850 protected $attributes = [];
853 * Constructor
854 * @param moodle_url $url
855 * @param string $label button text
856 * @param string $method get or post submit method
857 * @param bool $primary whether this is a primary button, used for styling
858 * @param array $attributes Attributes for the HTML button tag
860 public function __construct(moodle_url $url, $label, $method='post', $primary=false, $attributes = []) {
861 $this->url = clone($url);
862 $this->label = $label;
863 $this->method = $method;
864 $this->primary = $primary;
865 $this->attributes = $attributes;
869 * Shortcut for adding a JS confirm dialog when the button is clicked.
870 * The message must be a yes/no question.
872 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
874 public function add_confirm_action($confirmmessage) {
875 $this->add_action(new confirm_action($confirmmessage));
879 * Add action to the button.
880 * @param component_action $action
882 public function add_action(component_action $action) {
883 $this->actions[] = $action;
887 * Sets an attribute for the HTML button tag.
889 * @param string $name The attribute name
890 * @param mixed $value The value
891 * @return null
893 public function set_attribute($name, $value) {
894 $this->attributes[$name] = $value;
898 * Export data.
900 * @param renderer_base $output Renderer.
901 * @return stdClass
903 public function export_for_template(renderer_base $output) {
904 $url = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
906 $data = new stdClass();
907 $data->id = html_writer::random_id('single_button');
908 $data->formid = $this->formid;
909 $data->method = $this->method;
910 $data->url = $url === '' ? '#' : $url;
911 $data->label = $this->label;
912 $data->classes = $this->class;
913 $data->disabled = $this->disabled;
914 $data->tooltip = $this->tooltip;
915 $data->primary = $this->primary;
917 $data->attributes = [];
918 foreach ($this->attributes as $key => $value) {
919 $data->attributes[] = ['name' => $key, 'value' => $value];
922 // Form parameters.
923 $params = $this->url->params();
924 if ($this->method === 'post') {
925 $params['sesskey'] = sesskey();
927 $data->params = array_map(function($key) use ($params) {
928 return ['name' => $key, 'value' => $params[$key]];
929 }, array_keys($params));
931 // Button actions.
932 $actions = $this->actions;
933 $data->actions = array_map(function($action) use ($output) {
934 return $action->export_for_template($output);
935 }, $actions);
936 $data->hasactions = !empty($data->actions);
938 return $data;
944 * Simple form with just one select field that gets submitted automatically.
946 * If JS not enabled small go button is printed too.
948 * @copyright 2009 Petr Skoda
949 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
950 * @since Moodle 2.0
951 * @package core
952 * @category output
954 class single_select implements renderable, templatable {
957 * @var moodle_url Target url - includes hidden fields
959 var $url;
962 * @var string Name of the select element.
964 var $name;
967 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
968 * it is also possible to specify optgroup as complex label array ex.:
969 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
970 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
972 var $options;
975 * @var string Selected option
977 var $selected;
980 * @var array Nothing selected
982 var $nothing;
985 * @var array Extra select field attributes
987 var $attributes = array();
990 * @var string Button label
992 var $label = '';
995 * @var array Button label's attributes
997 var $labelattributes = array();
1000 * @var string Form submit method post or get
1002 var $method = 'get';
1005 * @var string Wrapping div class
1007 var $class = 'singleselect';
1010 * @var bool True if button disabled, false if normal
1012 var $disabled = false;
1015 * @var string Button tooltip
1017 var $tooltip = null;
1020 * @var string Form id
1022 var $formid = null;
1025 * @var help_icon The help icon for this element.
1027 var $helpicon = null;
1030 * Constructor
1031 * @param moodle_url $url form action target, includes hidden fields
1032 * @param string $name name of selection field - the changing parameter in url
1033 * @param array $options list of options
1034 * @param string $selected selected element
1035 * @param array $nothing
1036 * @param string $formid
1038 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1039 $this->url = $url;
1040 $this->name = $name;
1041 $this->options = $options;
1042 $this->selected = $selected;
1043 $this->nothing = $nothing;
1044 $this->formid = $formid;
1048 * Shortcut for adding a JS confirm dialog when the button is clicked.
1049 * The message must be a yes/no question.
1051 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
1053 public function add_confirm_action($confirmmessage) {
1054 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
1058 * Add action to the button.
1060 * @param component_action $action
1062 public function add_action(component_action $action) {
1063 $this->actions[] = $action;
1067 * Adds help icon.
1069 * @deprecated since Moodle 2.0
1071 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1072 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1076 * Adds help icon.
1078 * @param string $identifier The keyword that defines a help page
1079 * @param string $component
1081 public function set_help_icon($identifier, $component = 'moodle') {
1082 $this->helpicon = new help_icon($identifier, $component);
1086 * Sets select's label
1088 * @param string $label
1089 * @param array $attributes (optional)
1091 public function set_label($label, $attributes = array()) {
1092 $this->label = $label;
1093 $this->labelattributes = $attributes;
1098 * Export data.
1100 * @param renderer_base $output Renderer.
1101 * @return stdClass
1103 public function export_for_template(renderer_base $output) {
1104 $attributes = $this->attributes;
1106 $data = new stdClass();
1107 $data->name = $this->name;
1108 $data->method = $this->method;
1109 $data->action = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
1110 $data->classes = $this->class;
1111 $data->label = $this->label;
1112 $data->disabled = $this->disabled;
1113 $data->title = $this->tooltip;
1114 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('single_select_f');
1115 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('single_select');
1117 // Select element attributes.
1118 // Unset attributes that are already predefined in the template.
1119 unset($attributes['id']);
1120 unset($attributes['class']);
1121 unset($attributes['name']);
1122 unset($attributes['title']);
1123 unset($attributes['disabled']);
1125 // Map the attributes.
1126 $data->attributes = array_map(function($key) use ($attributes) {
1127 return ['name' => $key, 'value' => $attributes[$key]];
1128 }, array_keys($attributes));
1130 // Form parameters.
1131 $params = $this->url->params();
1132 if ($this->method === 'post') {
1133 $params['sesskey'] = sesskey();
1135 $data->params = array_map(function($key) use ($params) {
1136 return ['name' => $key, 'value' => $params[$key]];
1137 }, array_keys($params));
1139 // Select options.
1140 $hasnothing = false;
1141 if (is_string($this->nothing) && $this->nothing !== '') {
1142 $nothing = ['' => $this->nothing];
1143 $hasnothing = true;
1144 $nothingkey = '';
1145 } else if (is_array($this->nothing)) {
1146 $nothingvalue = reset($this->nothing);
1147 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1148 $nothing = [key($this->nothing) => get_string('choosedots')];
1149 } else {
1150 $nothing = $this->nothing;
1152 $hasnothing = true;
1153 $nothingkey = key($this->nothing);
1155 if ($hasnothing) {
1156 $options = $nothing + $this->options;
1157 } else {
1158 $options = $this->options;
1161 foreach ($options as $value => $name) {
1162 if (is_array($options[$value])) {
1163 foreach ($options[$value] as $optgroupname => $optgroupvalues) {
1164 $sublist = [];
1165 foreach ($optgroupvalues as $optvalue => $optname) {
1166 $option = [
1167 'value' => $optvalue,
1168 'name' => $optname,
1169 'selected' => strval($this->selected) === strval($optvalue),
1172 if ($hasnothing && $nothingkey === $optvalue) {
1173 $option['ignore'] = 'data-ignore';
1176 $sublist[] = $option;
1178 $data->options[] = [
1179 'name' => $optgroupname,
1180 'optgroup' => true,
1181 'options' => $sublist
1184 } else {
1185 $option = [
1186 'value' => $value,
1187 'name' => $options[$value],
1188 'selected' => strval($this->selected) === strval($value),
1189 'optgroup' => false
1192 if ($hasnothing && $nothingkey === $value) {
1193 $option['ignore'] = 'data-ignore';
1196 $data->options[] = $option;
1200 // Label attributes.
1201 $data->labelattributes = [];
1202 // Unset label attributes that are already in the template.
1203 unset($this->labelattributes['for']);
1204 // Map the label attributes.
1205 foreach ($this->labelattributes as $key => $value) {
1206 $data->labelattributes[] = ['name' => $key, 'value' => $value];
1209 // Help icon.
1210 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1212 return $data;
1217 * Simple URL selection widget description.
1219 * @copyright 2009 Petr Skoda
1220 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1221 * @since Moodle 2.0
1222 * @package core
1223 * @category output
1225 class url_select implements renderable, templatable {
1227 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
1228 * it is also possible to specify optgroup as complex label array ex.:
1229 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1230 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1232 var $urls;
1235 * @var string Selected option
1237 var $selected;
1240 * @var array Nothing selected
1242 var $nothing;
1245 * @var array Extra select field attributes
1247 var $attributes = array();
1250 * @var string Button label
1252 var $label = '';
1255 * @var array Button label's attributes
1257 var $labelattributes = array();
1260 * @var string Wrapping div class
1262 var $class = 'urlselect';
1265 * @var bool True if button disabled, false if normal
1267 var $disabled = false;
1270 * @var string Button tooltip
1272 var $tooltip = null;
1275 * @var string Form id
1277 var $formid = null;
1280 * @var help_icon The help icon for this element.
1282 var $helpicon = null;
1285 * @var string If set, makes button visible with given name for button
1287 var $showbutton = null;
1290 * Constructor
1291 * @param array $urls list of options
1292 * @param string $selected selected element
1293 * @param array $nothing
1294 * @param string $formid
1295 * @param string $showbutton Set to text of button if it should be visible
1296 * or null if it should be hidden (hidden version always has text 'go')
1298 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
1299 $this->urls = $urls;
1300 $this->selected = $selected;
1301 $this->nothing = $nothing;
1302 $this->formid = $formid;
1303 $this->showbutton = $showbutton;
1307 * Adds help icon.
1309 * @deprecated since Moodle 2.0
1311 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1312 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1316 * Adds help icon.
1318 * @param string $identifier The keyword that defines a help page
1319 * @param string $component
1321 public function set_help_icon($identifier, $component = 'moodle') {
1322 $this->helpicon = new help_icon($identifier, $component);
1326 * Sets select's label
1328 * @param string $label
1329 * @param array $attributes (optional)
1331 public function set_label($label, $attributes = array()) {
1332 $this->label = $label;
1333 $this->labelattributes = $attributes;
1337 * Clean a URL.
1339 * @param string $value The URL.
1340 * @return The cleaned URL.
1342 protected function clean_url($value) {
1343 global $CFG;
1345 if (empty($value)) {
1346 // Nothing.
1348 } else if (strpos($value, $CFG->wwwroot . '/') === 0) {
1349 $value = str_replace($CFG->wwwroot, '', $value);
1351 } else if (strpos($value, '/') !== 0) {
1352 debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER);
1355 return $value;
1359 * Flatten the options for Mustache.
1361 * This also cleans the URLs.
1363 * @param array $options The options.
1364 * @param array $nothing The nothing option.
1365 * @return array
1367 protected function flatten_options($options, $nothing) {
1368 $flattened = [];
1370 foreach ($options as $value => $option) {
1371 if (is_array($option)) {
1372 foreach ($option as $groupname => $optoptions) {
1373 if (!isset($flattened[$groupname])) {
1374 $flattened[$groupname] = [
1375 'name' => $groupname,
1376 'isgroup' => true,
1377 'options' => []
1380 foreach ($optoptions as $optvalue => $optoption) {
1381 $cleanedvalue = $this->clean_url($optvalue);
1382 $flattened[$groupname]['options'][$cleanedvalue] = [
1383 'name' => $optoption,
1384 'value' => $cleanedvalue,
1385 'selected' => $this->selected == $optvalue,
1390 } else {
1391 $cleanedvalue = $this->clean_url($value);
1392 $flattened[$cleanedvalue] = [
1393 'name' => $option,
1394 'value' => $cleanedvalue,
1395 'selected' => $this->selected == $value,
1400 if (!empty($nothing)) {
1401 $value = key($nothing);
1402 $name = reset($nothing);
1403 $flattened = [
1404 $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value]
1405 ] + $flattened;
1408 // Make non-associative array.
1409 foreach ($flattened as $key => $value) {
1410 if (!empty($value['options'])) {
1411 $flattened[$key]['options'] = array_values($value['options']);
1414 $flattened = array_values($flattened);
1416 return $flattened;
1420 * Export for template.
1422 * @param renderer_base $output Renderer.
1423 * @return stdClass
1425 public function export_for_template(renderer_base $output) {
1426 $attributes = $this->attributes;
1428 $data = new stdClass();
1429 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('url_select_f');
1430 $data->classes = $this->class;
1431 $data->label = $this->label;
1432 $data->disabled = $this->disabled;
1433 $data->title = $this->tooltip;
1434 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('url_select');
1435 $data->sesskey = sesskey();
1436 $data->action = (new moodle_url('/course/jumpto.php'))->out(false);
1438 // Remove attributes passed as property directly.
1439 unset($attributes['class']);
1440 unset($attributes['id']);
1441 unset($attributes['name']);
1442 unset($attributes['title']);
1443 unset($attributes['disabled']);
1445 $data->showbutton = $this->showbutton;
1447 // Select options.
1448 $nothing = false;
1449 if (is_string($this->nothing) && $this->nothing !== '') {
1450 $nothing = ['' => $this->nothing];
1451 } else if (is_array($this->nothing)) {
1452 $nothingvalue = reset($this->nothing);
1453 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1454 $nothing = [key($this->nothing) => get_string('choosedots')];
1455 } else {
1456 $nothing = $this->nothing;
1459 $data->options = $this->flatten_options($this->urls, $nothing);
1461 // Label attributes.
1462 $data->labelattributes = [];
1463 // Unset label attributes that are already in the template.
1464 unset($this->labelattributes['for']);
1465 // Map the label attributes.
1466 foreach ($this->labelattributes as $key => $value) {
1467 $data->labelattributes[] = ['name' => $key, 'value' => $value];
1470 // Help icon.
1471 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1473 // Finally all the remaining attributes.
1474 $data->attributes = [];
1475 foreach ($attributes as $key => $value) {
1476 $data->attributes[] = ['name' => $key, 'value' => $value];
1479 return $data;
1484 * Data structure describing html link with special action attached.
1486 * @copyright 2010 Petr Skoda
1487 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1488 * @since Moodle 2.0
1489 * @package core
1490 * @category output
1492 class action_link implements renderable {
1495 * @var moodle_url Href url
1497 public $url;
1500 * @var string Link text HTML fragment
1502 public $text;
1505 * @var array HTML attributes
1507 public $attributes;
1510 * @var array List of actions attached to link
1512 public $actions;
1515 * @var pix_icon Optional pix icon to render with the link
1517 public $icon;
1520 * Constructor
1521 * @param moodle_url $url
1522 * @param string $text HTML fragment
1523 * @param component_action $action
1524 * @param array $attributes associative array of html link attributes + disabled
1525 * @param pix_icon $icon optional pix_icon to render with the link text
1527 public function __construct(moodle_url $url,
1528 $text,
1529 component_action $action=null,
1530 array $attributes=null,
1531 pix_icon $icon=null) {
1532 $this->url = clone($url);
1533 $this->text = $text;
1534 if (empty($attributes['id'])) {
1535 $attributes['id'] = html_writer::random_id('action_link');
1537 $this->attributes = (array)$attributes;
1538 if ($action) {
1539 $this->add_action($action);
1541 $this->icon = $icon;
1545 * Add action to the link.
1547 * @param component_action $action
1549 public function add_action(component_action $action) {
1550 $this->actions[] = $action;
1554 * Adds a CSS class to this action link object
1555 * @param string $class
1557 public function add_class($class) {
1558 if (empty($this->attributes['class'])) {
1559 $this->attributes['class'] = $class;
1560 } else {
1561 $this->attributes['class'] .= ' ' . $class;
1566 * Returns true if the specified class has been added to this link.
1567 * @param string $class
1568 * @return bool
1570 public function has_class($class) {
1571 return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
1575 * Return the rendered HTML for the icon. Useful for rendering action links in a template.
1576 * @return string
1578 public function get_icon_html() {
1579 global $OUTPUT;
1580 if (!$this->icon) {
1581 return '';
1583 return $OUTPUT->render($this->icon);
1587 * Export for template.
1589 * @param renderer_base $output The renderer.
1590 * @return stdClass
1592 public function export_for_template(renderer_base $output) {
1593 $data = new stdClass();
1594 $attributes = $this->attributes;
1596 $data->id = $attributes['id'];
1597 unset($attributes['id']);
1599 $data->disabled = !empty($attributes['disabled']);
1600 unset($attributes['disabled']);
1602 $data->text = $this->text instanceof renderable ? $output->render($this->text) : (string) $this->text;
1603 $data->url = $this->url ? $this->url->out(false) : '';
1604 $data->icon = $this->icon ? $this->icon->export_for_pix() : null;
1605 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
1606 unset($attributes['class']);
1608 $data->attributes = array_map(function($key, $value) {
1609 return [
1610 'name' => $key,
1611 'value' => $value
1613 }, array_keys($attributes), $attributes);
1615 $data->actions = array_map(function($action) use ($output) {
1616 return $action->export_for_template($output);
1617 }, !empty($this->actions) ? $this->actions : []);
1618 $data->hasactions = !empty($this->actions);
1620 return $data;
1625 * Simple html output class
1627 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1628 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1629 * @since Moodle 2.0
1630 * @package core
1631 * @category output
1633 class html_writer {
1636 * Outputs a tag with attributes and contents
1638 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1639 * @param string $contents What goes between the opening and closing tags
1640 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1641 * @return string HTML fragment
1643 public static function tag($tagname, $contents, array $attributes = null) {
1644 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1648 * Outputs an opening tag with attributes
1650 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1651 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1652 * @return string HTML fragment
1654 public static function start_tag($tagname, array $attributes = null) {
1655 return '<' . $tagname . self::attributes($attributes) . '>';
1659 * Outputs a closing tag
1661 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1662 * @return string HTML fragment
1664 public static function end_tag($tagname) {
1665 return '</' . $tagname . '>';
1669 * Outputs an empty tag with attributes
1671 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1672 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1673 * @return string HTML fragment
1675 public static function empty_tag($tagname, array $attributes = null) {
1676 return '<' . $tagname . self::attributes($attributes) . ' />';
1680 * Outputs a tag, but only if the contents are not empty
1682 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1683 * @param string $contents What goes between the opening and closing tags
1684 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1685 * @return string HTML fragment
1687 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1688 if ($contents === '' || is_null($contents)) {
1689 return '';
1691 return self::tag($tagname, $contents, $attributes);
1695 * Outputs a HTML attribute and value
1697 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1698 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1699 * @return string HTML fragment
1701 public static function attribute($name, $value) {
1702 if ($value instanceof moodle_url) {
1703 return ' ' . $name . '="' . $value->out() . '"';
1706 // special case, we do not want these in output
1707 if ($value === null) {
1708 return '';
1711 // no sloppy trimming here!
1712 return ' ' . $name . '="' . s($value) . '"';
1716 * Outputs a list of HTML attributes and values
1718 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1719 * The values will be escaped with {@link s()}
1720 * @return string HTML fragment
1722 public static function attributes(array $attributes = null) {
1723 $attributes = (array)$attributes;
1724 $output = '';
1725 foreach ($attributes as $name => $value) {
1726 $output .= self::attribute($name, $value);
1728 return $output;
1732 * Generates a simple image tag with attributes.
1734 * @param string $src The source of image
1735 * @param string $alt The alternate text for image
1736 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1737 * @return string HTML fragment
1739 public static function img($src, $alt, array $attributes = null) {
1740 $attributes = (array)$attributes;
1741 $attributes['src'] = $src;
1742 $attributes['alt'] = $alt;
1744 return self::empty_tag('img', $attributes);
1748 * Generates random html element id.
1750 * @staticvar int $counter
1751 * @staticvar type $uniq
1752 * @param string $base A string fragment that will be included in the random ID.
1753 * @return string A unique ID
1755 public static function random_id($base='random') {
1756 static $counter = 0;
1757 static $uniq;
1759 if (!isset($uniq)) {
1760 $uniq = uniqid();
1763 $counter++;
1764 return $base.$uniq.$counter;
1768 * Generates a simple html link
1770 * @param string|moodle_url $url The URL
1771 * @param string $text The text
1772 * @param array $attributes HTML attributes
1773 * @return string HTML fragment
1775 public static function link($url, $text, array $attributes = null) {
1776 $attributes = (array)$attributes;
1777 $attributes['href'] = $url;
1778 return self::tag('a', $text, $attributes);
1782 * Generates a simple checkbox with optional label
1784 * @param string $name The name of the checkbox
1785 * @param string $value The value of the checkbox
1786 * @param bool $checked Whether the checkbox is checked
1787 * @param string $label The label for the checkbox
1788 * @param array $attributes Any attributes to apply to the checkbox
1789 * @param array $labelattributes Any attributes to apply to the label, if present
1790 * @return string html fragment
1792 public static function checkbox($name, $value, $checked = true, $label = '',
1793 array $attributes = null, array $labelattributes = null) {
1794 $attributes = (array) $attributes;
1795 $output = '';
1797 if ($label !== '' and !is_null($label)) {
1798 if (empty($attributes['id'])) {
1799 $attributes['id'] = self::random_id('checkbox_');
1802 $attributes['type'] = 'checkbox';
1803 $attributes['value'] = $value;
1804 $attributes['name'] = $name;
1805 $attributes['checked'] = $checked ? 'checked' : null;
1807 $output .= self::empty_tag('input', $attributes);
1809 if ($label !== '' and !is_null($label)) {
1810 $labelattributes = (array) $labelattributes;
1811 $labelattributes['for'] = $attributes['id'];
1812 $output .= self::tag('label', $label, $labelattributes);
1815 return $output;
1819 * Generates a simple select yes/no form field
1821 * @param string $name name of select element
1822 * @param bool $selected
1823 * @param array $attributes - html select element attributes
1824 * @return string HTML fragment
1826 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1827 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1828 return self::select($options, $name, $selected, null, $attributes);
1832 * Generates a simple select form field
1834 * Note this function does HTML escaping on the optgroup labels, but not on the choice labels.
1836 * @param array $options associative array value=>label ex.:
1837 * array(1=>'One, 2=>Two)
1838 * it is also possible to specify optgroup as complex label array ex.:
1839 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1840 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1841 * @param string $name name of select element
1842 * @param string|array $selected value or array of values depending on multiple attribute
1843 * @param array|bool $nothing add nothing selected option, or false of not added
1844 * @param array $attributes html select element attributes
1845 * @return string HTML fragment
1847 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1848 $attributes = (array)$attributes;
1849 if (is_array($nothing)) {
1850 foreach ($nothing as $k=>$v) {
1851 if ($v === 'choose' or $v === 'choosedots') {
1852 $nothing[$k] = get_string('choosedots');
1855 $options = $nothing + $options; // keep keys, do not override
1857 } else if (is_string($nothing) and $nothing !== '') {
1858 // BC
1859 $options = array(''=>$nothing) + $options;
1862 // we may accept more values if multiple attribute specified
1863 $selected = (array)$selected;
1864 foreach ($selected as $k=>$v) {
1865 $selected[$k] = (string)$v;
1868 if (!isset($attributes['id'])) {
1869 $id = 'menu'.$name;
1870 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1871 $id = str_replace('[', '', $id);
1872 $id = str_replace(']', '', $id);
1873 $attributes['id'] = $id;
1876 if (!isset($attributes['class'])) {
1877 $class = 'menu'.$name;
1878 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1879 $class = str_replace('[', '', $class);
1880 $class = str_replace(']', '', $class);
1881 $attributes['class'] = $class;
1883 $attributes['class'] = 'select custom-select ' . $attributes['class']; // Add 'select' selector always.
1885 $attributes['name'] = $name;
1887 if (!empty($attributes['disabled'])) {
1888 $attributes['disabled'] = 'disabled';
1889 } else {
1890 unset($attributes['disabled']);
1893 $output = '';
1894 foreach ($options as $value=>$label) {
1895 if (is_array($label)) {
1896 // ignore key, it just has to be unique
1897 $output .= self::select_optgroup(key($label), current($label), $selected);
1898 } else {
1899 $output .= self::select_option($label, $value, $selected);
1902 return self::tag('select', $output, $attributes);
1906 * Returns HTML to display a select box option.
1908 * @param string $label The label to display as the option.
1909 * @param string|int $value The value the option represents
1910 * @param array $selected An array of selected options
1911 * @return string HTML fragment
1913 private static function select_option($label, $value, array $selected) {
1914 $attributes = array();
1915 $value = (string)$value;
1916 if (in_array($value, $selected, true)) {
1917 $attributes['selected'] = 'selected';
1919 $attributes['value'] = $value;
1920 return self::tag('option', $label, $attributes);
1924 * Returns HTML to display a select box option group.
1926 * @param string $groupname The label to use for the group
1927 * @param array $options The options in the group
1928 * @param array $selected An array of selected values.
1929 * @return string HTML fragment.
1931 private static function select_optgroup($groupname, $options, array $selected) {
1932 if (empty($options)) {
1933 return '';
1935 $attributes = array('label'=>$groupname);
1936 $output = '';
1937 foreach ($options as $value=>$label) {
1938 $output .= self::select_option($label, $value, $selected);
1940 return self::tag('optgroup', $output, $attributes);
1944 * This is a shortcut for making an hour selector menu.
1946 * @param string $type The type of selector (years, months, days, hours, minutes)
1947 * @param string $name fieldname
1948 * @param int $currenttime A default timestamp in GMT
1949 * @param int $step minute spacing
1950 * @param array $attributes - html select element attributes
1951 * @return HTML fragment
1953 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1954 global $OUTPUT;
1956 if (!$currenttime) {
1957 $currenttime = time();
1959 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1960 $currentdate = $calendartype->timestamp_to_date_array($currenttime);
1961 $userdatetype = $type;
1962 $timeunits = array();
1964 switch ($type) {
1965 case 'years':
1966 $timeunits = $calendartype->get_years();
1967 $userdatetype = 'year';
1968 break;
1969 case 'months':
1970 $timeunits = $calendartype->get_months();
1971 $userdatetype = 'month';
1972 $currentdate['month'] = (int)$currentdate['mon'];
1973 break;
1974 case 'days':
1975 $timeunits = $calendartype->get_days();
1976 $userdatetype = 'mday';
1977 break;
1978 case 'hours':
1979 for ($i=0; $i<=23; $i++) {
1980 $timeunits[$i] = sprintf("%02d",$i);
1982 break;
1983 case 'minutes':
1984 if ($step != 1) {
1985 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1988 for ($i=0; $i<=59; $i+=$step) {
1989 $timeunits[$i] = sprintf("%02d",$i);
1991 break;
1992 default:
1993 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1996 $attributes = (array) $attributes;
1997 $data = (object) [
1998 'name' => $name,
1999 'id' => !empty($attributes['id']) ? $attributes['id'] : self::random_id('ts_'),
2000 'label' => get_string(substr($type, 0, -1), 'form'),
2001 'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) {
2002 return [
2003 'name' => $timeunits[$value],
2004 'value' => $value,
2005 'selected' => $currentdate[$userdatetype] == $value
2007 }, array_keys($timeunits)),
2010 unset($attributes['id']);
2011 unset($attributes['name']);
2012 $data->attributes = array_map(function($name) use ($attributes) {
2013 return [
2014 'name' => $name,
2015 'value' => $attributes[$name]
2017 }, array_keys($attributes));
2019 return $OUTPUT->render_from_template('core/select_time', $data);
2023 * Shortcut for quick making of lists
2025 * Note: 'list' is a reserved keyword ;-)
2027 * @param array $items
2028 * @param array $attributes
2029 * @param string $tag ul or ol
2030 * @return string
2032 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
2033 $output = html_writer::start_tag($tag, $attributes)."\n";
2034 foreach ($items as $item) {
2035 $output .= html_writer::tag('li', $item)."\n";
2037 $output .= html_writer::end_tag($tag);
2038 return $output;
2042 * Returns hidden input fields created from url parameters.
2044 * @param moodle_url $url
2045 * @param array $exclude list of excluded parameters
2046 * @return string HTML fragment
2048 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
2049 $exclude = (array)$exclude;
2050 $params = $url->params();
2051 foreach ($exclude as $key) {
2052 unset($params[$key]);
2055 $output = '';
2056 foreach ($params as $key => $value) {
2057 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
2058 $output .= self::empty_tag('input', $attributes)."\n";
2060 return $output;
2064 * Generate a script tag containing the the specified code.
2066 * @param string $jscode the JavaScript code
2067 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
2068 * @return string HTML, the code wrapped in <script> tags.
2070 public static function script($jscode, $url=null) {
2071 if ($jscode) {
2072 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n") . "\n";
2074 } else if ($url) {
2075 return self::tag('script', '', ['src' => $url]) . "\n";
2077 } else {
2078 return '';
2083 * Renders HTML table
2085 * This method may modify the passed instance by adding some default properties if they are not set yet.
2086 * If this is not what you want, you should make a full clone of your data before passing them to this
2087 * method. In most cases this is not an issue at all so we do not clone by default for performance
2088 * and memory consumption reasons.
2090 * @param html_table $table data to be rendered
2091 * @return string HTML code
2093 public static function table(html_table $table) {
2094 // prepare table data and populate missing properties with reasonable defaults
2095 if (!empty($table->align)) {
2096 foreach ($table->align as $key => $aa) {
2097 if ($aa) {
2098 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
2099 } else {
2100 $table->align[$key] = null;
2104 if (!empty($table->size)) {
2105 foreach ($table->size as $key => $ss) {
2106 if ($ss) {
2107 $table->size[$key] = 'width:'. $ss .';';
2108 } else {
2109 $table->size[$key] = null;
2113 if (!empty($table->wrap)) {
2114 foreach ($table->wrap as $key => $ww) {
2115 if ($ww) {
2116 $table->wrap[$key] = 'white-space:nowrap;';
2117 } else {
2118 $table->wrap[$key] = '';
2122 if (!empty($table->head)) {
2123 foreach ($table->head as $key => $val) {
2124 if (!isset($table->align[$key])) {
2125 $table->align[$key] = null;
2127 if (!isset($table->size[$key])) {
2128 $table->size[$key] = null;
2130 if (!isset($table->wrap[$key])) {
2131 $table->wrap[$key] = null;
2136 if (empty($table->attributes['class'])) {
2137 $table->attributes['class'] = 'generaltable';
2139 if (!empty($table->tablealign)) {
2140 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
2143 // explicitly assigned properties override those defined via $table->attributes
2144 $table->attributes['class'] = trim($table->attributes['class']);
2145 $attributes = array_merge($table->attributes, array(
2146 'id' => $table->id,
2147 'width' => $table->width,
2148 'summary' => $table->summary,
2149 'cellpadding' => $table->cellpadding,
2150 'cellspacing' => $table->cellspacing,
2152 $output = html_writer::start_tag('table', $attributes) . "\n";
2154 $countcols = 0;
2156 // Output a caption if present.
2157 if (!empty($table->caption)) {
2158 $captionattributes = array();
2159 if ($table->captionhide) {
2160 $captionattributes['class'] = 'accesshide';
2162 $output .= html_writer::tag(
2163 'caption',
2164 $table->caption,
2165 $captionattributes
2169 if (!empty($table->head)) {
2170 $countcols = count($table->head);
2172 $output .= html_writer::start_tag('thead', array()) . "\n";
2173 $output .= html_writer::start_tag('tr', array()) . "\n";
2174 $keys = array_keys($table->head);
2175 $lastkey = end($keys);
2177 foreach ($table->head as $key => $heading) {
2178 // Convert plain string headings into html_table_cell objects
2179 if (!($heading instanceof html_table_cell)) {
2180 $headingtext = $heading;
2181 $heading = new html_table_cell();
2182 $heading->text = $headingtext;
2183 $heading->header = true;
2186 if ($heading->header !== false) {
2187 $heading->header = true;
2190 $tagtype = 'td';
2191 if ($heading->header && (string)$heading->text != '') {
2192 $tagtype = 'th';
2195 $heading->attributes['class'] .= ' header c' . $key;
2196 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
2197 $heading->colspan = $table->headspan[$key];
2198 $countcols += $table->headspan[$key] - 1;
2201 if ($key == $lastkey) {
2202 $heading->attributes['class'] .= ' lastcol';
2204 if (isset($table->colclasses[$key])) {
2205 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
2207 $heading->attributes['class'] = trim($heading->attributes['class']);
2208 $attributes = array_merge($heading->attributes, [
2209 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
2210 'colspan' => $heading->colspan,
2213 if ($tagtype == 'th') {
2214 $attributes['scope'] = !empty($heading->scope) ? $heading->scope : 'col';
2217 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
2219 $output .= html_writer::end_tag('tr') . "\n";
2220 $output .= html_writer::end_tag('thead') . "\n";
2222 if (empty($table->data)) {
2223 // For valid XHTML strict every table must contain either a valid tr
2224 // or a valid tbody... both of which must contain a valid td
2225 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
2226 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
2227 $output .= html_writer::end_tag('tbody');
2231 if (!empty($table->data)) {
2232 $keys = array_keys($table->data);
2233 $lastrowkey = end($keys);
2234 $output .= html_writer::start_tag('tbody', array());
2236 foreach ($table->data as $key => $row) {
2237 if (($row === 'hr') && ($countcols)) {
2238 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
2239 } else {
2240 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
2241 if (!($row instanceof html_table_row)) {
2242 $newrow = new html_table_row();
2244 foreach ($row as $cell) {
2245 if (!($cell instanceof html_table_cell)) {
2246 $cell = new html_table_cell($cell);
2248 $newrow->cells[] = $cell;
2250 $row = $newrow;
2253 if (isset($table->rowclasses[$key])) {
2254 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
2257 if ($key == $lastrowkey) {
2258 $row->attributes['class'] .= ' lastrow';
2261 // Explicitly assigned properties should override those defined in the attributes.
2262 $row->attributes['class'] = trim($row->attributes['class']);
2263 $trattributes = array_merge($row->attributes, array(
2264 'id' => $row->id,
2265 'style' => $row->style,
2267 $output .= html_writer::start_tag('tr', $trattributes) . "\n";
2268 $keys2 = array_keys($row->cells);
2269 $lastkey = end($keys2);
2271 $gotlastkey = false; //flag for sanity checking
2272 foreach ($row->cells as $key => $cell) {
2273 if ($gotlastkey) {
2274 //This should never happen. Why do we have a cell after the last cell?
2275 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
2278 if (!($cell instanceof html_table_cell)) {
2279 $mycell = new html_table_cell();
2280 $mycell->text = $cell;
2281 $cell = $mycell;
2284 if (($cell->header === true) && empty($cell->scope)) {
2285 $cell->scope = 'row';
2288 if (isset($table->colclasses[$key])) {
2289 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
2292 $cell->attributes['class'] .= ' cell c' . $key;
2293 if ($key == $lastkey) {
2294 $cell->attributes['class'] .= ' lastcol';
2295 $gotlastkey = true;
2297 $tdstyle = '';
2298 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
2299 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
2300 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
2301 $cell->attributes['class'] = trim($cell->attributes['class']);
2302 $tdattributes = array_merge($cell->attributes, array(
2303 'style' => $tdstyle . $cell->style,
2304 'colspan' => $cell->colspan,
2305 'rowspan' => $cell->rowspan,
2306 'id' => $cell->id,
2307 'abbr' => $cell->abbr,
2308 'scope' => $cell->scope,
2310 $tagtype = 'td';
2311 if ($cell->header === true) {
2312 $tagtype = 'th';
2314 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
2317 $output .= html_writer::end_tag('tr') . "\n";
2319 $output .= html_writer::end_tag('tbody') . "\n";
2321 $output .= html_writer::end_tag('table') . "\n";
2323 if ($table->responsive) {
2324 return self::div($output, 'table-responsive');
2327 return $output;
2331 * Renders form element label
2333 * By default, the label is suffixed with a label separator defined in the
2334 * current language pack (colon by default in the English lang pack).
2335 * Adding the colon can be explicitly disabled if needed. Label separators
2336 * are put outside the label tag itself so they are not read by
2337 * screenreaders (accessibility).
2339 * Parameter $for explicitly associates the label with a form control. When
2340 * set, the value of this attribute must be the same as the value of
2341 * the id attribute of the form control in the same document. When null,
2342 * the label being defined is associated with the control inside the label
2343 * element.
2345 * @param string $text content of the label tag
2346 * @param string|null $for id of the element this label is associated with, null for no association
2347 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
2348 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
2349 * @return string HTML of the label element
2351 public static function label($text, $for, $colonize = true, array $attributes=array()) {
2352 if (!is_null($for)) {
2353 $attributes = array_merge($attributes, array('for' => $for));
2355 $text = trim($text);
2356 $label = self::tag('label', $text, $attributes);
2358 // TODO MDL-12192 $colonize disabled for now yet
2359 // if (!empty($text) and $colonize) {
2360 // // the $text may end with the colon already, though it is bad string definition style
2361 // $colon = get_string('labelsep', 'langconfig');
2362 // if (!empty($colon)) {
2363 // $trimmed = trim($colon);
2364 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
2365 // //debugging('The label text should not end with colon or other label separator,
2366 // // please fix the string definition.', DEBUG_DEVELOPER);
2367 // } else {
2368 // $label .= $colon;
2369 // }
2370 // }
2371 // }
2373 return $label;
2377 * Combines a class parameter with other attributes. Aids in code reduction
2378 * because the class parameter is very frequently used.
2380 * If the class attribute is specified both in the attributes and in the
2381 * class parameter, the two values are combined with a space between.
2383 * @param string $class Optional CSS class (or classes as space-separated list)
2384 * @param array $attributes Optional other attributes as array
2385 * @return array Attributes (or null if still none)
2387 private static function add_class($class = '', array $attributes = null) {
2388 if ($class !== '') {
2389 $classattribute = array('class' => $class);
2390 if ($attributes) {
2391 if (array_key_exists('class', $attributes)) {
2392 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
2393 } else {
2394 $attributes = $classattribute + $attributes;
2396 } else {
2397 $attributes = $classattribute;
2400 return $attributes;
2404 * Creates a <div> tag. (Shortcut function.)
2406 * @param string $content HTML content of tag
2407 * @param string $class Optional CSS class (or classes as space-separated list)
2408 * @param array $attributes Optional other attributes as array
2409 * @return string HTML code for div
2411 public static function div($content, $class = '', array $attributes = null) {
2412 return self::tag('div', $content, self::add_class($class, $attributes));
2416 * Starts a <div> tag. (Shortcut function.)
2418 * @param string $class Optional CSS class (or classes as space-separated list)
2419 * @param array $attributes Optional other attributes as array
2420 * @return string HTML code for open div tag
2422 public static function start_div($class = '', array $attributes = null) {
2423 return self::start_tag('div', self::add_class($class, $attributes));
2427 * Ends a <div> tag. (Shortcut function.)
2429 * @return string HTML code for close div tag
2431 public static function end_div() {
2432 return self::end_tag('div');
2436 * Creates a <span> tag. (Shortcut function.)
2438 * @param string $content HTML content of tag
2439 * @param string $class Optional CSS class (or classes as space-separated list)
2440 * @param array $attributes Optional other attributes as array
2441 * @return string HTML code for span
2443 public static function span($content, $class = '', array $attributes = null) {
2444 return self::tag('span', $content, self::add_class($class, $attributes));
2448 * Starts a <span> tag. (Shortcut function.)
2450 * @param string $class Optional CSS class (or classes as space-separated list)
2451 * @param array $attributes Optional other attributes as array
2452 * @return string HTML code for open span tag
2454 public static function start_span($class = '', array $attributes = null) {
2455 return self::start_tag('span', self::add_class($class, $attributes));
2459 * Ends a <span> tag. (Shortcut function.)
2461 * @return string HTML code for close span tag
2463 public static function end_span() {
2464 return self::end_tag('span');
2469 * Simple javascript output class
2471 * @copyright 2010 Petr Skoda
2472 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2473 * @since Moodle 2.0
2474 * @package core
2475 * @category output
2477 class js_writer {
2480 * Returns javascript code calling the function
2482 * @param string $function function name, can be complex like Y.Event.purgeElement
2483 * @param array $arguments parameters
2484 * @param int $delay execution delay in seconds
2485 * @return string JS code fragment
2487 public static function function_call($function, array $arguments = null, $delay=0) {
2488 if ($arguments) {
2489 $arguments = array_map('json_encode', convert_to_array($arguments));
2490 $arguments = implode(', ', $arguments);
2491 } else {
2492 $arguments = '';
2494 $js = "$function($arguments);";
2496 if ($delay) {
2497 $delay = $delay * 1000; // in miliseconds
2498 $js = "setTimeout(function() { $js }, $delay);";
2500 return $js . "\n";
2504 * Special function which adds Y as first argument of function call.
2506 * @param string $function The function to call
2507 * @param array $extraarguments Any arguments to pass to it
2508 * @return string Some JS code
2510 public static function function_call_with_Y($function, array $extraarguments = null) {
2511 if ($extraarguments) {
2512 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
2513 $arguments = 'Y, ' . implode(', ', $extraarguments);
2514 } else {
2515 $arguments = 'Y';
2517 return "$function($arguments);\n";
2521 * Returns JavaScript code to initialise a new object
2523 * @param string $var If it is null then no var is assigned the new object.
2524 * @param string $class The class to initialise an object for.
2525 * @param array $arguments An array of args to pass to the init method.
2526 * @param array $requirements Any modules required for this class.
2527 * @param int $delay The delay before initialisation. 0 = no delay.
2528 * @return string Some JS code
2530 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
2531 if (is_array($arguments)) {
2532 $arguments = array_map('json_encode', convert_to_array($arguments));
2533 $arguments = implode(', ', $arguments);
2536 if ($var === null) {
2537 $js = "new $class(Y, $arguments);";
2538 } else if (strpos($var, '.')!==false) {
2539 $js = "$var = new $class(Y, $arguments);";
2540 } else {
2541 $js = "var $var = new $class(Y, $arguments);";
2544 if ($delay) {
2545 $delay = $delay * 1000; // in miliseconds
2546 $js = "setTimeout(function() { $js }, $delay);";
2549 if (count($requirements) > 0) {
2550 $requirements = implode("', '", $requirements);
2551 $js = "Y.use('$requirements', function(Y){ $js });";
2553 return $js."\n";
2557 * Returns code setting value to variable
2559 * @param string $name
2560 * @param mixed $value json serialised value
2561 * @param bool $usevar add var definition, ignored for nested properties
2562 * @return string JS code fragment
2564 public static function set_variable($name, $value, $usevar = true) {
2565 $output = '';
2567 if ($usevar) {
2568 if (strpos($name, '.')) {
2569 $output .= '';
2570 } else {
2571 $output .= 'var ';
2575 $output .= "$name = ".json_encode($value).";";
2577 return $output;
2581 * Writes event handler attaching code
2583 * @param array|string $selector standard YUI selector for elements, may be
2584 * array or string, element id is in the form "#idvalue"
2585 * @param string $event A valid DOM event (click, mousedown, change etc.)
2586 * @param string $function The name of the function to call
2587 * @param array $arguments An optional array of argument parameters to pass to the function
2588 * @return string JS code fragment
2590 public static function event_handler($selector, $event, $function, array $arguments = null) {
2591 $selector = json_encode($selector);
2592 $output = "Y.on('$event', $function, $selector, null";
2593 if (!empty($arguments)) {
2594 $output .= ', ' . json_encode($arguments);
2596 return $output . ");\n";
2601 * Holds all the information required to render a <table> by {@link core_renderer::table()}
2603 * Example of usage:
2604 * $t = new html_table();
2605 * ... // set various properties of the object $t as described below
2606 * echo html_writer::table($t);
2608 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
2609 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2610 * @since Moodle 2.0
2611 * @package core
2612 * @category output
2614 class html_table {
2617 * @var string Value to use for the id attribute of the table
2619 public $id = null;
2622 * @var array Attributes of HTML attributes for the <table> element
2624 public $attributes = array();
2627 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
2628 * For more control over the rendering of the headers, an array of html_table_cell objects
2629 * can be passed instead of an array of strings.
2631 * Example of usage:
2632 * $t->head = array('Student', 'Grade');
2634 public $head;
2637 * @var array An array that can be used to make a heading span multiple columns.
2638 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
2639 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
2641 * Example of usage:
2642 * $t->headspan = array(2,1);
2644 public $headspan;
2647 * @var array An array of column alignments.
2648 * The value is used as CSS 'text-align' property. Therefore, possible
2649 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
2650 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
2652 * Examples of usage:
2653 * $t->align = array(null, 'right');
2654 * or
2655 * $t->align[1] = 'right';
2657 public $align;
2660 * @var array The value is used as CSS 'size' property.
2662 * Examples of usage:
2663 * $t->size = array('50%', '50%');
2664 * or
2665 * $t->size[1] = '120px';
2667 public $size;
2670 * @var array An array of wrapping information.
2671 * The only possible value is 'nowrap' that sets the
2672 * CSS property 'white-space' to the value 'nowrap' in the given column.
2674 * Example of usage:
2675 * $t->wrap = array(null, 'nowrap');
2677 public $wrap;
2680 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2681 * $head specified, the string 'hr' (for horizontal ruler) can be used
2682 * instead of an array of cells data resulting in a divider rendered.
2684 * Example of usage with array of arrays:
2685 * $row1 = array('Harry Potter', '76 %');
2686 * $row2 = array('Hermione Granger', '100 %');
2687 * $t->data = array($row1, $row2);
2689 * Example with array of html_table_row objects: (used for more fine-grained control)
2690 * $cell1 = new html_table_cell();
2691 * $cell1->text = 'Harry Potter';
2692 * $cell1->colspan = 2;
2693 * $row1 = new html_table_row();
2694 * $row1->cells[] = $cell1;
2695 * $cell2 = new html_table_cell();
2696 * $cell2->text = 'Hermione Granger';
2697 * $cell3 = new html_table_cell();
2698 * $cell3->text = '100 %';
2699 * $row2 = new html_table_row();
2700 * $row2->cells = array($cell2, $cell3);
2701 * $t->data = array($row1, $row2);
2703 public $data = [];
2706 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2707 * @var string Width of the table, percentage of the page preferred.
2709 public $width = null;
2712 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2713 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2715 public $tablealign = null;
2718 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2719 * @var int Padding on each cell, in pixels
2721 public $cellpadding = null;
2724 * @var int Spacing between cells, in pixels
2725 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2727 public $cellspacing = null;
2730 * @var array Array of classes to add to particular rows, space-separated string.
2731 * Class 'lastrow' is added automatically for the last row in the table.
2733 * Example of usage:
2734 * $t->rowclasses[9] = 'tenth'
2736 public $rowclasses;
2739 * @var array An array of classes to add to every cell in a particular column,
2740 * space-separated string. Class 'cell' is added automatically by the renderer.
2741 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2742 * respectively. Class 'lastcol' is added automatically for all last cells
2743 * in a row.
2745 * Example of usage:
2746 * $t->colclasses = array(null, 'grade');
2748 public $colclasses;
2751 * @var string Description of the contents for screen readers.
2753 * The "summary" attribute on the "table" element is not supported in HTML5.
2754 * Consider describing the structure of the table in a "caption" element or in a "figure" element containing the table;
2755 * or, simplify the structure of the table so that no description is needed.
2757 * @deprecated since Moodle 3.9.
2759 public $summary;
2762 * @var string Caption for the table, typically a title.
2764 * Example of usage:
2765 * $t->caption = "TV Guide";
2767 public $caption;
2770 * @var bool Whether to hide the table's caption from sighted users.
2772 * Example of usage:
2773 * $t->caption = "TV Guide";
2774 * $t->captionhide = true;
2776 public $captionhide = false;
2778 /** @var bool Whether to make the table to be scrolled horizontally with ease. Make table responsive across all viewports. */
2779 public $responsive = true;
2782 * Constructor
2784 public function __construct() {
2785 $this->attributes['class'] = '';
2790 * Component representing a table row.
2792 * @copyright 2009 Nicolas Connault
2793 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2794 * @since Moodle 2.0
2795 * @package core
2796 * @category output
2798 class html_table_row {
2801 * @var string Value to use for the id attribute of the row.
2803 public $id = null;
2806 * @var array Array of html_table_cell objects
2808 public $cells = array();
2811 * @var string Value to use for the style attribute of the table row
2813 public $style = null;
2816 * @var array Attributes of additional HTML attributes for the <tr> element
2818 public $attributes = array();
2821 * Constructor
2822 * @param array $cells
2824 public function __construct(array $cells=null) {
2825 $this->attributes['class'] = '';
2826 $cells = (array)$cells;
2827 foreach ($cells as $cell) {
2828 if ($cell instanceof html_table_cell) {
2829 $this->cells[] = $cell;
2830 } else {
2831 $this->cells[] = new html_table_cell($cell);
2838 * Component representing a table cell.
2840 * @copyright 2009 Nicolas Connault
2841 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2842 * @since Moodle 2.0
2843 * @package core
2844 * @category output
2846 class html_table_cell {
2849 * @var string Value to use for the id attribute of the cell.
2851 public $id = null;
2854 * @var string The contents of the cell.
2856 public $text;
2859 * @var string Abbreviated version of the contents of the cell.
2861 public $abbr = null;
2864 * @var int Number of columns this cell should span.
2866 public $colspan = null;
2869 * @var int Number of rows this cell should span.
2871 public $rowspan = null;
2874 * @var string Defines a way to associate header cells and data cells in a table.
2876 public $scope = null;
2879 * @var bool Whether or not this cell is a header cell.
2881 public $header = null;
2884 * @var string Value to use for the style attribute of the table cell
2886 public $style = null;
2889 * @var array Attributes of additional HTML attributes for the <td> element
2891 public $attributes = array();
2894 * Constructs a table cell
2896 * @param string $text
2898 public function __construct($text = null) {
2899 $this->text = $text;
2900 $this->attributes['class'] = '';
2905 * Component representing a paging bar.
2907 * @copyright 2009 Nicolas Connault
2908 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2909 * @since Moodle 2.0
2910 * @package core
2911 * @category output
2913 class paging_bar implements renderable, templatable {
2916 * @var int The maximum number of pagelinks to display.
2918 public $maxdisplay = 18;
2921 * @var int The total number of entries to be pages through..
2923 public $totalcount;
2926 * @var int The page you are currently viewing.
2928 public $page;
2931 * @var int The number of entries that should be shown per page.
2933 public $perpage;
2936 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2937 * an equals sign and the page number.
2938 * If this is a moodle_url object then the pagevar param will be replaced by
2939 * the page no, for each page.
2941 public $baseurl;
2944 * @var string This is the variable name that you use for the pagenumber in your
2945 * code (ie. 'tablepage', 'blogpage', etc)
2947 public $pagevar;
2950 * @var string A HTML link representing the "previous" page.
2952 public $previouslink = null;
2955 * @var string A HTML link representing the "next" page.
2957 public $nextlink = null;
2960 * @var string A HTML link representing the first page.
2962 public $firstlink = null;
2965 * @var string A HTML link representing the last page.
2967 public $lastlink = null;
2970 * @var array An array of strings. One of them is just a string: the current page
2972 public $pagelinks = array();
2975 * Constructor paging_bar with only the required params.
2977 * @param int $totalcount The total number of entries available to be paged through
2978 * @param int $page The page you are currently viewing
2979 * @param int $perpage The number of entries that should be shown per page
2980 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2981 * @param string $pagevar name of page parameter that holds the page number
2983 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2984 $this->totalcount = $totalcount;
2985 $this->page = $page;
2986 $this->perpage = $perpage;
2987 $this->baseurl = $baseurl;
2988 $this->pagevar = $pagevar;
2992 * Prepares the paging bar for output.
2994 * This method validates the arguments set up for the paging bar and then
2995 * produces fragments of HTML to assist display later on.
2997 * @param renderer_base $output
2998 * @param moodle_page $page
2999 * @param string $target
3000 * @throws coding_exception
3002 public function prepare(renderer_base $output, moodle_page $page, $target) {
3003 if (!isset($this->totalcount) || is_null($this->totalcount)) {
3004 throw new coding_exception('paging_bar requires a totalcount value.');
3006 if (!isset($this->page) || is_null($this->page)) {
3007 throw new coding_exception('paging_bar requires a page value.');
3009 if (empty($this->perpage)) {
3010 throw new coding_exception('paging_bar requires a perpage value.');
3012 if (empty($this->baseurl)) {
3013 throw new coding_exception('paging_bar requires a baseurl value.');
3016 if ($this->totalcount > $this->perpage) {
3017 $pagenum = $this->page - 1;
3019 if ($this->page > 0) {
3020 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
3023 if ($this->perpage > 0) {
3024 $lastpage = ceil($this->totalcount / $this->perpage);
3025 } else {
3026 $lastpage = 1;
3029 if ($this->page > round(($this->maxdisplay/3)*2)) {
3030 $currpage = $this->page - round($this->maxdisplay/3);
3032 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
3033 } else {
3034 $currpage = 0;
3037 $displaycount = $displaypage = 0;
3039 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3040 $displaypage = $currpage + 1;
3042 if ($this->page == $currpage) {
3043 $this->pagelinks[] = html_writer::span($displaypage, 'current-page');
3044 } else {
3045 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
3046 $this->pagelinks[] = $pagelink;
3049 $displaycount++;
3050 $currpage++;
3053 if ($currpage < $lastpage) {
3054 $lastpageactual = $lastpage - 1;
3055 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
3058 $pagenum = $this->page + 1;
3060 if ($pagenum != $lastpage) {
3061 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
3067 * Export for template.
3069 * @param renderer_base $output The renderer.
3070 * @return stdClass
3072 public function export_for_template(renderer_base $output) {
3073 $data = new stdClass();
3074 $data->previous = null;
3075 $data->next = null;
3076 $data->first = null;
3077 $data->last = null;
3078 $data->label = get_string('page');
3079 $data->pages = [];
3080 $data->haspages = $this->totalcount > $this->perpage;
3081 $data->pagesize = $this->perpage;
3083 if (!$data->haspages) {
3084 return $data;
3087 if ($this->page > 0) {
3088 $data->previous = [
3089 'page' => $this->page,
3090 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page - 1]))->out(false)
3094 $currpage = 0;
3095 if ($this->page > round(($this->maxdisplay / 3) * 2)) {
3096 $currpage = $this->page - round($this->maxdisplay / 3);
3097 $data->first = [
3098 'page' => 1,
3099 'url' => (new moodle_url($this->baseurl, [$this->pagevar => 0]))->out(false)
3103 $lastpage = 1;
3104 if ($this->perpage > 0) {
3105 $lastpage = ceil($this->totalcount / $this->perpage);
3108 $displaycount = 0;
3109 $displaypage = 0;
3110 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3111 $displaypage = $currpage + 1;
3113 $iscurrent = $this->page == $currpage;
3114 $link = new moodle_url($this->baseurl, [$this->pagevar => $currpage]);
3116 $data->pages[] = [
3117 'page' => $displaypage,
3118 'active' => $iscurrent,
3119 'url' => $iscurrent ? null : $link->out(false)
3122 $displaycount++;
3123 $currpage++;
3126 if ($currpage < $lastpage) {
3127 $data->last = [
3128 'page' => $lastpage,
3129 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $lastpage - 1]))->out(false)
3133 if ($this->page + 1 != $lastpage) {
3134 $data->next = [
3135 'page' => $this->page + 2,
3136 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page + 1]))->out(false)
3140 return $data;
3145 * Component representing initials bar.
3147 * @copyright 2017 Ilya Tregubov
3148 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3149 * @since Moodle 3.3
3150 * @package core
3151 * @category output
3153 class initials_bar implements renderable, templatable {
3156 * @var string Currently selected letter.
3158 public $current;
3161 * @var string Class name to add to this initial bar.
3163 public $class;
3166 * @var string The name to put in front of this initial bar.
3168 public $title;
3171 * @var string URL parameter name for this initial.
3173 public $urlvar;
3176 * @var string URL object.
3178 public $url;
3181 * @var array An array of letters in the alphabet.
3183 public $alpha;
3186 * Constructor initials_bar with only the required params.
3188 * @param string $current the currently selected letter.
3189 * @param string $class class name to add to this initial bar.
3190 * @param string $title the name to put in front of this initial bar.
3191 * @param string $urlvar URL parameter name for this initial.
3192 * @param string $url URL object.
3193 * @param array $alpha of letters in the alphabet.
3195 public function __construct($current, $class, $title, $urlvar, $url, $alpha = null) {
3196 $this->current = $current;
3197 $this->class = $class;
3198 $this->title = $title;
3199 $this->urlvar = $urlvar;
3200 $this->url = $url;
3201 $this->alpha = $alpha;
3205 * Export for template.
3207 * @param renderer_base $output The renderer.
3208 * @return stdClass
3210 public function export_for_template(renderer_base $output) {
3211 $data = new stdClass();
3213 if ($this->alpha == null) {
3214 $this->alpha = explode(',', get_string('alphabet', 'langconfig'));
3217 if ($this->current == 'all') {
3218 $this->current = '';
3221 // We want to find a letter grouping size which suits the language so
3222 // find the largest group size which is less than 15 chars.
3223 // The choice of 15 chars is the largest number of chars that reasonably
3224 // fits on the smallest supported screen size. By always using a max number
3225 // of groups which is a factor of 2, we always get nice wrapping, and the
3226 // last row is always the shortest.
3227 $groupsize = count($this->alpha);
3228 $groups = 1;
3229 while ($groupsize > 15) {
3230 $groups *= 2;
3231 $groupsize = ceil(count($this->alpha) / $groups);
3234 $groupsizelimit = 0;
3235 $groupnumber = 0;
3236 foreach ($this->alpha as $letter) {
3237 if ($groupsizelimit++ > 0 && $groupsizelimit % $groupsize == 1) {
3238 $groupnumber++;
3240 $groupletter = new stdClass();
3241 $groupletter->name = $letter;
3242 $groupletter->url = $this->url->out(false, array($this->urlvar => $letter));
3243 if ($letter == $this->current) {
3244 $groupletter->selected = $this->current;
3246 if (!isset($data->group[$groupnumber])) {
3247 $data->group[$groupnumber] = new stdClass();
3249 $data->group[$groupnumber]->letter[] = $groupletter;
3252 $data->class = $this->class;
3253 $data->title = $this->title;
3254 $data->url = $this->url->out(false, array($this->urlvar => ''));
3255 $data->current = $this->current;
3256 $data->all = get_string('all');
3258 return $data;
3263 * This class represents how a block appears on a page.
3265 * During output, each block instance is asked to return a block_contents object,
3266 * those are then passed to the $OUTPUT->block function for display.
3268 * contents should probably be generated using a moodle_block_..._renderer.
3270 * Other block-like things that need to appear on the page, for example the
3271 * add new block UI, are also represented as block_contents objects.
3273 * @copyright 2009 Tim Hunt
3274 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3275 * @since Moodle 2.0
3276 * @package core
3277 * @category output
3279 class block_contents {
3281 /** Used when the block cannot be collapsed **/
3282 const NOT_HIDEABLE = 0;
3284 /** Used when the block can be collapsed but currently is not **/
3285 const VISIBLE = 1;
3287 /** Used when the block has been collapsed **/
3288 const HIDDEN = 2;
3291 * @var int Used to set $skipid.
3293 protected static $idcounter = 1;
3296 * @var int All the blocks (or things that look like blocks) printed on
3297 * a page are given a unique number that can be used to construct id="" attributes.
3298 * This is set automatically be the {@link prepare()} method.
3299 * Do not try to set it manually.
3301 public $skipid;
3304 * @var int If this is the contents of a real block, this should be set
3305 * to the block_instance.id. Otherwise this should be set to 0.
3307 public $blockinstanceid = 0;
3310 * @var int If this is a real block instance, and there is a corresponding
3311 * block_position.id for the block on this page, this should be set to that id.
3312 * Otherwise it should be 0.
3314 public $blockpositionid = 0;
3317 * @var array An array of attribute => value pairs that are put on the outer div of this
3318 * block. {@link $id} and {@link $classes} attributes should be set separately.
3320 public $attributes;
3323 * @var string The title of this block. If this came from user input, it should already
3324 * have had format_string() processing done on it. This will be output inside
3325 * <h2> tags. Please do not cause invalid XHTML.
3327 public $title = '';
3330 * @var string The label to use when the block does not, or will not have a visible title.
3331 * You should never set this as well as title... it will just be ignored.
3333 public $arialabel = '';
3336 * @var string HTML for the content
3338 public $content = '';
3341 * @var array An alternative to $content, it you want a list of things with optional icons.
3343 public $footer = '';
3346 * @var string Any small print that should appear under the block to explain
3347 * to the teacher about the block, for example 'This is a sticky block that was
3348 * added in the system context.'
3350 public $annotation = '';
3353 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
3354 * the user can toggle whether this block is visible.
3356 public $collapsible = self::NOT_HIDEABLE;
3359 * Set this to true if the block is dockable.
3360 * @var bool
3362 public $dockable = false;
3365 * @var array A (possibly empty) array of editing controls. Each element of
3366 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
3367 * $icon is the icon name. Fed to $OUTPUT->image_url.
3369 public $controls = array();
3373 * Create new instance of block content
3374 * @param array $attributes
3376 public function __construct(array $attributes = null) {
3377 $this->skipid = self::$idcounter;
3378 self::$idcounter += 1;
3380 if ($attributes) {
3381 // standard block
3382 $this->attributes = $attributes;
3383 } else {
3384 // simple "fake" blocks used in some modules and "Add new block" block
3385 $this->attributes = array('class'=>'block');
3390 * Add html class to block
3392 * @param string $class
3394 public function add_class($class) {
3395 $this->attributes['class'] .= ' '.$class;
3399 * Check if the block is a fake block.
3401 * @return boolean
3403 public function is_fake() {
3404 return isset($this->attributes['data-block']) && $this->attributes['data-block'] == '_fake';
3410 * This class represents a target for where a block can go when it is being moved.
3412 * This needs to be rendered as a form with the given hidden from fields, and
3413 * clicking anywhere in the form should submit it. The form action should be
3414 * $PAGE->url.
3416 * @copyright 2009 Tim Hunt
3417 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3418 * @since Moodle 2.0
3419 * @package core
3420 * @category output
3422 class block_move_target {
3425 * @var moodle_url Move url
3427 public $url;
3430 * Constructor
3431 * @param moodle_url $url
3433 public function __construct(moodle_url $url) {
3434 $this->url = $url;
3439 * Custom menu item
3441 * This class is used to represent one item within a custom menu that may or may
3442 * not have children.
3444 * @copyright 2010 Sam Hemelryk
3445 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3446 * @since Moodle 2.0
3447 * @package core
3448 * @category output
3450 class custom_menu_item implements renderable, templatable {
3453 * @var string The text to show for the item
3455 protected $text;
3458 * @var moodle_url The link to give the icon if it has no children
3460 protected $url;
3463 * @var string A title to apply to the item. By default the text
3465 protected $title;
3468 * @var int A sort order for the item, not necessary if you order things in
3469 * the CFG var.
3471 protected $sort;
3474 * @var custom_menu_item A reference to the parent for this item or NULL if
3475 * it is a top level item
3477 protected $parent;
3480 * @var array A array in which to store children this item has.
3482 protected $children = array();
3485 * @var int A reference to the sort var of the last child that was added
3487 protected $lastsort = 0;
3489 /** @var array Array of other HTML attributes for the custom menu item. */
3490 protected $attributes = [];
3493 * Constructs the new custom menu item
3495 * @param string $text
3496 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
3497 * @param string $title A title to apply to this item [Optional]
3498 * @param int $sort A sort or to use if we need to sort differently [Optional]
3499 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
3500 * belongs to, only if the child has a parent. [Optional]
3501 * @param array $attributes Array of other HTML attributes for the custom menu item.
3503 public function __construct($text, moodle_url $url = null, $title = null, $sort = null, custom_menu_item $parent = null,
3504 array $attributes = []) {
3505 $this->text = $text;
3506 $this->url = $url;
3507 $this->title = $title;
3508 $this->sort = (int)$sort;
3509 $this->parent = $parent;
3510 $this->attributes = $attributes;
3514 * Adds a custom menu item as a child of this node given its properties.
3516 * @param string $text
3517 * @param moodle_url $url
3518 * @param string $title
3519 * @param int $sort
3520 * @param array $attributes Array of other HTML attributes for the custom menu item.
3521 * @return custom_menu_item
3523 public function add($text, moodle_url $url = null, $title = null, $sort = null, $attributes = []) {
3524 $key = count($this->children);
3525 if (empty($sort)) {
3526 $sort = $this->lastsort + 1;
3528 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this, $attributes);
3529 $this->lastsort = (int)$sort;
3530 return $this->children[$key];
3534 * Removes a custom menu item that is a child or descendant to the current menu.
3536 * Returns true if child was found and removed.
3538 * @param custom_menu_item $menuitem
3539 * @return bool
3541 public function remove_child(custom_menu_item $menuitem) {
3542 $removed = false;
3543 if (($key = array_search($menuitem, $this->children)) !== false) {
3544 unset($this->children[$key]);
3545 $this->children = array_values($this->children);
3546 $removed = true;
3547 } else {
3548 foreach ($this->children as $child) {
3549 if ($removed = $child->remove_child($menuitem)) {
3550 break;
3554 return $removed;
3558 * Returns the text for this item
3559 * @return string
3561 public function get_text() {
3562 return $this->text;
3566 * Returns the url for this item
3567 * @return moodle_url
3569 public function get_url() {
3570 return $this->url;
3574 * Returns the title for this item
3575 * @return string
3577 public function get_title() {
3578 return $this->title;
3582 * Sorts and returns the children for this item
3583 * @return array
3585 public function get_children() {
3586 $this->sort();
3587 return $this->children;
3591 * Gets the sort order for this child
3592 * @return int
3594 public function get_sort_order() {
3595 return $this->sort;
3599 * Gets the parent this child belong to
3600 * @return custom_menu_item
3602 public function get_parent() {
3603 return $this->parent;
3607 * Sorts the children this item has
3609 public function sort() {
3610 usort($this->children, array('custom_menu','sort_custom_menu_items'));
3614 * Returns true if this item has any children
3615 * @return bool
3617 public function has_children() {
3618 return (count($this->children) > 0);
3622 * Sets the text for the node
3623 * @param string $text
3625 public function set_text($text) {
3626 $this->text = (string)$text;
3630 * Sets the title for the node
3631 * @param string $title
3633 public function set_title($title) {
3634 $this->title = (string)$title;
3638 * Sets the url for the node
3639 * @param moodle_url $url
3641 public function set_url(moodle_url $url) {
3642 $this->url = $url;
3646 * Export this data so it can be used as the context for a mustache template.
3648 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
3649 * @return array
3651 public function export_for_template(renderer_base $output) {
3652 global $CFG;
3654 require_once($CFG->libdir . '/externallib.php');
3656 $syscontext = context_system::instance();
3658 $context = new stdClass();
3659 $context->moremenuid = uniqid();
3660 $context->text = external_format_string($this->text, $syscontext->id);
3661 $context->url = $this->url ? $this->url->out() : null;
3662 // No need for the title if it's the same with text.
3663 if ($this->text !== $this->title) {
3664 // Show the title attribute only if it's different from the text.
3665 $context->title = external_format_string($this->title, $syscontext->id);
3667 $context->sort = $this->sort;
3668 if (!empty($this->attributes)) {
3669 $context->attributes = $this->attributes;
3671 $context->children = array();
3672 if (preg_match("/^#+$/", $this->text)) {
3673 $context->divider = true;
3675 $context->haschildren = !empty($this->children) && (count($this->children) > 0);
3676 foreach ($this->children as $child) {
3677 $child = $child->export_for_template($output);
3678 array_push($context->children, $child);
3681 return $context;
3686 * Custom menu class
3688 * This class is used to operate a custom menu that can be rendered for the page.
3689 * The custom menu is built using $CFG->custommenuitems and is a structured collection
3690 * of custom_menu_item nodes that can be rendered by the core renderer.
3692 * To configure the custom menu:
3693 * Settings: Administration > Appearance > Themes > Theme settings
3695 * @copyright 2010 Sam Hemelryk
3696 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3697 * @since Moodle 2.0
3698 * @package core
3699 * @category output
3701 class custom_menu extends custom_menu_item {
3704 * @var string The language we should render for, null disables multilang support.
3706 protected $currentlanguage = null;
3709 * Creates the custom menu
3711 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
3712 * @param string $currentlanguage the current language code, null disables multilang support
3714 public function __construct($definition = '', $currentlanguage = null) {
3715 $this->currentlanguage = $currentlanguage;
3716 parent::__construct('root'); // create virtual root element of the menu
3717 if (!empty($definition)) {
3718 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
3723 * Overrides the children of this custom menu. Useful when getting children
3724 * from $CFG->custommenuitems
3726 * @param array $children
3728 public function override_children(array $children) {
3729 $this->children = array();
3730 foreach ($children as $child) {
3731 if ($child instanceof custom_menu_item) {
3732 $this->children[] = $child;
3738 * Converts a string into a structured array of custom_menu_items which can
3739 * then be added to a custom menu.
3741 * Structure:
3742 * text|url|title|langs
3743 * The number of hyphens at the start determines the depth of the item. The
3744 * languages are optional, comma separated list of languages the line is for.
3746 * Example structure:
3747 * First level first item|http://www.moodle.com/
3748 * -Second level first item|http://www.moodle.com/partners/
3749 * -Second level second item|http://www.moodle.com/hq/
3750 * --Third level first item|http://www.moodle.com/jobs/
3751 * -Second level third item|http://www.moodle.com/development/
3752 * First level second item|http://www.moodle.com/feedback/
3753 * First level third item
3754 * English only|http://moodle.com|English only item|en
3755 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
3758 * @static
3759 * @param string $text the menu items definition
3760 * @param string $language the language code, null disables multilang support
3761 * @return array
3763 public static function convert_text_to_menu_nodes($text, $language = null) {
3764 $root = new custom_menu();
3765 $lastitem = $root;
3766 $lastdepth = 0;
3767 $hiddenitems = array();
3768 $lines = explode("\n", $text);
3769 foreach ($lines as $linenumber => $line) {
3770 $line = trim($line);
3771 if (strlen($line) == 0) {
3772 continue;
3774 // Parse item settings.
3775 $itemtext = null;
3776 $itemurl = null;
3777 $itemtitle = null;
3778 $itemvisible = true;
3779 $settings = explode('|', $line);
3780 foreach ($settings as $i => $setting) {
3781 $setting = trim($setting);
3782 if (!empty($setting)) {
3783 switch ($i) {
3784 case 0: // Menu text.
3785 $itemtext = ltrim($setting, '-');
3786 break;
3787 case 1: // URL.
3788 try {
3789 $itemurl = new moodle_url($setting);
3790 } catch (moodle_exception $exception) {
3791 // We're not actually worried about this, we don't want to mess up the display
3792 // just for a wrongly entered URL.
3793 $itemurl = null;
3795 break;
3796 case 2: // Title attribute.
3797 $itemtitle = $setting;
3798 break;
3799 case 3: // Language.
3800 if (!empty($language)) {
3801 $itemlanguages = array_map('trim', explode(',', $setting));
3802 $itemvisible &= in_array($language, $itemlanguages);
3804 break;
3808 // Get depth of new item.
3809 preg_match('/^(\-*)/', $line, $match);
3810 $itemdepth = strlen($match[1]) + 1;
3811 // Find parent item for new item.
3812 while (($lastdepth - $itemdepth) >= 0) {
3813 $lastitem = $lastitem->get_parent();
3814 $lastdepth--;
3816 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1);
3817 $lastdepth++;
3818 if (!$itemvisible) {
3819 $hiddenitems[] = $lastitem;
3822 foreach ($hiddenitems as $item) {
3823 $item->parent->remove_child($item);
3825 return $root->get_children();
3829 * Sorts two custom menu items
3831 * This function is designed to be used with the usort method
3832 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
3834 * @static
3835 * @param custom_menu_item $itema
3836 * @param custom_menu_item $itemb
3837 * @return int
3839 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
3840 $itema = $itema->get_sort_order();
3841 $itemb = $itemb->get_sort_order();
3842 if ($itema == $itemb) {
3843 return 0;
3845 return ($itema > $itemb) ? +1 : -1;
3850 * Stores one tab
3852 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3853 * @package core
3855 class tabobject implements renderable, templatable {
3856 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
3857 var $id;
3858 /** @var moodle_url|string link */
3859 var $link;
3860 /** @var string text on the tab */
3861 var $text;
3862 /** @var string title under the link, by defaul equals to text */
3863 var $title;
3864 /** @var bool whether to display a link under the tab name when it's selected */
3865 var $linkedwhenselected = false;
3866 /** @var bool whether the tab is inactive */
3867 var $inactive = false;
3868 /** @var bool indicates that this tab's child is selected */
3869 var $activated = false;
3870 /** @var bool indicates that this tab is selected */
3871 var $selected = false;
3872 /** @var array stores children tabobjects */
3873 var $subtree = array();
3874 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
3875 var $level = 1;
3878 * Constructor
3880 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
3881 * @param string|moodle_url $link
3882 * @param string $text text on the tab
3883 * @param string $title title under the link, by defaul equals to text
3884 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
3886 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
3887 $this->id = $id;
3888 $this->link = $link;
3889 $this->text = $text;
3890 $this->title = $title ? $title : $text;
3891 $this->linkedwhenselected = $linkedwhenselected;
3895 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
3897 * @param string $selected the id of the selected tab (whatever row it's on),
3898 * if null marks all tabs as unselected
3899 * @return bool whether this tab is selected or contains selected tab in its subtree
3901 protected function set_selected($selected) {
3902 if ((string)$selected === (string)$this->id) {
3903 $this->selected = true;
3904 // This tab is selected. No need to travel through subtree.
3905 return true;
3907 foreach ($this->subtree as $subitem) {
3908 if ($subitem->set_selected($selected)) {
3909 // This tab has child that is selected. Mark it as activated. No need to check other children.
3910 $this->activated = true;
3911 return true;
3914 return false;
3918 * Travels through tree and finds a tab with specified id
3920 * @param string $id
3921 * @return tabtree|null
3923 public function find($id) {
3924 if ((string)$this->id === (string)$id) {
3925 return $this;
3927 foreach ($this->subtree as $tab) {
3928 if ($obj = $tab->find($id)) {
3929 return $obj;
3932 return null;
3936 * Allows to mark each tab's level in the tree before rendering.
3938 * @param int $level
3940 protected function set_level($level) {
3941 $this->level = $level;
3942 foreach ($this->subtree as $tab) {
3943 $tab->set_level($level + 1);
3948 * Export for template.
3950 * @param renderer_base $output Renderer.
3951 * @return object
3953 public function export_for_template(renderer_base $output) {
3954 if ($this->inactive || ($this->selected && !$this->linkedwhenselected) || $this->activated) {
3955 $link = null;
3956 } else {
3957 $link = $this->link;
3959 $active = $this->activated || $this->selected;
3961 return (object) [
3962 'id' => $this->id,
3963 'link' => is_object($link) ? $link->out(false) : $link,
3964 'text' => $this->text,
3965 'title' => $this->title,
3966 'inactive' => !$active && $this->inactive,
3967 'active' => $active,
3968 'level' => $this->level,
3975 * Renderable for the main page header.
3977 * @package core
3978 * @category output
3979 * @since 2.9
3980 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
3981 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3983 class context_header implements renderable {
3986 * @var string $heading Main heading.
3988 public $heading;
3990 * @var int $headinglevel Main heading 'h' tag level.
3992 public $headinglevel;
3994 * @var string|null $imagedata HTML code for the picture in the page header.
3996 public $imagedata;
3998 * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
3999 * array elements - title => alternate text for the image, or if no image is available the button text.
4000 * url => Link for the button to head to. Should be a moodle_url.
4001 * image => location to the image, or name of the image in /pix/t/{image name}.
4002 * linkattributes => additional attributes for the <a href> element.
4003 * page => page object. Don't include if the image is an external image.
4005 public $additionalbuttons;
4007 * @var string $prefix A string that is before the title.
4009 public $prefix;
4012 * Constructor.
4014 * @param string $heading Main heading data.
4015 * @param int $headinglevel Main heading 'h' tag level.
4016 * @param string|null $imagedata HTML code for the picture in the page header.
4017 * @param string $additionalbuttons Buttons for the header e.g. Messaging button for the user header.
4018 * @param string $prefix Text that precedes the heading.
4020 public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null, $prefix = null) {
4022 $this->heading = $heading;
4023 $this->headinglevel = $headinglevel;
4024 $this->imagedata = $imagedata;
4025 $this->additionalbuttons = $additionalbuttons;
4026 // If we have buttons then format them.
4027 if (isset($this->additionalbuttons)) {
4028 $this->format_button_images();
4030 $this->prefix = $prefix;
4034 * Adds an array element for a formatted image.
4036 protected function format_button_images() {
4038 foreach ($this->additionalbuttons as $buttontype => $button) {
4039 $page = $button['page'];
4040 // If no image is provided then just use the title.
4041 if (!isset($button['image'])) {
4042 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['title'];
4043 } else {
4044 // Check to see if this is an internal Moodle icon.
4045 $internalimage = $page->theme->resolve_image_location('t/' . $button['image'], 'moodle');
4046 if ($internalimage) {
4047 $this->additionalbuttons[$buttontype]['formattedimage'] = 't/' . $button['image'];
4048 } else {
4049 // Treat as an external image.
4050 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['image'];
4054 if (isset($button['linkattributes']['class'])) {
4055 $class = $button['linkattributes']['class'] . ' btn';
4056 } else {
4057 $class = 'btn';
4059 // Add the bootstrap 'btn' class for formatting.
4060 $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
4061 array('class' => $class));
4067 * Stores tabs list
4069 * Example how to print a single line tabs:
4070 * $rows = array(
4071 * new tabobject(...),
4072 * new tabobject(...)
4073 * );
4074 * echo $OUTPUT->tabtree($rows, $selectedid);
4076 * Multiple row tabs may not look good on some devices but if you want to use them
4077 * you can specify ->subtree for the active tabobject.
4079 * @copyright 2013 Marina Glancy
4080 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4081 * @since Moodle 2.5
4082 * @package core
4083 * @category output
4085 class tabtree extends tabobject {
4087 * Constuctor
4089 * It is highly recommended to call constructor when list of tabs is already
4090 * populated, this way you ensure that selected and inactive tabs are located
4091 * and attribute level is set correctly.
4093 * @param array $tabs array of tabs, each of them may have it's own ->subtree
4094 * @param string|null $selected which tab to mark as selected, all parent tabs will
4095 * automatically be marked as activated
4096 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4097 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
4099 public function __construct($tabs, $selected = null, $inactive = null) {
4100 $this->subtree = $tabs;
4101 if ($selected !== null) {
4102 $this->set_selected($selected);
4104 if ($inactive !== null) {
4105 if (is_array($inactive)) {
4106 foreach ($inactive as $id) {
4107 if ($tab = $this->find($id)) {
4108 $tab->inactive = true;
4111 } else if ($tab = $this->find($inactive)) {
4112 $tab->inactive = true;
4115 $this->set_level(0);
4119 * Export for template.
4121 * @param renderer_base $output Renderer.
4122 * @return object
4124 public function export_for_template(renderer_base $output) {
4125 $tabs = [];
4126 $secondrow = false;
4128 foreach ($this->subtree as $tab) {
4129 $tabs[] = $tab->export_for_template($output);
4130 if (!empty($tab->subtree) && ($tab->level == 0 || $tab->selected || $tab->activated)) {
4131 $secondrow = new tabtree($tab->subtree);
4135 return (object) [
4136 'tabs' => $tabs,
4137 'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false
4143 * An action menu.
4145 * This action menu component takes a series of primary and secondary actions.
4146 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
4147 * down menu.
4149 * @package core
4150 * @category output
4151 * @copyright 2013 Sam Hemelryk
4152 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4154 class action_menu implements renderable, templatable {
4157 * Top right alignment.
4159 const TL = 1;
4162 * Top right alignment.
4164 const TR = 2;
4167 * Top right alignment.
4169 const BL = 3;
4172 * Top right alignment.
4174 const BR = 4;
4177 * The instance number. This is unique to this instance of the action menu.
4178 * @var int
4180 protected $instance = 0;
4183 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
4184 * @var array
4186 protected $primaryactions = array();
4189 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
4190 * @var array
4192 protected $secondaryactions = array();
4195 * An array of attributes added to the container of the action menu.
4196 * Initialised with defaults during construction.
4197 * @var array
4199 public $attributes = array();
4201 * An array of attributes added to the container of the primary actions.
4202 * Initialised with defaults during construction.
4203 * @var array
4205 public $attributesprimary = array();
4207 * An array of attributes added to the container of the secondary actions.
4208 * Initialised with defaults during construction.
4209 * @var array
4211 public $attributessecondary = array();
4214 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
4215 * @var array
4217 public $actiontext = null;
4220 * The string to use for the accessible label for the menu.
4221 * @var array
4223 public $actionlabel = null;
4226 * An icon to use for the toggling the secondary menu (dropdown).
4227 * @var pix_icon
4229 public $actionicon;
4232 * Any text to use for the toggling the secondary menu (dropdown).
4233 * @var string
4235 public $menutrigger = '';
4238 * Any extra classes for toggling to the secondary menu.
4239 * @var string
4241 public $triggerextraclasses = '';
4244 * Place the action menu before all other actions.
4245 * @var bool
4247 public $prioritise = false;
4250 * Dropdown menu alignment class.
4251 * @var string
4253 public $dropdownalignment = '';
4256 * Constructs the action menu with the given items.
4258 * @param array $actions An array of actions (action_menu_link|pix_icon|string).
4260 public function __construct(array $actions = array()) {
4261 static $initialised = 0;
4262 $this->instance = $initialised;
4263 $initialised++;
4265 $this->attributes = array(
4266 'id' => 'action-menu-'.$this->instance,
4267 'class' => 'moodle-actionmenu',
4268 'data-enhance' => 'moodle-core-actionmenu'
4270 $this->attributesprimary = array(
4271 'id' => 'action-menu-'.$this->instance.'-menubar',
4272 'class' => 'menubar',
4274 $this->attributessecondary = array(
4275 'id' => 'action-menu-'.$this->instance.'-menu',
4276 'class' => 'menu',
4277 'data-rel' => 'menu-content',
4278 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
4279 'role' => 'menu'
4281 $this->dropdownalignment = 'dropdown-menu-right';
4282 foreach ($actions as $action) {
4283 $this->add($action);
4288 * Sets the label for the menu trigger.
4290 * @param string $label The text
4292 public function set_action_label($label) {
4293 $this->actionlabel = $label;
4297 * Sets the menu trigger text.
4299 * @param string $trigger The text
4300 * @param string $extraclasses Extra classes to style the secondary menu toggle.
4302 public function set_menu_trigger($trigger, $extraclasses = '') {
4303 $this->menutrigger = $trigger;
4304 $this->triggerextraclasses = $extraclasses;
4308 * Return true if there is at least one visible link in the menu.
4310 * @return bool
4312 public function is_empty() {
4313 return !count($this->primaryactions) && !count($this->secondaryactions);
4317 * Initialises JS required fore the action menu.
4318 * The JS is only required once as it manages all action menu's on the page.
4320 * @param moodle_page $page
4322 public function initialise_js(moodle_page $page) {
4323 static $initialised = false;
4324 if (!$initialised) {
4325 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
4326 $initialised = true;
4331 * Adds an action to this action menu.
4333 * @param action_menu_link|pix_icon|string $action
4335 public function add($action) {
4336 if ($action instanceof action_link) {
4337 if ($action->primary) {
4338 $this->add_primary_action($action);
4339 } else {
4340 $this->add_secondary_action($action);
4342 } else if ($action instanceof pix_icon) {
4343 $this->add_primary_action($action);
4344 } else {
4345 $this->add_secondary_action($action);
4350 * Adds a primary action to the action menu.
4352 * @param action_menu_link|action_link|pix_icon|string $action
4354 public function add_primary_action($action) {
4355 if ($action instanceof action_link || $action instanceof pix_icon) {
4356 $action->attributes['role'] = 'menuitem';
4357 $action->attributes['tabindex'] = '-1';
4358 if ($action instanceof action_menu_link) {
4359 $action->actionmenu = $this;
4362 $this->primaryactions[] = $action;
4366 * Adds a secondary action to the action menu.
4368 * @param action_link|pix_icon|string $action
4370 public function add_secondary_action($action) {
4371 if ($action instanceof action_link || $action instanceof pix_icon) {
4372 $action->attributes['role'] = 'menuitem';
4373 $action->attributes['tabindex'] = '-1';
4374 if ($action instanceof action_menu_link) {
4375 $action->actionmenu = $this;
4378 $this->secondaryactions[] = $action;
4382 * Returns the primary actions ready to be rendered.
4384 * @param core_renderer $output The renderer to use for getting icons.
4385 * @return array
4387 public function get_primary_actions(core_renderer $output = null) {
4388 global $OUTPUT;
4389 if ($output === null) {
4390 $output = $OUTPUT;
4392 $pixicon = $this->actionicon;
4393 $linkclasses = array('toggle-display');
4395 $title = '';
4396 if (!empty($this->menutrigger)) {
4397 $pixicon = '<b class="caret"></b>';
4398 $linkclasses[] = 'textmenu';
4399 } else {
4400 $title = new lang_string('actionsmenu', 'moodle');
4401 $this->actionicon = new pix_icon(
4402 't/edit_menu',
4404 'moodle',
4405 array('class' => 'iconsmall actionmenu', 'title' => '')
4407 $pixicon = $this->actionicon;
4409 if ($pixicon instanceof renderable) {
4410 $pixicon = $output->render($pixicon);
4411 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
4412 $title = $pixicon->attributes['alt'];
4415 $string = '';
4416 if ($this->actiontext) {
4417 $string = $this->actiontext;
4419 $label = '';
4420 if ($this->actionlabel) {
4421 $label = $this->actionlabel;
4422 } else {
4423 $label = $title;
4425 $actions = $this->primaryactions;
4426 $attributes = array(
4427 'class' => implode(' ', $linkclasses),
4428 'title' => $title,
4429 'aria-label' => $label,
4430 'id' => 'action-menu-toggle-'.$this->instance,
4431 'role' => 'menuitem',
4432 'tabindex' => '-1',
4434 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
4435 if ($this->prioritise) {
4436 array_unshift($actions, $link);
4437 } else {
4438 $actions[] = $link;
4440 return $actions;
4444 * Returns the secondary actions ready to be rendered.
4445 * @return array
4447 public function get_secondary_actions() {
4448 return $this->secondaryactions;
4452 * Sets the selector that should be used to find the owning node of this menu.
4453 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
4455 public function set_owner_selector($selector) {
4456 $this->attributes['data-owner'] = $selector;
4460 * Sets the alignment of the dialogue in relation to button used to toggle it.
4462 * @deprecated since Moodle 4.0
4464 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4465 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4467 public function set_alignment($dialogue, $button) {
4468 debugging('The method action_menu::set_alignment() is deprecated, use action_menu::set_menu_left()', DEBUG_DEVELOPER);
4469 if (isset($this->attributessecondary['data-align'])) {
4470 // We've already got one set, lets remove the old class so as to avoid troubles.
4471 $class = $this->attributessecondary['class'];
4472 $search = 'align-'.$this->attributessecondary['data-align'];
4473 $this->attributessecondary['class'] = str_replace($search, '', $class);
4475 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
4476 $this->attributessecondary['data-align'] = $align;
4477 $this->attributessecondary['class'] .= ' align-'.$align;
4481 * Returns a string to describe the alignment.
4483 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4484 * @return string
4486 protected function get_align_string($align) {
4487 switch ($align) {
4488 case self::TL :
4489 return 'tl';
4490 case self::TR :
4491 return 'tr';
4492 case self::BL :
4493 return 'bl';
4494 case self::BR :
4495 return 'br';
4496 default :
4497 return 'tl';
4502 * Aligns the left corner of the dropdown.
4505 public function set_menu_left() {
4506 $this->dropdownalignment = 'dropdown-menu-left';
4510 * Sets a constraint for the dialogue.
4512 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
4513 * element the constraint identifies.
4515 * This is required whenever the action menu is displayed inside any CSS element with the .no-overflow class
4516 * (flexible_table and any of it's child classes are a likely candidate).
4518 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
4520 public function set_constraint($ancestorselector) {
4521 $this->attributessecondary['data-constraint'] = $ancestorselector;
4525 * If you call this method the action menu will be displayed but will not be enhanced.
4527 * By not displaying the menu enhanced all items will be displayed in a single row.
4529 * @deprecated since Moodle 3.2
4531 public function do_not_enhance() {
4532 debugging('The method action_menu::do_not_enhance() is deprecated, use a list of action_icon instead.', DEBUG_DEVELOPER);
4536 * Returns true if this action menu will be enhanced.
4538 * @return bool
4540 public function will_be_enhanced() {
4541 return isset($this->attributes['data-enhance']);
4545 * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
4547 * This property can be useful when the action menu is displayed within a parent element that is either floated
4548 * or relatively positioned.
4549 * In that situation the width of the menu is determined by the width of the parent element which may not be large
4550 * enough for the menu items without them wrapping.
4551 * This disables the wrapping so that the menu takes on the width of the longest item.
4553 * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
4555 public function set_nowrap_on_items($value = true) {
4556 $class = 'nowrap-items';
4557 if (!empty($this->attributes['class'])) {
4558 $pos = strpos($this->attributes['class'], $class);
4559 if ($value === true && $pos === false) {
4560 // The value is true and the class has not been set yet. Add it.
4561 $this->attributes['class'] .= ' '.$class;
4562 } else if ($value === false && $pos !== false) {
4563 // The value is false and the class has been set. Remove it.
4564 $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class));
4566 } else if ($value) {
4567 // The value is true and the class has not been set yet. Add it.
4568 $this->attributes['class'] = $class;
4573 * Add classes to the action menu for an easier styling.
4575 * @param string $class The class to add to attributes.
4577 public function set_additional_classes(string $class = '') {
4578 if (!empty($this->attributes['class'])) {
4579 $this->attributes['class'] .= " ".$class;
4580 } else {
4581 $this->attributes['class'] = $class;
4586 * Export for template.
4588 * @param renderer_base $output The renderer.
4589 * @return stdClass
4591 public function export_for_template(renderer_base $output) {
4592 $data = new stdClass();
4593 // Assign a role of menubar to this action menu when:
4594 // - it contains 2 or more primary actions; or
4595 // - if it contains a primary action and secondary actions.
4596 if (count($this->primaryactions) > 1 || (!empty($this->primaryactions) && !empty($this->secondaryactions))) {
4597 $this->attributes['role'] = 'menubar';
4599 $attributes = $this->attributes;
4600 $attributesprimary = $this->attributesprimary;
4601 $attributessecondary = $this->attributessecondary;
4603 $data->instance = $this->instance;
4605 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
4606 unset($attributes['class']);
4608 $data->attributes = array_map(function($key, $value) {
4609 return [ 'name' => $key, 'value' => $value ];
4610 }, array_keys($attributes), $attributes);
4612 $primary = new stdClass();
4613 $primary->title = '';
4614 $primary->prioritise = $this->prioritise;
4616 $primary->classes = isset($attributesprimary['class']) ? $attributesprimary['class'] : '';
4617 unset($attributesprimary['class']);
4618 $primary->attributes = array_map(function($key, $value) {
4619 return [ 'name' => $key, 'value' => $value ];
4620 }, array_keys($attributesprimary), $attributesprimary);
4622 $actionicon = $this->actionicon;
4623 if (!empty($this->menutrigger)) {
4624 $primary->menutrigger = $this->menutrigger;
4625 $primary->triggerextraclasses = $this->triggerextraclasses;
4626 if ($this->actionlabel) {
4627 $primary->title = $this->actionlabel;
4628 } else if ($this->actiontext) {
4629 $primary->title = $this->actiontext;
4630 } else {
4631 $primary->title = strip_tags($this->menutrigger);
4633 } else {
4634 $primary->title = get_string('actionsmenu');
4635 $iconattributes = ['class' => 'iconsmall actionmenu', 'title' => $primary->title];
4636 $actionicon = new pix_icon('t/edit_menu', '', 'moodle', $iconattributes);
4639 // If the menu trigger is within the menubar, assign a role of menuitem. Otherwise, assign as a button.
4640 $primary->triggerrole = 'button';
4641 if (isset($attributes['role']) && $attributes['role'] === 'menubar') {
4642 $primary->triggerrole = 'menuitem';
4645 if ($actionicon instanceof pix_icon) {
4646 $primary->icon = $actionicon->export_for_pix();
4647 if (!empty($actionicon->attributes['alt'])) {
4648 $primary->title = $actionicon->attributes['alt'];
4650 } else {
4651 $primary->iconraw = $actionicon ? $output->render($actionicon) : '';
4654 $primary->actiontext = $this->actiontext ? (string) $this->actiontext : '';
4655 $primary->items = array_map(function($item) use ($output) {
4656 $data = (object) [];
4657 if ($item instanceof action_menu_link) {
4658 $data->actionmenulink = $item->export_for_template($output);
4659 } else if ($item instanceof action_menu_filler) {
4660 $data->actionmenufiller = $item->export_for_template($output);
4661 } else if ($item instanceof action_link) {
4662 $data->actionlink = $item->export_for_template($output);
4663 } else if ($item instanceof pix_icon) {
4664 $data->pixicon = $item->export_for_template($output);
4665 } else {
4666 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4668 return $data;
4669 }, $this->primaryactions);
4671 $secondary = new stdClass();
4672 $secondary->classes = isset($attributessecondary['class']) ? $attributessecondary['class'] : '';
4673 unset($attributessecondary['class']);
4674 $secondary->attributes = array_map(function($key, $value) {
4675 return [ 'name' => $key, 'value' => $value ];
4676 }, array_keys($attributessecondary), $attributessecondary);
4677 $secondary->items = array_map(function($item) use ($output) {
4678 $data = (object) [];
4679 if ($item instanceof action_menu_link) {
4680 $data->actionmenulink = $item->export_for_template($output);
4681 } else if ($item instanceof action_menu_filler) {
4682 $data->actionmenufiller = $item->export_for_template($output);
4683 } else if ($item instanceof action_link) {
4684 $data->actionlink = $item->export_for_template($output);
4685 } else if ($item instanceof pix_icon) {
4686 $data->pixicon = $item->export_for_template($output);
4687 } else {
4688 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4690 return $data;
4691 }, $this->secondaryactions);
4693 $data->primary = $primary;
4694 $data->secondary = $secondary;
4695 $data->dropdownalignment = $this->dropdownalignment;
4697 return $data;
4703 * An action menu filler
4705 * @package core
4706 * @category output
4707 * @copyright 2013 Andrew Nicols
4708 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4710 class action_menu_filler extends action_link implements renderable {
4713 * True if this is a primary action. False if not.
4714 * @var bool
4716 public $primary = true;
4719 * Constructs the object.
4721 public function __construct() {
4722 $this->attributes['id'] = html_writer::random_id('action_link');
4727 * An action menu action
4729 * @package core
4730 * @category output
4731 * @copyright 2013 Sam Hemelryk
4732 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4734 class action_menu_link extends action_link implements renderable {
4737 * True if this is a primary action. False if not.
4738 * @var bool
4740 public $primary = true;
4743 * The action menu this link has been added to.
4744 * @var action_menu
4746 public $actionmenu = null;
4749 * The number of instances of this action menu link (and its subclasses).
4750 * @var int
4752 protected static $instance = 1;
4755 * Constructs the object.
4757 * @param moodle_url $url The URL for the action.
4758 * @param pix_icon|null $icon The icon to represent the action.
4759 * @param string $text The text to represent the action.
4760 * @param bool $primary Whether this is a primary action or not.
4761 * @param array $attributes Any attribtues associated with the action.
4763 public function __construct(moodle_url $url, ?pix_icon $icon, $text, $primary = true, array $attributes = array()) {
4764 parent::__construct($url, $text, null, $attributes, $icon);
4765 $this->primary = (bool)$primary;
4766 $this->add_class('menu-action');
4767 $this->attributes['role'] = 'menuitem';
4771 * Export for template.
4773 * @param renderer_base $output The renderer.
4774 * @return stdClass
4776 public function export_for_template(renderer_base $output) {
4777 $data = parent::export_for_template($output);
4778 $data->instance = self::$instance++;
4780 // Ignore what the parent did with the attributes, except for ID and class.
4781 $data->attributes = [];
4782 $attributes = $this->attributes;
4783 unset($attributes['id']);
4784 unset($attributes['class']);
4786 // Handle text being a renderable.
4787 if ($this->text instanceof renderable) {
4788 $data->text = $this->render($this->text);
4791 $data->showtext = (!$this->icon || $this->primary === false);
4793 $data->icon = null;
4794 if ($this->icon) {
4795 $icon = $this->icon;
4796 if ($this->primary || !$this->actionmenu->will_be_enhanced()) {
4797 $attributes['title'] = $data->text;
4799 $data->icon = $icon ? $icon->export_for_pix() : null;
4802 $data->disabled = !empty($attributes['disabled']);
4803 unset($attributes['disabled']);
4805 $data->attributes = array_map(function($key, $value) {
4806 return [
4807 'name' => $key,
4808 'value' => $value
4810 }, array_keys($attributes), $attributes);
4812 return $data;
4817 * A primary action menu action
4819 * @package core
4820 * @category output
4821 * @copyright 2013 Sam Hemelryk
4822 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4824 class action_menu_link_primary extends action_menu_link {
4826 * Constructs the object.
4828 * @param moodle_url $url
4829 * @param pix_icon|null $icon
4830 * @param string $text
4831 * @param array $attributes
4833 public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) {
4834 parent::__construct($url, $icon, $text, true, $attributes);
4839 * A secondary action menu action
4841 * @package core
4842 * @category output
4843 * @copyright 2013 Sam Hemelryk
4844 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4846 class action_menu_link_secondary extends action_menu_link {
4848 * Constructs the object.
4850 * @param moodle_url $url
4851 * @param pix_icon|null $icon
4852 * @param string $text
4853 * @param array $attributes
4855 public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) {
4856 parent::__construct($url, $icon, $text, false, $attributes);
4861 * Represents a set of preferences groups.
4863 * @package core
4864 * @category output
4865 * @copyright 2015 Frédéric Massart - FMCorz.net
4866 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4868 class preferences_groups implements renderable {
4871 * Array of preferences_group.
4872 * @var array
4874 public $groups;
4877 * Constructor.
4878 * @param array $groups of preferences_group
4880 public function __construct($groups) {
4881 $this->groups = $groups;
4887 * Represents a group of preferences page link.
4889 * @package core
4890 * @category output
4891 * @copyright 2015 Frédéric Massart - FMCorz.net
4892 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4894 class preferences_group implements renderable {
4897 * Title of the group.
4898 * @var string
4900 public $title;
4903 * Array of navigation_node.
4904 * @var array
4906 public $nodes;
4909 * Constructor.
4910 * @param string $title The title.
4911 * @param array $nodes of navigation_node.
4913 public function __construct($title, $nodes) {
4914 $this->title = $title;
4915 $this->nodes = $nodes;
4920 * Progress bar class.
4922 * Manages the display of a progress bar.
4924 * To use this class.
4925 * - construct
4926 * - call create (or use the 3rd param to the constructor)
4927 * - call update or update_full() or update() repeatedly
4929 * @copyright 2008 jamiesensei
4930 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4931 * @package core
4932 * @category output
4934 class progress_bar implements renderable, templatable {
4935 /** @var string html id */
4936 private $html_id;
4937 /** @var int total width */
4938 private $width;
4939 /** @var int last percentage printed */
4940 private $percent = 0;
4941 /** @var int time when last printed */
4942 private $lastupdate = 0;
4943 /** @var int when did we start printing this */
4944 private $time_start = 0;
4947 * Constructor
4949 * Prints JS code if $autostart true.
4951 * @param string $htmlid The container ID.
4952 * @param int $width The suggested width.
4953 * @param bool $autostart Whether to start the progress bar right away.
4955 public function __construct($htmlid = '', $width = 500, $autostart = false) {
4956 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
4957 debugging('progress_bar used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', DEBUG_DEVELOPER);
4960 if (!empty($htmlid)) {
4961 $this->html_id = $htmlid;
4962 } else {
4963 $this->html_id = 'pbar_'.uniqid();
4966 $this->width = $width;
4968 if ($autostart) {
4969 $this->create();
4974 * Getter for ID
4975 * @return string id
4977 public function get_id() : string {
4978 return $this->html_id;
4982 * Create a new progress bar, this function will output html.
4984 * @return void Echo's output
4986 public function create() {
4987 global $OUTPUT;
4989 $this->time_start = microtime(true);
4991 flush();
4992 echo $OUTPUT->render($this);
4993 flush();
4997 * Update the progress bar.
4999 * @param int $percent From 1-100.
5000 * @param string $msg The message.
5001 * @return void Echo's output
5002 * @throws coding_exception
5004 private function _update($percent, $msg) {
5005 global $OUTPUT;
5007 if (empty($this->time_start)) {
5008 throw new coding_exception('You must call create() (or use the $autostart ' .
5009 'argument to the constructor) before you try updating the progress bar.');
5012 $estimate = $this->estimate($percent);
5014 if ($estimate === null) {
5015 // Always do the first and last updates.
5016 } else if ($estimate == 0) {
5017 // Always do the last updates.
5018 } else if ($this->lastupdate + 20 < time()) {
5019 // We must update otherwise browser would time out.
5020 } else if (round($this->percent, 2) === round($percent, 2)) {
5021 // No significant change, no need to update anything.
5022 return;
5025 $estimatemsg = '';
5026 if ($estimate != 0 && is_numeric($estimate)) {
5027 $estimatemsg = format_time(round($estimate));
5030 $this->percent = $percent;
5031 $this->lastupdate = microtime(true);
5033 echo $OUTPUT->render_progress_bar_update($this->html_id, sprintf("%.1f", $this->percent), $msg, $estimatemsg);
5034 flush();
5038 * Estimate how much time it is going to take.
5040 * @param int $pt From 1-100.
5041 * @return mixed Null (unknown), or int.
5043 private function estimate($pt) {
5044 if ($this->lastupdate == 0) {
5045 return null;
5047 if ($pt < 0.00001) {
5048 return null; // We do not know yet how long it will take.
5050 if ($pt > 99.99999) {
5051 return 0; // Nearly done, right?
5053 $consumed = microtime(true) - $this->time_start;
5054 if ($consumed < 0.001) {
5055 return null;
5058 return (100 - $pt) * ($consumed / $pt);
5062 * Update progress bar according percent.
5064 * @param int $percent From 1-100.
5065 * @param string $msg The message needed to be shown.
5067 public function update_full($percent, $msg) {
5068 $percent = max(min($percent, 100), 0);
5069 $this->_update($percent, $msg);
5073 * Update progress bar according the number of tasks.
5075 * @param int $cur Current task number.
5076 * @param int $total Total task number.
5077 * @param string $msg The message needed to be shown.
5079 public function update($cur, $total, $msg) {
5080 $percent = ($cur / $total) * 100;
5081 $this->update_full($percent, $msg);
5085 * Restart the progress bar.
5087 public function restart() {
5088 $this->percent = 0;
5089 $this->lastupdate = 0;
5090 $this->time_start = 0;
5094 * Export for template.
5096 * @param renderer_base $output The renderer.
5097 * @return array
5099 public function export_for_template(renderer_base $output) {
5100 return [
5101 'id' => $this->html_id,
5102 'width' => $this->width,