Merge branch 'MDL-76956-m400' of https://github.com/sammarshallou/moodle into MOODLE_...
[moodle.git] / lib / outputcomponents.php
blobd3235a76ada77d4d326bad83591adf528627e55c
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
171 * (false/0 = 35px)
172 * for backward compatibility.
174 public $size = 35;
177 * @var bool Add non-blank alt-text to the image.
178 * Default true, set to false when image alt just duplicates text in screenreaders.
180 public $alttext = true;
183 * @var bool Whether or not to open the link in a popup window.
185 public $popup = false;
188 * @var string Image class attribute
190 public $class = 'userpicture';
193 * @var bool Whether to be visible to screen readers.
195 public $visibletoscreenreaders = true;
198 * @var bool Whether to include the fullname in the user picture link.
200 public $includefullname = false;
203 * @var mixed Include user authentication token. True indicates to generate a token for current user, and integer value
204 * indicates to generate a token for the user whose id is the value indicated.
206 public $includetoken = false;
209 * User picture constructor.
211 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
212 * It is recommended to add also contextid of the user for performance reasons.
214 public function __construct(stdClass $user) {
215 global $DB;
217 if (empty($user->id)) {
218 throw new coding_exception('User id is required when printing user avatar image.');
221 // only touch the DB if we are missing data and complain loudly...
222 $needrec = false;
223 foreach (\core_user\fields::get_picture_fields() as $field) {
224 if (!property_exists($user, $field)) {
225 $needrec = true;
226 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
227 .'Please use the \core_user\fields API to get the full list of required fields.', DEBUG_DEVELOPER);
228 break;
232 if ($needrec) {
233 $this->user = $DB->get_record('user', array('id' => $user->id),
234 implode(',', \core_user\fields::get_picture_fields()), MUST_EXIST);
235 } else {
236 $this->user = clone($user);
241 * Returns a list of required user fields, useful when fetching required user info from db.
243 * In some cases we have to fetch the user data together with some other information,
244 * the idalias is useful there because the id would otherwise override the main
245 * id of the result record. Please note it has to be converted back to id before rendering.
247 * @param string $tableprefix name of database table prefix in query
248 * @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)
249 * @param string $idalias alias of id field
250 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
251 * @return string
252 * @deprecated since Moodle 3.11 MDL-45242
253 * @see \core_user\fields
255 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
256 debugging('user_picture::fields() is deprecated. Please use the \core_user\fields API instead.', DEBUG_DEVELOPER);
257 $userfields = \core_user\fields::for_userpic();
258 if ($extrafields) {
259 $userfields->including(...$extrafields);
261 $selects = $userfields->get_sql($tableprefix, false, $fieldprefix, $idalias, false)->selects;
262 if ($tableprefix === '') {
263 // If no table alias is specified, don't add {user}. in front of fields.
264 $selects = str_replace('{user}.', '', $selects);
266 // Maintain legacy behaviour where the field list was done with 'implode' and no spaces.
267 $selects = str_replace(', ', ',', $selects);
268 return $selects;
272 * Extract the aliased user fields from a given record
274 * Given a record that was previously obtained using {@link self::fields()} with aliases,
275 * this method extracts user related unaliased fields.
277 * @param stdClass $record containing user picture fields
278 * @param array $extrafields extra fields included in the $record
279 * @param string $idalias alias of the id field
280 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
281 * @return stdClass object with unaliased user fields
283 public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
285 if (empty($idalias)) {
286 $idalias = 'id';
289 $return = new stdClass();
291 foreach (\core_user\fields::get_picture_fields() as $field) {
292 if ($field === 'id') {
293 if (property_exists($record, $idalias)) {
294 $return->id = $record->{$idalias};
296 } else {
297 if (property_exists($record, $fieldprefix.$field)) {
298 $return->{$field} = $record->{$fieldprefix.$field};
302 // add extra fields if not already there
303 if ($extrafields) {
304 foreach ($extrafields as $e) {
305 if ($e === 'id' or property_exists($return, $e)) {
306 continue;
308 $return->{$e} = $record->{$fieldprefix.$e};
312 return $return;
316 * Works out the URL for the users picture.
318 * This method is recommended as it avoids costly redirects of user pictures
319 * if requests are made for non-existent files etc.
321 * @param moodle_page $page
322 * @param renderer_base $renderer
323 * @return moodle_url
325 public function get_url(moodle_page $page, renderer_base $renderer = null) {
326 global $CFG;
328 if (is_null($renderer)) {
329 $renderer = $page->get_renderer('core');
332 // Sort out the filename and size. Size is only required for the gravatar
333 // implementation presently.
334 if (empty($this->size)) {
335 $filename = 'f2';
336 $size = 35;
337 } else if ($this->size === true or $this->size == 1) {
338 $filename = 'f1';
339 $size = 100;
340 } else if ($this->size > 100) {
341 $filename = 'f3';
342 $size = (int)$this->size;
343 } else if ($this->size >= 50) {
344 $filename = 'f1';
345 $size = (int)$this->size;
346 } else {
347 $filename = 'f2';
348 $size = (int)$this->size;
351 $defaulturl = $renderer->image_url('u/'.$filename); // default image
353 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
354 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
355 // Protect images if login required and not logged in;
356 // also if login is required for profile images and is not logged in or guest
357 // do not use require_login() because it is expensive and not suitable here anyway.
358 return $defaulturl;
361 // First try to detect deleted users - but do not read from database for performance reasons!
362 if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
363 // All deleted users should have email replaced by md5 hash,
364 // all active users are expected to have valid email.
365 return $defaulturl;
368 // Did the user upload a picture?
369 if ($this->user->picture > 0) {
370 if (!empty($this->user->contextid)) {
371 $contextid = $this->user->contextid;
372 } else {
373 $context = context_user::instance($this->user->id, IGNORE_MISSING);
374 if (!$context) {
375 // This must be an incorrectly deleted user, all other users have context.
376 return $defaulturl;
378 $contextid = $context->id;
381 $path = '/';
382 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
383 // We append the theme name to the file path if we have it so that
384 // in the circumstance that the profile picture is not available
385 // when the user actually requests it they still get the profile
386 // picture for the correct theme.
387 $path .= $page->theme->name.'/';
389 // Set the image URL to the URL for the uploaded file and return.
390 $url = moodle_url::make_pluginfile_url(
391 $contextid, 'user', 'icon', null, $path, $filename, false, $this->includetoken);
392 $url->param('rev', $this->user->picture);
393 return $url;
396 if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
397 // Normalise the size variable to acceptable bounds
398 if ($size < 1 || $size > 512) {
399 $size = 35;
401 // Hash the users email address
402 $md5 = md5(strtolower(trim($this->user->email)));
403 // Build a gravatar URL with what we know.
405 // Find the best default image URL we can (MDL-35669)
406 if (empty($CFG->gravatardefaulturl)) {
407 $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
408 if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
409 $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
410 } else {
411 $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
413 } else {
414 $gravatardefault = $CFG->gravatardefaulturl;
417 // If the currently requested page is https then we'll return an
418 // https gravatar page.
419 if (is_https()) {
420 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
421 } else {
422 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
426 return $defaulturl;
431 * Data structure representing a help icon.
433 * @copyright 2010 Petr Skoda (info@skodak.org)
434 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
435 * @since Moodle 2.0
436 * @package core
437 * @category output
439 class help_icon implements renderable, templatable {
442 * @var string lang pack identifier (without the "_help" suffix),
443 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
444 * must exist.
446 public $identifier;
449 * @var string Component name, the same as in get_string()
451 public $component;
454 * @var string Extra descriptive text next to the icon
456 public $linktext = null;
459 * Constructor
461 * @param string $identifier string for help page title,
462 * string with _help suffix is used for the actual help text.
463 * string with _link suffix is used to create a link to further info (if it exists)
464 * @param string $component
466 public function __construct($identifier, $component) {
467 $this->identifier = $identifier;
468 $this->component = $component;
472 * Verifies that both help strings exists, shows debug warnings if not
474 public function diag_strings() {
475 $sm = get_string_manager();
476 if (!$sm->string_exists($this->identifier, $this->component)) {
477 debugging("Help title string does not exist: [$this->identifier, $this->component]");
479 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
480 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
485 * Export this data so it can be used as the context for a mustache template.
487 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
488 * @return array
490 public function export_for_template(renderer_base $output) {
491 global $CFG;
493 $title = get_string($this->identifier, $this->component);
495 if (empty($this->linktext)) {
496 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
497 } else {
498 $alt = get_string('helpwiththis');
501 $data = get_formatted_help_string($this->identifier, $this->component, false);
503 $data->alt = $alt;
504 $data->icon = (new pix_icon('help', $alt, 'core', ['class' => 'iconhelp']))->export_for_template($output);
505 $data->linktext = $this->linktext;
506 $data->title = get_string('helpprefix2', '', trim($title, ". \t"));
508 $options = [
509 'component' => $this->component,
510 'identifier' => $this->identifier,
511 'lang' => current_language()
514 // Debugging feature lets you display string identifier and component.
515 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
516 $options['strings'] = 1;
519 $data->url = (new moodle_url('/help.php', $options))->out(false);
520 $data->ltr = !right_to_left();
521 return $data;
527 * Data structure representing an icon font.
529 * @copyright 2016 Damyon Wiese
530 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
531 * @package core
532 * @category output
534 class pix_icon_font implements templatable {
537 * @var pix_icon $pixicon The original icon.
539 private $pixicon = null;
542 * @var string $key The mapped key.
544 private $key;
547 * @var bool $mapped The icon could not be mapped.
549 private $mapped;
552 * Constructor
554 * @param pix_icon $pixicon The original icon
556 public function __construct(pix_icon $pixicon) {
557 global $PAGE;
559 $this->pixicon = $pixicon;
560 $this->mapped = false;
561 $iconsystem = \core\output\icon_system::instance();
563 $this->key = $iconsystem->remap_icon_name($pixicon->pix, $pixicon->component);
564 if (!empty($this->key)) {
565 $this->mapped = true;
570 * Return true if this pix_icon was successfully mapped to an icon font.
572 * @return bool
574 public function is_mapped() {
575 return $this->mapped;
579 * Export this data so it can be used as the context for a mustache template.
581 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
582 * @return array
584 public function export_for_template(renderer_base $output) {
586 $pixdata = $this->pixicon->export_for_template($output);
588 $title = isset($this->pixicon->attributes['title']) ? $this->pixicon->attributes['title'] : '';
589 $alt = isset($this->pixicon->attributes['alt']) ? $this->pixicon->attributes['alt'] : '';
590 if (empty($title)) {
591 $title = $alt;
593 $data = array(
594 'extraclasses' => $pixdata['extraclasses'],
595 'title' => $title,
596 'alt' => $alt,
597 'key' => $this->key
600 return $data;
605 * Data structure representing an icon subtype.
607 * @copyright 2016 Damyon Wiese
608 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
609 * @package core
610 * @category output
612 class pix_icon_fontawesome extends pix_icon_font {
617 * Data structure representing an icon.
619 * @copyright 2010 Petr Skoda
620 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
621 * @since Moodle 2.0
622 * @package core
623 * @category output
625 class pix_icon implements renderable, templatable {
628 * @var string The icon name
630 var $pix;
633 * @var string The component the icon belongs to.
635 var $component;
638 * @var array An array of attributes to use on the icon
640 var $attributes = array();
643 * Constructor
645 * @param string $pix short icon name
646 * @param string $alt The alt text to use for the icon
647 * @param string $component component name
648 * @param array $attributes html attributes
650 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
651 global $PAGE;
653 $this->pix = $pix;
654 $this->component = $component;
655 $this->attributes = (array)$attributes;
657 if (empty($this->attributes['class'])) {
658 $this->attributes['class'] = '';
661 // Set an additional class for big icons so that they can be styled properly.
662 if (substr($pix, 0, 2) === 'b/') {
663 $this->attributes['class'] .= ' iconsize-big';
666 // If the alt is empty, don't place it in the attributes, otherwise it will override parent alt text.
667 if (!is_null($alt)) {
668 $this->attributes['alt'] = $alt;
670 // If there is no title, set it to the attribute.
671 if (!isset($this->attributes['title'])) {
672 $this->attributes['title'] = $this->attributes['alt'];
674 } else {
675 unset($this->attributes['alt']);
678 if (empty($this->attributes['title'])) {
679 // Remove the title attribute if empty, we probably want to use the parent node's title
680 // and some browsers might overwrite it with an empty title.
681 unset($this->attributes['title']);
684 // Hide icons from screen readers that have no alt.
685 if (empty($this->attributes['alt'])) {
686 $this->attributes['aria-hidden'] = 'true';
691 * Export this data so it can be used as the context for a mustache template.
693 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
694 * @return array
696 public function export_for_template(renderer_base $output) {
697 $attributes = $this->attributes;
698 $extraclasses = '';
700 foreach ($attributes as $key => $item) {
701 if ($key == 'class') {
702 $extraclasses = $item;
703 unset($attributes[$key]);
704 break;
708 $attributes['src'] = $output->image_url($this->pix, $this->component)->out(false);
709 $templatecontext = array();
710 foreach ($attributes as $name => $value) {
711 $templatecontext[] = array('name' => $name, 'value' => $value);
713 $title = isset($attributes['title']) ? $attributes['title'] : '';
714 if (empty($title)) {
715 $title = isset($attributes['alt']) ? $attributes['alt'] : '';
717 $data = array(
718 'attributes' => $templatecontext,
719 'extraclasses' => $extraclasses
722 return $data;
726 * Much simpler version of export that will produce the data required to render this pix with the
727 * pix helper in a mustache tag.
729 * @return array
731 public function export_for_pix() {
732 $title = isset($this->attributes['title']) ? $this->attributes['title'] : '';
733 if (empty($title)) {
734 $title = isset($this->attributes['alt']) ? $this->attributes['alt'] : '';
736 return [
737 'key' => $this->pix,
738 'component' => $this->component,
739 'title' => (string) $title,
745 * Data structure representing an activity icon.
747 * The difference is that activity icons will always render with the standard icon system (no font icons).
749 * @copyright 2017 Damyon Wiese
750 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
751 * @package core
753 class image_icon extends pix_icon {
757 * Data structure representing an emoticon image
759 * @copyright 2010 David Mudrak
760 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
761 * @since Moodle 2.0
762 * @package core
763 * @category output
765 class pix_emoticon extends pix_icon implements renderable {
768 * Constructor
769 * @param string $pix short icon name
770 * @param string $alt alternative text
771 * @param string $component emoticon image provider
772 * @param array $attributes explicit HTML attributes
774 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
775 if (empty($attributes['class'])) {
776 $attributes['class'] = 'emoticon';
778 parent::__construct($pix, $alt, $component, $attributes);
783 * Data structure representing a simple form with only one button.
785 * @copyright 2009 Petr Skoda
786 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
787 * @since Moodle 2.0
788 * @package core
789 * @category output
791 class single_button implements renderable {
794 * @var moodle_url Target url
796 public $url;
799 * @var string Button label
801 public $label;
804 * @var string Form submit method post or get
806 public $method = 'post';
809 * @var string Wrapping div class
811 public $class = 'singlebutton';
814 * @var bool True if button is primary button. Used for styling.
816 public $primary = false;
819 * @var bool True if button disabled, false if normal
821 public $disabled = false;
824 * @var string Button tooltip
826 public $tooltip = null;
829 * @var string Form id
831 public $formid;
834 * @var array List of attached actions
836 public $actions = array();
839 * @var array $params URL Params
841 public $params;
844 * @var string Action id
846 public $actionid;
849 * @var array
851 protected $attributes = [];
854 * Constructor
855 * @param moodle_url $url
856 * @param string $label button text
857 * @param string $method get or post submit method
858 * @param bool $primary whether this is a primary button, used for styling
859 * @param array $attributes Attributes for the HTML button tag
861 public function __construct(moodle_url $url, $label, $method='post', $primary=false, $attributes = []) {
862 $this->url = clone($url);
863 $this->label = $label;
864 $this->method = $method;
865 $this->primary = $primary;
866 $this->attributes = $attributes;
870 * Shortcut for adding a JS confirm dialog when the button is clicked.
871 * The message must be a yes/no question.
873 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
875 public function add_confirm_action($confirmmessage) {
876 $this->add_action(new confirm_action($confirmmessage));
880 * Add action to the button.
881 * @param component_action $action
883 public function add_action(component_action $action) {
884 $this->actions[] = $action;
888 * Sets an attribute for the HTML button tag.
890 * @param string $name The attribute name
891 * @param mixed $value The value
892 * @return null
894 public function set_attribute($name, $value) {
895 $this->attributes[$name] = $value;
899 * Export data.
901 * @param renderer_base $output Renderer.
902 * @return stdClass
904 public function export_for_template(renderer_base $output) {
905 $url = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
907 $data = new stdClass();
908 $data->id = html_writer::random_id('single_button');
909 $data->formid = $this->formid;
910 $data->method = $this->method;
911 $data->url = $url === '' ? '#' : $url;
912 $data->label = $this->label;
913 $data->classes = $this->class;
914 $data->disabled = $this->disabled;
915 $data->tooltip = $this->tooltip;
916 $data->primary = $this->primary;
918 $data->attributes = [];
919 foreach ($this->attributes as $key => $value) {
920 $data->attributes[] = ['name' => $key, 'value' => $value];
923 // Form parameters.
924 $params = $this->url->params();
925 if ($this->method === 'post') {
926 $params['sesskey'] = sesskey();
928 $data->params = array_map(function($key) use ($params) {
929 return ['name' => $key, 'value' => $params[$key]];
930 }, array_keys($params));
932 // Button actions.
933 $actions = $this->actions;
934 $data->actions = array_map(function($action) use ($output) {
935 return $action->export_for_template($output);
936 }, $actions);
937 $data->hasactions = !empty($data->actions);
939 return $data;
945 * Simple form with just one select field that gets submitted automatically.
947 * If JS not enabled small go button is printed too.
949 * @copyright 2009 Petr Skoda
950 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
951 * @since Moodle 2.0
952 * @package core
953 * @category output
955 class single_select implements renderable, templatable {
958 * @var moodle_url Target url - includes hidden fields
960 var $url;
963 * @var string Name of the select element.
965 var $name;
968 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
969 * it is also possible to specify optgroup as complex label array ex.:
970 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
971 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
973 var $options;
976 * @var string Selected option
978 var $selected;
981 * @var array Nothing selected
983 var $nothing;
986 * @var array Extra select field attributes
988 var $attributes = array();
991 * @var string Button label
993 var $label = '';
996 * @var array Button label's attributes
998 var $labelattributes = array();
1001 * @var string Form submit method post or get
1003 var $method = 'get';
1006 * @var string Wrapping div class
1008 var $class = 'singleselect';
1011 * @var bool True if button disabled, false if normal
1013 var $disabled = false;
1016 * @var string Button tooltip
1018 var $tooltip = null;
1021 * @var string Form id
1023 var $formid = null;
1026 * @var help_icon The help icon for this element.
1028 var $helpicon = null;
1031 * Constructor
1032 * @param moodle_url $url form action target, includes hidden fields
1033 * @param string $name name of selection field - the changing parameter in url
1034 * @param array $options list of options
1035 * @param string $selected selected element
1036 * @param array $nothing
1037 * @param string $formid
1039 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1040 $this->url = $url;
1041 $this->name = $name;
1042 $this->options = $options;
1043 $this->selected = $selected;
1044 $this->nothing = $nothing;
1045 $this->formid = $formid;
1049 * Shortcut for adding a JS confirm dialog when the button is clicked.
1050 * The message must be a yes/no question.
1052 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
1054 public function add_confirm_action($confirmmessage) {
1055 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
1059 * Add action to the button.
1061 * @param component_action $action
1063 public function add_action(component_action $action) {
1064 $this->actions[] = $action;
1068 * Adds help icon.
1070 * @deprecated since Moodle 2.0
1072 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1073 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1077 * Adds help icon.
1079 * @param string $identifier The keyword that defines a help page
1080 * @param string $component
1082 public function set_help_icon($identifier, $component = 'moodle') {
1083 $this->helpicon = new help_icon($identifier, $component);
1087 * Sets select's label
1089 * @param string $label
1090 * @param array $attributes (optional)
1092 public function set_label($label, $attributes = array()) {
1093 $this->label = $label;
1094 $this->labelattributes = $attributes;
1099 * Export data.
1101 * @param renderer_base $output Renderer.
1102 * @return stdClass
1104 public function export_for_template(renderer_base $output) {
1105 $attributes = $this->attributes;
1107 $data = new stdClass();
1108 $data->name = $this->name;
1109 $data->method = $this->method;
1110 $data->action = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
1111 $data->classes = $this->class;
1112 $data->label = $this->label;
1113 $data->disabled = $this->disabled;
1114 $data->title = $this->tooltip;
1115 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('single_select_f');
1116 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('single_select');
1118 // Select element attributes.
1119 // Unset attributes that are already predefined in the template.
1120 unset($attributes['id']);
1121 unset($attributes['class']);
1122 unset($attributes['name']);
1123 unset($attributes['title']);
1124 unset($attributes['disabled']);
1126 // Map the attributes.
1127 $data->attributes = array_map(function($key) use ($attributes) {
1128 return ['name' => $key, 'value' => $attributes[$key]];
1129 }, array_keys($attributes));
1131 // Form parameters.
1132 $params = $this->url->params();
1133 if ($this->method === 'post') {
1134 $params['sesskey'] = sesskey();
1136 $data->params = array_map(function($key) use ($params) {
1137 return ['name' => $key, 'value' => $params[$key]];
1138 }, array_keys($params));
1140 // Select options.
1141 $hasnothing = false;
1142 if (is_string($this->nothing) && $this->nothing !== '') {
1143 $nothing = ['' => $this->nothing];
1144 $hasnothing = true;
1145 $nothingkey = '';
1146 } else if (is_array($this->nothing)) {
1147 $nothingvalue = reset($this->nothing);
1148 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1149 $nothing = [key($this->nothing) => get_string('choosedots')];
1150 } else {
1151 $nothing = $this->nothing;
1153 $hasnothing = true;
1154 $nothingkey = key($this->nothing);
1156 if ($hasnothing) {
1157 $options = $nothing + $this->options;
1158 } else {
1159 $options = $this->options;
1162 foreach ($options as $value => $name) {
1163 if (is_array($options[$value])) {
1164 foreach ($options[$value] as $optgroupname => $optgroupvalues) {
1165 $sublist = [];
1166 foreach ($optgroupvalues as $optvalue => $optname) {
1167 $option = [
1168 'value' => $optvalue,
1169 'name' => $optname,
1170 'selected' => strval($this->selected) === strval($optvalue),
1173 if ($hasnothing && $nothingkey === $optvalue) {
1174 $option['ignore'] = 'data-ignore';
1177 $sublist[] = $option;
1179 $data->options[] = [
1180 'name' => $optgroupname,
1181 'optgroup' => true,
1182 'options' => $sublist
1185 } else {
1186 $option = [
1187 'value' => $value,
1188 'name' => $options[$value],
1189 'selected' => strval($this->selected) === strval($value),
1190 'optgroup' => false
1193 if ($hasnothing && $nothingkey === $value) {
1194 $option['ignore'] = 'data-ignore';
1197 $data->options[] = $option;
1201 // Label attributes.
1202 $data->labelattributes = [];
1203 // Unset label attributes that are already in the template.
1204 unset($this->labelattributes['for']);
1205 // Map the label attributes.
1206 foreach ($this->labelattributes as $key => $value) {
1207 $data->labelattributes[] = ['name' => $key, 'value' => $value];
1210 // Help icon.
1211 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1213 return $data;
1218 * Simple URL selection widget description.
1220 * @copyright 2009 Petr Skoda
1221 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1222 * @since Moodle 2.0
1223 * @package core
1224 * @category output
1226 class url_select implements renderable, templatable {
1228 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
1229 * it is also possible to specify optgroup as complex label array ex.:
1230 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1231 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1233 var $urls;
1236 * @var string Selected option
1238 var $selected;
1241 * @var array Nothing selected
1243 var $nothing;
1246 * @var array Extra select field attributes
1248 var $attributes = array();
1251 * @var string Button label
1253 var $label = '';
1256 * @var array Button label's attributes
1258 var $labelattributes = array();
1261 * @var string Wrapping div class
1263 var $class = 'urlselect';
1266 * @var bool True if button disabled, false if normal
1268 var $disabled = false;
1271 * @var string Button tooltip
1273 var $tooltip = null;
1276 * @var string Form id
1278 var $formid = null;
1281 * @var help_icon The help icon for this element.
1283 var $helpicon = null;
1286 * @var string If set, makes button visible with given name for button
1288 var $showbutton = null;
1291 * Constructor
1292 * @param array $urls list of options
1293 * @param string $selected selected element
1294 * @param array $nothing
1295 * @param string $formid
1296 * @param string $showbutton Set to text of button if it should be visible
1297 * or null if it should be hidden (hidden version always has text 'go')
1299 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
1300 $this->urls = $urls;
1301 $this->selected = $selected;
1302 $this->nothing = $nothing;
1303 $this->formid = $formid;
1304 $this->showbutton = $showbutton;
1308 * Adds help icon.
1310 * @deprecated since Moodle 2.0
1312 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1313 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1317 * Adds help icon.
1319 * @param string $identifier The keyword that defines a help page
1320 * @param string $component
1322 public function set_help_icon($identifier, $component = 'moodle') {
1323 $this->helpicon = new help_icon($identifier, $component);
1327 * Sets select's label
1329 * @param string $label
1330 * @param array $attributes (optional)
1332 public function set_label($label, $attributes = array()) {
1333 $this->label = $label;
1334 $this->labelattributes = $attributes;
1338 * Clean a URL.
1340 * @param string $value The URL.
1341 * @return The cleaned URL.
1343 protected function clean_url($value) {
1344 global $CFG;
1346 if (empty($value)) {
1347 // Nothing.
1349 } else if (strpos($value, $CFG->wwwroot . '/') === 0) {
1350 $value = str_replace($CFG->wwwroot, '', $value);
1352 } else if (strpos($value, '/') !== 0) {
1353 debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER);
1356 return $value;
1360 * Flatten the options for Mustache.
1362 * This also cleans the URLs.
1364 * @param array $options The options.
1365 * @param array $nothing The nothing option.
1366 * @return array
1368 protected function flatten_options($options, $nothing) {
1369 $flattened = [];
1371 foreach ($options as $value => $option) {
1372 if (is_array($option)) {
1373 foreach ($option as $groupname => $optoptions) {
1374 if (!isset($flattened[$groupname])) {
1375 $flattened[$groupname] = [
1376 'name' => $groupname,
1377 'isgroup' => true,
1378 'options' => []
1381 foreach ($optoptions as $optvalue => $optoption) {
1382 $cleanedvalue = $this->clean_url($optvalue);
1383 $flattened[$groupname]['options'][$cleanedvalue] = [
1384 'name' => $optoption,
1385 'value' => $cleanedvalue,
1386 'selected' => $this->selected == $optvalue,
1391 } else {
1392 $cleanedvalue = $this->clean_url($value);
1393 $flattened[$cleanedvalue] = [
1394 'name' => $option,
1395 'value' => $cleanedvalue,
1396 'selected' => $this->selected == $value,
1401 if (!empty($nothing)) {
1402 $value = key($nothing);
1403 $name = reset($nothing);
1404 $flattened = [
1405 $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value]
1406 ] + $flattened;
1409 // Make non-associative array.
1410 foreach ($flattened as $key => $value) {
1411 if (!empty($value['options'])) {
1412 $flattened[$key]['options'] = array_values($value['options']);
1415 $flattened = array_values($flattened);
1417 return $flattened;
1421 * Export for template.
1423 * @param renderer_base $output Renderer.
1424 * @return stdClass
1426 public function export_for_template(renderer_base $output) {
1427 $attributes = $this->attributes;
1429 $data = new stdClass();
1430 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('url_select_f');
1431 $data->classes = $this->class;
1432 $data->label = $this->label;
1433 $data->disabled = $this->disabled;
1434 $data->title = $this->tooltip;
1435 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('url_select');
1436 $data->sesskey = sesskey();
1437 $data->action = (new moodle_url('/course/jumpto.php'))->out(false);
1439 // Remove attributes passed as property directly.
1440 unset($attributes['class']);
1441 unset($attributes['id']);
1442 unset($attributes['name']);
1443 unset($attributes['title']);
1444 unset($attributes['disabled']);
1446 $data->showbutton = $this->showbutton;
1448 // Select options.
1449 $nothing = false;
1450 if (is_string($this->nothing) && $this->nothing !== '') {
1451 $nothing = ['' => $this->nothing];
1452 } else if (is_array($this->nothing)) {
1453 $nothingvalue = reset($this->nothing);
1454 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1455 $nothing = [key($this->nothing) => get_string('choosedots')];
1456 } else {
1457 $nothing = $this->nothing;
1460 $data->options = $this->flatten_options($this->urls, $nothing);
1462 // Label attributes.
1463 $data->labelattributes = [];
1464 // Unset label attributes that are already in the template.
1465 unset($this->labelattributes['for']);
1466 // Map the label attributes.
1467 foreach ($this->labelattributes as $key => $value) {
1468 $data->labelattributes[] = ['name' => $key, 'value' => $value];
1471 // Help icon.
1472 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1474 // Finally all the remaining attributes.
1475 $data->attributes = [];
1476 foreach ($attributes as $key => $value) {
1477 $data->attributes[] = ['name' => $key, 'value' => $value];
1480 return $data;
1485 * Data structure describing html link with special action attached.
1487 * @copyright 2010 Petr Skoda
1488 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1489 * @since Moodle 2.0
1490 * @package core
1491 * @category output
1493 class action_link implements renderable {
1496 * @var moodle_url Href url
1498 public $url;
1501 * @var string Link text HTML fragment
1503 public $text;
1506 * @var array HTML attributes
1508 public $attributes;
1511 * @var array List of actions attached to link
1513 public $actions;
1516 * @var pix_icon Optional pix icon to render with the link
1518 public $icon;
1521 * Constructor
1522 * @param moodle_url $url
1523 * @param string $text HTML fragment
1524 * @param component_action $action
1525 * @param array $attributes associative array of html link attributes + disabled
1526 * @param pix_icon $icon optional pix_icon to render with the link text
1528 public function __construct(moodle_url $url,
1529 $text,
1530 component_action $action=null,
1531 array $attributes=null,
1532 pix_icon $icon=null) {
1533 $this->url = clone($url);
1534 $this->text = $text;
1535 if (empty($attributes['id'])) {
1536 $attributes['id'] = html_writer::random_id('action_link');
1538 $this->attributes = (array)$attributes;
1539 if ($action) {
1540 $this->add_action($action);
1542 $this->icon = $icon;
1546 * Add action to the link.
1548 * @param component_action $action
1550 public function add_action(component_action $action) {
1551 $this->actions[] = $action;
1555 * Adds a CSS class to this action link object
1556 * @param string $class
1558 public function add_class($class) {
1559 if (empty($this->attributes['class'])) {
1560 $this->attributes['class'] = $class;
1561 } else {
1562 $this->attributes['class'] .= ' ' . $class;
1567 * Returns true if the specified class has been added to this link.
1568 * @param string $class
1569 * @return bool
1571 public function has_class($class) {
1572 return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
1576 * Return the rendered HTML for the icon. Useful for rendering action links in a template.
1577 * @return string
1579 public function get_icon_html() {
1580 global $OUTPUT;
1581 if (!$this->icon) {
1582 return '';
1584 return $OUTPUT->render($this->icon);
1588 * Export for template.
1590 * @param renderer_base $output The renderer.
1591 * @return stdClass
1593 public function export_for_template(renderer_base $output) {
1594 $data = new stdClass();
1595 $attributes = $this->attributes;
1597 $data->id = $attributes['id'];
1598 unset($attributes['id']);
1600 $data->disabled = !empty($attributes['disabled']);
1601 unset($attributes['disabled']);
1603 $data->text = $this->text instanceof renderable ? $output->render($this->text) : (string) $this->text;
1604 $data->url = $this->url ? $this->url->out(false) : '';
1605 $data->icon = $this->icon ? $this->icon->export_for_pix() : null;
1606 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
1607 unset($attributes['class']);
1609 $data->attributes = array_map(function($key, $value) {
1610 return [
1611 'name' => $key,
1612 'value' => $value
1614 }, array_keys($attributes), $attributes);
1616 $data->actions = array_map(function($action) use ($output) {
1617 return $action->export_for_template($output);
1618 }, !empty($this->actions) ? $this->actions : []);
1619 $data->hasactions = !empty($this->actions);
1621 return $data;
1626 * Simple html output class
1628 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1629 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1630 * @since Moodle 2.0
1631 * @package core
1632 * @category output
1634 class html_writer {
1637 * Outputs a tag with attributes and contents
1639 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1640 * @param string $contents What goes between the opening and closing tags
1641 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1642 * @return string HTML fragment
1644 public static function tag($tagname, $contents, array $attributes = null) {
1645 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1649 * Outputs an opening tag with attributes
1651 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1652 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1653 * @return string HTML fragment
1655 public static function start_tag($tagname, array $attributes = null) {
1656 return '<' . $tagname . self::attributes($attributes) . '>';
1660 * Outputs a closing tag
1662 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1663 * @return string HTML fragment
1665 public static function end_tag($tagname) {
1666 return '</' . $tagname . '>';
1670 * Outputs an empty tag with attributes
1672 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1673 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1674 * @return string HTML fragment
1676 public static function empty_tag($tagname, array $attributes = null) {
1677 return '<' . $tagname . self::attributes($attributes) . ' />';
1681 * Outputs a tag, but only if the contents are not empty
1683 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1684 * @param string $contents What goes between the opening and closing tags
1685 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1686 * @return string HTML fragment
1688 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1689 if ($contents === '' || is_null($contents)) {
1690 return '';
1692 return self::tag($tagname, $contents, $attributes);
1696 * Outputs a HTML attribute and value
1698 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1699 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1700 * @return string HTML fragment
1702 public static function attribute($name, $value) {
1703 if ($value instanceof moodle_url) {
1704 return ' ' . $name . '="' . $value->out() . '"';
1707 // special case, we do not want these in output
1708 if ($value === null) {
1709 return '';
1712 // no sloppy trimming here!
1713 return ' ' . $name . '="' . s($value) . '"';
1717 * Outputs a list of HTML attributes and values
1719 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1720 * The values will be escaped with {@link s()}
1721 * @return string HTML fragment
1723 public static function attributes(array $attributes = null) {
1724 $attributes = (array)$attributes;
1725 $output = '';
1726 foreach ($attributes as $name => $value) {
1727 $output .= self::attribute($name, $value);
1729 return $output;
1733 * Generates a simple image tag with attributes.
1735 * @param string $src The source of image
1736 * @param string $alt The alternate text for image
1737 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1738 * @return string HTML fragment
1740 public static function img($src, $alt, array $attributes = null) {
1741 $attributes = (array)$attributes;
1742 $attributes['src'] = $src;
1743 $attributes['alt'] = $alt;
1745 return self::empty_tag('img', $attributes);
1749 * Generates random html element id.
1751 * @staticvar int $counter
1752 * @staticvar type $uniq
1753 * @param string $base A string fragment that will be included in the random ID.
1754 * @return string A unique ID
1756 public static function random_id($base='random') {
1757 static $counter = 0;
1758 static $uniq;
1760 if (!isset($uniq)) {
1761 $uniq = uniqid();
1764 $counter++;
1765 return $base.$uniq.$counter;
1769 * Generates a simple html link
1771 * @param string|moodle_url $url The URL
1772 * @param string $text The text
1773 * @param array $attributes HTML attributes
1774 * @return string HTML fragment
1776 public static function link($url, $text, array $attributes = null) {
1777 $attributes = (array)$attributes;
1778 $attributes['href'] = $url;
1779 return self::tag('a', $text, $attributes);
1783 * Generates a simple checkbox with optional label
1785 * @param string $name The name of the checkbox
1786 * @param string $value The value of the checkbox
1787 * @param bool $checked Whether the checkbox is checked
1788 * @param string $label The label for the checkbox
1789 * @param array $attributes Any attributes to apply to the checkbox
1790 * @param array $labelattributes Any attributes to apply to the label, if present
1791 * @return string html fragment
1793 public static function checkbox($name, $value, $checked = true, $label = '',
1794 array $attributes = null, array $labelattributes = null) {
1795 $attributes = (array) $attributes;
1796 $output = '';
1798 if ($label !== '' and !is_null($label)) {
1799 if (empty($attributes['id'])) {
1800 $attributes['id'] = self::random_id('checkbox_');
1803 $attributes['type'] = 'checkbox';
1804 $attributes['value'] = $value;
1805 $attributes['name'] = $name;
1806 $attributes['checked'] = $checked ? 'checked' : null;
1808 $output .= self::empty_tag('input', $attributes);
1810 if ($label !== '' and !is_null($label)) {
1811 $labelattributes = (array) $labelattributes;
1812 $labelattributes['for'] = $attributes['id'];
1813 $output .= self::tag('label', $label, $labelattributes);
1816 return $output;
1820 * Generates a simple select yes/no form field
1822 * @param string $name name of select element
1823 * @param bool $selected
1824 * @param array $attributes - html select element attributes
1825 * @return string HTML fragment
1827 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1828 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1829 return self::select($options, $name, $selected, null, $attributes);
1833 * Generates a simple select form field
1835 * Note this function does HTML escaping on the optgroup labels, but not on the choice labels.
1837 * @param array $options associative array value=>label ex.:
1838 * array(1=>'One, 2=>Two)
1839 * it is also possible to specify optgroup as complex label array ex.:
1840 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1841 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1842 * @param string $name name of select element
1843 * @param string|array $selected value or array of values depending on multiple attribute
1844 * @param array|bool $nothing add nothing selected option, or false of not added
1845 * @param array $attributes html select element attributes
1846 * @return string HTML fragment
1848 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1849 $attributes = (array)$attributes;
1850 if (is_array($nothing)) {
1851 foreach ($nothing as $k=>$v) {
1852 if ($v === 'choose' or $v === 'choosedots') {
1853 $nothing[$k] = get_string('choosedots');
1856 $options = $nothing + $options; // keep keys, do not override
1858 } else if (is_string($nothing) and $nothing !== '') {
1859 // BC
1860 $options = array(''=>$nothing) + $options;
1863 // we may accept more values if multiple attribute specified
1864 $selected = (array)$selected;
1865 foreach ($selected as $k=>$v) {
1866 $selected[$k] = (string)$v;
1869 if (!isset($attributes['id'])) {
1870 $id = 'menu'.$name;
1871 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1872 $id = str_replace('[', '', $id);
1873 $id = str_replace(']', '', $id);
1874 $attributes['id'] = $id;
1877 if (!isset($attributes['class'])) {
1878 $class = 'menu'.$name;
1879 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1880 $class = str_replace('[', '', $class);
1881 $class = str_replace(']', '', $class);
1882 $attributes['class'] = $class;
1884 $attributes['class'] = 'select custom-select ' . $attributes['class']; // Add 'select' selector always.
1886 $attributes['name'] = $name;
1888 if (!empty($attributes['disabled'])) {
1889 $attributes['disabled'] = 'disabled';
1890 } else {
1891 unset($attributes['disabled']);
1894 $output = '';
1895 foreach ($options as $value=>$label) {
1896 if (is_array($label)) {
1897 // ignore key, it just has to be unique
1898 $output .= self::select_optgroup(key($label), current($label), $selected);
1899 } else {
1900 $output .= self::select_option($label, $value, $selected);
1903 return self::tag('select', $output, $attributes);
1907 * Returns HTML to display a select box option.
1909 * @param string $label The label to display as the option.
1910 * @param string|int $value The value the option represents
1911 * @param array $selected An array of selected options
1912 * @return string HTML fragment
1914 private static function select_option($label, $value, array $selected) {
1915 $attributes = array();
1916 $value = (string)$value;
1917 if (in_array($value, $selected, true)) {
1918 $attributes['selected'] = 'selected';
1920 $attributes['value'] = $value;
1921 return self::tag('option', $label, $attributes);
1925 * Returns HTML to display a select box option group.
1927 * @param string $groupname The label to use for the group
1928 * @param array $options The options in the group
1929 * @param array $selected An array of selected values.
1930 * @return string HTML fragment.
1932 private static function select_optgroup($groupname, $options, array $selected) {
1933 if (empty($options)) {
1934 return '';
1936 $attributes = array('label'=>$groupname);
1937 $output = '';
1938 foreach ($options as $value=>$label) {
1939 $output .= self::select_option($label, $value, $selected);
1941 return self::tag('optgroup', $output, $attributes);
1945 * This is a shortcut for making an hour selector menu.
1947 * @param string $type The type of selector (years, months, days, hours, minutes)
1948 * @param string $name fieldname
1949 * @param int $currenttime A default timestamp in GMT
1950 * @param int $step minute spacing
1951 * @param array $attributes - html select element attributes
1952 * @return HTML fragment
1954 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1955 global $OUTPUT;
1957 if (!$currenttime) {
1958 $currenttime = time();
1960 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1961 $currentdate = $calendartype->timestamp_to_date_array($currenttime);
1962 $userdatetype = $type;
1963 $timeunits = array();
1965 switch ($type) {
1966 case 'years':
1967 $timeunits = $calendartype->get_years();
1968 $userdatetype = 'year';
1969 break;
1970 case 'months':
1971 $timeunits = $calendartype->get_months();
1972 $userdatetype = 'month';
1973 $currentdate['month'] = (int)$currentdate['mon'];
1974 break;
1975 case 'days':
1976 $timeunits = $calendartype->get_days();
1977 $userdatetype = 'mday';
1978 break;
1979 case 'hours':
1980 for ($i=0; $i<=23; $i++) {
1981 $timeunits[$i] = sprintf("%02d",$i);
1983 break;
1984 case 'minutes':
1985 if ($step != 1) {
1986 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1989 for ($i=0; $i<=59; $i+=$step) {
1990 $timeunits[$i] = sprintf("%02d",$i);
1992 break;
1993 default:
1994 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1997 $attributes = (array) $attributes;
1998 $data = (object) [
1999 'name' => $name,
2000 'id' => !empty($attributes['id']) ? $attributes['id'] : self::random_id('ts_'),
2001 'label' => get_string(substr($type, 0, -1), 'form'),
2002 'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) {
2003 return [
2004 'name' => $timeunits[$value],
2005 'value' => $value,
2006 'selected' => $currentdate[$userdatetype] == $value
2008 }, array_keys($timeunits)),
2011 unset($attributes['id']);
2012 unset($attributes['name']);
2013 $data->attributes = array_map(function($name) use ($attributes) {
2014 return [
2015 'name' => $name,
2016 'value' => $attributes[$name]
2018 }, array_keys($attributes));
2020 return $OUTPUT->render_from_template('core/select_time', $data);
2024 * Shortcut for quick making of lists
2026 * Note: 'list' is a reserved keyword ;-)
2028 * @param array $items
2029 * @param array $attributes
2030 * @param string $tag ul or ol
2031 * @return string
2033 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
2034 $output = html_writer::start_tag($tag, $attributes)."\n";
2035 foreach ($items as $item) {
2036 $output .= html_writer::tag('li', $item)."\n";
2038 $output .= html_writer::end_tag($tag);
2039 return $output;
2043 * Returns hidden input fields created from url parameters.
2045 * @param moodle_url $url
2046 * @param array $exclude list of excluded parameters
2047 * @return string HTML fragment
2049 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
2050 $exclude = (array)$exclude;
2051 $params = $url->params();
2052 foreach ($exclude as $key) {
2053 unset($params[$key]);
2056 $output = '';
2057 foreach ($params as $key => $value) {
2058 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
2059 $output .= self::empty_tag('input', $attributes)."\n";
2061 return $output;
2065 * Generate a script tag containing the the specified code.
2067 * @param string $jscode the JavaScript code
2068 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
2069 * @return string HTML, the code wrapped in <script> tags.
2071 public static function script($jscode, $url=null) {
2072 if ($jscode) {
2073 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n") . "\n";
2075 } else if ($url) {
2076 return self::tag('script', '', ['src' => $url]) . "\n";
2078 } else {
2079 return '';
2084 * Renders HTML table
2086 * This method may modify the passed instance by adding some default properties if they are not set yet.
2087 * If this is not what you want, you should make a full clone of your data before passing them to this
2088 * method. In most cases this is not an issue at all so we do not clone by default for performance
2089 * and memory consumption reasons.
2091 * @param html_table $table data to be rendered
2092 * @return string HTML code
2094 public static function table(html_table $table) {
2095 // prepare table data and populate missing properties with reasonable defaults
2096 if (!empty($table->align)) {
2097 foreach ($table->align as $key => $aa) {
2098 if ($aa) {
2099 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
2100 } else {
2101 $table->align[$key] = null;
2105 if (!empty($table->size)) {
2106 foreach ($table->size as $key => $ss) {
2107 if ($ss) {
2108 $table->size[$key] = 'width:'. $ss .';';
2109 } else {
2110 $table->size[$key] = null;
2114 if (!empty($table->wrap)) {
2115 foreach ($table->wrap as $key => $ww) {
2116 if ($ww) {
2117 $table->wrap[$key] = 'white-space:nowrap;';
2118 } else {
2119 $table->wrap[$key] = '';
2123 if (!empty($table->head)) {
2124 foreach ($table->head as $key => $val) {
2125 if (!isset($table->align[$key])) {
2126 $table->align[$key] = null;
2128 if (!isset($table->size[$key])) {
2129 $table->size[$key] = null;
2131 if (!isset($table->wrap[$key])) {
2132 $table->wrap[$key] = null;
2137 if (empty($table->attributes['class'])) {
2138 $table->attributes['class'] = 'generaltable';
2140 if (!empty($table->tablealign)) {
2141 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
2144 // explicitly assigned properties override those defined via $table->attributes
2145 $table->attributes['class'] = trim($table->attributes['class']);
2146 $attributes = array_merge($table->attributes, array(
2147 'id' => $table->id,
2148 'width' => $table->width,
2149 'summary' => $table->summary,
2150 'cellpadding' => $table->cellpadding,
2151 'cellspacing' => $table->cellspacing,
2153 $output = html_writer::start_tag('table', $attributes) . "\n";
2155 $countcols = 0;
2157 // Output a caption if present.
2158 if (!empty($table->caption)) {
2159 $captionattributes = array();
2160 if ($table->captionhide) {
2161 $captionattributes['class'] = 'accesshide';
2163 $output .= html_writer::tag(
2164 'caption',
2165 $table->caption,
2166 $captionattributes
2170 if (!empty($table->head)) {
2171 $countcols = count($table->head);
2173 $output .= html_writer::start_tag('thead', array()) . "\n";
2174 $output .= html_writer::start_tag('tr', array()) . "\n";
2175 $keys = array_keys($table->head);
2176 $lastkey = end($keys);
2178 foreach ($table->head as $key => $heading) {
2179 // Convert plain string headings into html_table_cell objects
2180 if (!($heading instanceof html_table_cell)) {
2181 $headingtext = $heading;
2182 $heading = new html_table_cell();
2183 $heading->text = $headingtext;
2184 $heading->header = true;
2187 if ($heading->header !== false) {
2188 $heading->header = true;
2191 $tagtype = 'td';
2192 if ($heading->header && (string)$heading->text != '') {
2193 $tagtype = 'th';
2196 $heading->attributes['class'] .= ' header c' . $key;
2197 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
2198 $heading->colspan = $table->headspan[$key];
2199 $countcols += $table->headspan[$key] - 1;
2202 if ($key == $lastkey) {
2203 $heading->attributes['class'] .= ' lastcol';
2205 if (isset($table->colclasses[$key])) {
2206 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
2208 $heading->attributes['class'] = trim($heading->attributes['class']);
2209 $attributes = array_merge($heading->attributes, [
2210 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
2211 'colspan' => $heading->colspan,
2214 if ($tagtype == 'th') {
2215 $attributes['scope'] = !empty($heading->scope) ? $heading->scope : 'col';
2218 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
2220 $output .= html_writer::end_tag('tr') . "\n";
2221 $output .= html_writer::end_tag('thead') . "\n";
2223 if (empty($table->data)) {
2224 // For valid XHTML strict every table must contain either a valid tr
2225 // or a valid tbody... both of which must contain a valid td
2226 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
2227 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
2228 $output .= html_writer::end_tag('tbody');
2232 if (!empty($table->data)) {
2233 $keys = array_keys($table->data);
2234 $lastrowkey = end($keys);
2235 $output .= html_writer::start_tag('tbody', array());
2237 foreach ($table->data as $key => $row) {
2238 if (($row === 'hr') && ($countcols)) {
2239 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
2240 } else {
2241 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
2242 if (!($row instanceof html_table_row)) {
2243 $newrow = new html_table_row();
2245 foreach ($row as $cell) {
2246 if (!($cell instanceof html_table_cell)) {
2247 $cell = new html_table_cell($cell);
2249 $newrow->cells[] = $cell;
2251 $row = $newrow;
2254 if (isset($table->rowclasses[$key])) {
2255 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
2258 if ($key == $lastrowkey) {
2259 $row->attributes['class'] .= ' lastrow';
2262 // Explicitly assigned properties should override those defined in the attributes.
2263 $row->attributes['class'] = trim($row->attributes['class']);
2264 $trattributes = array_merge($row->attributes, array(
2265 'id' => $row->id,
2266 'style' => $row->style,
2268 $output .= html_writer::start_tag('tr', $trattributes) . "\n";
2269 $keys2 = array_keys($row->cells);
2270 $lastkey = end($keys2);
2272 $gotlastkey = false; //flag for sanity checking
2273 foreach ($row->cells as $key => $cell) {
2274 if ($gotlastkey) {
2275 //This should never happen. Why do we have a cell after the last cell?
2276 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
2279 if (!($cell instanceof html_table_cell)) {
2280 $mycell = new html_table_cell();
2281 $mycell->text = $cell;
2282 $cell = $mycell;
2285 if (($cell->header === true) && empty($cell->scope)) {
2286 $cell->scope = 'row';
2289 if (isset($table->colclasses[$key])) {
2290 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
2293 $cell->attributes['class'] .= ' cell c' . $key;
2294 if ($key == $lastkey) {
2295 $cell->attributes['class'] .= ' lastcol';
2296 $gotlastkey = true;
2298 $tdstyle = '';
2299 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
2300 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
2301 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
2302 $cell->attributes['class'] = trim($cell->attributes['class']);
2303 $tdattributes = array_merge($cell->attributes, array(
2304 'style' => $tdstyle . $cell->style,
2305 'colspan' => $cell->colspan,
2306 'rowspan' => $cell->rowspan,
2307 'id' => $cell->id,
2308 'abbr' => $cell->abbr,
2309 'scope' => $cell->scope,
2311 $tagtype = 'td';
2312 if ($cell->header === true) {
2313 $tagtype = 'th';
2315 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
2318 $output .= html_writer::end_tag('tr') . "\n";
2320 $output .= html_writer::end_tag('tbody') . "\n";
2322 $output .= html_writer::end_tag('table') . "\n";
2324 if ($table->responsive) {
2325 return self::div($output, 'table-responsive');
2328 return $output;
2332 * Renders form element label
2334 * By default, the label is suffixed with a label separator defined in the
2335 * current language pack (colon by default in the English lang pack).
2336 * Adding the colon can be explicitly disabled if needed. Label separators
2337 * are put outside the label tag itself so they are not read by
2338 * screenreaders (accessibility).
2340 * Parameter $for explicitly associates the label with a form control. When
2341 * set, the value of this attribute must be the same as the value of
2342 * the id attribute of the form control in the same document. When null,
2343 * the label being defined is associated with the control inside the label
2344 * element.
2346 * @param string $text content of the label tag
2347 * @param string|null $for id of the element this label is associated with, null for no association
2348 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
2349 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
2350 * @return string HTML of the label element
2352 public static function label($text, $for, $colonize = true, array $attributes=array()) {
2353 if (!is_null($for)) {
2354 $attributes = array_merge($attributes, array('for' => $for));
2356 $text = trim($text);
2357 $label = self::tag('label', $text, $attributes);
2359 // TODO MDL-12192 $colonize disabled for now yet
2360 // if (!empty($text) and $colonize) {
2361 // // the $text may end with the colon already, though it is bad string definition style
2362 // $colon = get_string('labelsep', 'langconfig');
2363 // if (!empty($colon)) {
2364 // $trimmed = trim($colon);
2365 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
2366 // //debugging('The label text should not end with colon or other label separator,
2367 // // please fix the string definition.', DEBUG_DEVELOPER);
2368 // } else {
2369 // $label .= $colon;
2370 // }
2371 // }
2372 // }
2374 return $label;
2378 * Combines a class parameter with other attributes. Aids in code reduction
2379 * because the class parameter is very frequently used.
2381 * If the class attribute is specified both in the attributes and in the
2382 * class parameter, the two values are combined with a space between.
2384 * @param string $class Optional CSS class (or classes as space-separated list)
2385 * @param array $attributes Optional other attributes as array
2386 * @return array Attributes (or null if still none)
2388 private static function add_class($class = '', array $attributes = null) {
2389 if ($class !== '') {
2390 $classattribute = array('class' => $class);
2391 if ($attributes) {
2392 if (array_key_exists('class', $attributes)) {
2393 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
2394 } else {
2395 $attributes = $classattribute + $attributes;
2397 } else {
2398 $attributes = $classattribute;
2401 return $attributes;
2405 * Creates a <div> tag. (Shortcut function.)
2407 * @param string $content HTML content of tag
2408 * @param string $class Optional CSS class (or classes as space-separated list)
2409 * @param array $attributes Optional other attributes as array
2410 * @return string HTML code for div
2412 public static function div($content, $class = '', array $attributes = null) {
2413 return self::tag('div', $content, self::add_class($class, $attributes));
2417 * Starts a <div> tag. (Shortcut function.)
2419 * @param string $class Optional CSS class (or classes as space-separated list)
2420 * @param array $attributes Optional other attributes as array
2421 * @return string HTML code for open div tag
2423 public static function start_div($class = '', array $attributes = null) {
2424 return self::start_tag('div', self::add_class($class, $attributes));
2428 * Ends a <div> tag. (Shortcut function.)
2430 * @return string HTML code for close div tag
2432 public static function end_div() {
2433 return self::end_tag('div');
2437 * Creates a <span> tag. (Shortcut function.)
2439 * @param string $content HTML content of tag
2440 * @param string $class Optional CSS class (or classes as space-separated list)
2441 * @param array $attributes Optional other attributes as array
2442 * @return string HTML code for span
2444 public static function span($content, $class = '', array $attributes = null) {
2445 return self::tag('span', $content, self::add_class($class, $attributes));
2449 * Starts a <span> tag. (Shortcut function.)
2451 * @param string $class Optional CSS class (or classes as space-separated list)
2452 * @param array $attributes Optional other attributes as array
2453 * @return string HTML code for open span tag
2455 public static function start_span($class = '', array $attributes = null) {
2456 return self::start_tag('span', self::add_class($class, $attributes));
2460 * Ends a <span> tag. (Shortcut function.)
2462 * @return string HTML code for close span tag
2464 public static function end_span() {
2465 return self::end_tag('span');
2470 * Simple javascript output class
2472 * @copyright 2010 Petr Skoda
2473 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2474 * @since Moodle 2.0
2475 * @package core
2476 * @category output
2478 class js_writer {
2481 * Returns javascript code calling the function
2483 * @param string $function function name, can be complex like Y.Event.purgeElement
2484 * @param array $arguments parameters
2485 * @param int $delay execution delay in seconds
2486 * @return string JS code fragment
2488 public static function function_call($function, array $arguments = null, $delay=0) {
2489 if ($arguments) {
2490 $arguments = array_map('json_encode', convert_to_array($arguments));
2491 $arguments = implode(', ', $arguments);
2492 } else {
2493 $arguments = '';
2495 $js = "$function($arguments);";
2497 if ($delay) {
2498 $delay = $delay * 1000; // in miliseconds
2499 $js = "setTimeout(function() { $js }, $delay);";
2501 return $js . "\n";
2505 * Special function which adds Y as first argument of function call.
2507 * @param string $function The function to call
2508 * @param array $extraarguments Any arguments to pass to it
2509 * @return string Some JS code
2511 public static function function_call_with_Y($function, array $extraarguments = null) {
2512 if ($extraarguments) {
2513 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
2514 $arguments = 'Y, ' . implode(', ', $extraarguments);
2515 } else {
2516 $arguments = 'Y';
2518 return "$function($arguments);\n";
2522 * Returns JavaScript code to initialise a new object
2524 * @param string $var If it is null then no var is assigned the new object.
2525 * @param string $class The class to initialise an object for.
2526 * @param array $arguments An array of args to pass to the init method.
2527 * @param array $requirements Any modules required for this class.
2528 * @param int $delay The delay before initialisation. 0 = no delay.
2529 * @return string Some JS code
2531 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
2532 if (is_array($arguments)) {
2533 $arguments = array_map('json_encode', convert_to_array($arguments));
2534 $arguments = implode(', ', $arguments);
2537 if ($var === null) {
2538 $js = "new $class(Y, $arguments);";
2539 } else if (strpos($var, '.')!==false) {
2540 $js = "$var = new $class(Y, $arguments);";
2541 } else {
2542 $js = "var $var = new $class(Y, $arguments);";
2545 if ($delay) {
2546 $delay = $delay * 1000; // in miliseconds
2547 $js = "setTimeout(function() { $js }, $delay);";
2550 if (count($requirements) > 0) {
2551 $requirements = implode("', '", $requirements);
2552 $js = "Y.use('$requirements', function(Y){ $js });";
2554 return $js."\n";
2558 * Returns code setting value to variable
2560 * @param string $name
2561 * @param mixed $value json serialised value
2562 * @param bool $usevar add var definition, ignored for nested properties
2563 * @return string JS code fragment
2565 public static function set_variable($name, $value, $usevar = true) {
2566 $output = '';
2568 if ($usevar) {
2569 if (strpos($name, '.')) {
2570 $output .= '';
2571 } else {
2572 $output .= 'var ';
2576 $output .= "$name = ".json_encode($value).";";
2578 return $output;
2582 * Writes event handler attaching code
2584 * @param array|string $selector standard YUI selector for elements, may be
2585 * array or string, element id is in the form "#idvalue"
2586 * @param string $event A valid DOM event (click, mousedown, change etc.)
2587 * @param string $function The name of the function to call
2588 * @param array $arguments An optional array of argument parameters to pass to the function
2589 * @return string JS code fragment
2591 public static function event_handler($selector, $event, $function, array $arguments = null) {
2592 $selector = json_encode($selector);
2593 $output = "Y.on('$event', $function, $selector, null";
2594 if (!empty($arguments)) {
2595 $output .= ', ' . json_encode($arguments);
2597 return $output . ");\n";
2602 * Holds all the information required to render a <table> by {@link core_renderer::table()}
2604 * Example of usage:
2605 * $t = new html_table();
2606 * ... // set various properties of the object $t as described below
2607 * echo html_writer::table($t);
2609 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
2610 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2611 * @since Moodle 2.0
2612 * @package core
2613 * @category output
2615 class html_table {
2618 * @var string Value to use for the id attribute of the table
2620 public $id = null;
2623 * @var array Attributes of HTML attributes for the <table> element
2625 public $attributes = array();
2628 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
2629 * For more control over the rendering of the headers, an array of html_table_cell objects
2630 * can be passed instead of an array of strings.
2632 * Example of usage:
2633 * $t->head = array('Student', 'Grade');
2635 public $head;
2638 * @var array An array that can be used to make a heading span multiple columns.
2639 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
2640 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
2642 * Example of usage:
2643 * $t->headspan = array(2,1);
2645 public $headspan;
2648 * @var array An array of column alignments.
2649 * The value is used as CSS 'text-align' property. Therefore, possible
2650 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
2651 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
2653 * Examples of usage:
2654 * $t->align = array(null, 'right');
2655 * or
2656 * $t->align[1] = 'right';
2658 public $align;
2661 * @var array The value is used as CSS 'size' property.
2663 * Examples of usage:
2664 * $t->size = array('50%', '50%');
2665 * or
2666 * $t->size[1] = '120px';
2668 public $size;
2671 * @var array An array of wrapping information.
2672 * The only possible value is 'nowrap' that sets the
2673 * CSS property 'white-space' to the value 'nowrap' in the given column.
2675 * Example of usage:
2676 * $t->wrap = array(null, 'nowrap');
2678 public $wrap;
2681 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2682 * $head specified, the string 'hr' (for horizontal ruler) can be used
2683 * instead of an array of cells data resulting in a divider rendered.
2685 * Example of usage with array of arrays:
2686 * $row1 = array('Harry Potter', '76 %');
2687 * $row2 = array('Hermione Granger', '100 %');
2688 * $t->data = array($row1, $row2);
2690 * Example with array of html_table_row objects: (used for more fine-grained control)
2691 * $cell1 = new html_table_cell();
2692 * $cell1->text = 'Harry Potter';
2693 * $cell1->colspan = 2;
2694 * $row1 = new html_table_row();
2695 * $row1->cells[] = $cell1;
2696 * $cell2 = new html_table_cell();
2697 * $cell2->text = 'Hermione Granger';
2698 * $cell3 = new html_table_cell();
2699 * $cell3->text = '100 %';
2700 * $row2 = new html_table_row();
2701 * $row2->cells = array($cell2, $cell3);
2702 * $t->data = array($row1, $row2);
2704 public $data = [];
2707 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2708 * @var string Width of the table, percentage of the page preferred.
2710 public $width = null;
2713 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2714 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2716 public $tablealign = null;
2719 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2720 * @var int Padding on each cell, in pixels
2722 public $cellpadding = null;
2725 * @var int Spacing between cells, in pixels
2726 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2728 public $cellspacing = null;
2731 * @var array Array of classes to add to particular rows, space-separated string.
2732 * Class 'lastrow' is added automatically for the last row in the table.
2734 * Example of usage:
2735 * $t->rowclasses[9] = 'tenth'
2737 public $rowclasses;
2740 * @var array An array of classes to add to every cell in a particular column,
2741 * space-separated string. Class 'cell' is added automatically by the renderer.
2742 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2743 * respectively. Class 'lastcol' is added automatically for all last cells
2744 * in a row.
2746 * Example of usage:
2747 * $t->colclasses = array(null, 'grade');
2749 public $colclasses;
2752 * @var string Description of the contents for screen readers.
2754 * The "summary" attribute on the "table" element is not supported in HTML5.
2755 * Consider describing the structure of the table in a "caption" element or in a "figure" element containing the table;
2756 * or, simplify the structure of the table so that no description is needed.
2758 * @deprecated since Moodle 3.9.
2760 public $summary;
2763 * @var string Caption for the table, typically a title.
2765 * Example of usage:
2766 * $t->caption = "TV Guide";
2768 public $caption;
2771 * @var bool Whether to hide the table's caption from sighted users.
2773 * Example of usage:
2774 * $t->caption = "TV Guide";
2775 * $t->captionhide = true;
2777 public $captionhide = false;
2779 /** @var bool Whether to make the table to be scrolled horizontally with ease. Make table responsive across all viewports. */
2780 public $responsive = true;
2783 * Constructor
2785 public function __construct() {
2786 $this->attributes['class'] = '';
2791 * Component representing a table row.
2793 * @copyright 2009 Nicolas Connault
2794 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2795 * @since Moodle 2.0
2796 * @package core
2797 * @category output
2799 class html_table_row {
2802 * @var string Value to use for the id attribute of the row.
2804 public $id = null;
2807 * @var array Array of html_table_cell objects
2809 public $cells = array();
2812 * @var string Value to use for the style attribute of the table row
2814 public $style = null;
2817 * @var array Attributes of additional HTML attributes for the <tr> element
2819 public $attributes = array();
2822 * Constructor
2823 * @param array $cells
2825 public function __construct(array $cells=null) {
2826 $this->attributes['class'] = '';
2827 $cells = (array)$cells;
2828 foreach ($cells as $cell) {
2829 if ($cell instanceof html_table_cell) {
2830 $this->cells[] = $cell;
2831 } else {
2832 $this->cells[] = new html_table_cell($cell);
2839 * Component representing a table cell.
2841 * @copyright 2009 Nicolas Connault
2842 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2843 * @since Moodle 2.0
2844 * @package core
2845 * @category output
2847 class html_table_cell {
2850 * @var string Value to use for the id attribute of the cell.
2852 public $id = null;
2855 * @var string The contents of the cell.
2857 public $text;
2860 * @var string Abbreviated version of the contents of the cell.
2862 public $abbr = null;
2865 * @var int Number of columns this cell should span.
2867 public $colspan = null;
2870 * @var int Number of rows this cell should span.
2872 public $rowspan = null;
2875 * @var string Defines a way to associate header cells and data cells in a table.
2877 public $scope = null;
2880 * @var bool Whether or not this cell is a header cell.
2882 public $header = null;
2885 * @var string Value to use for the style attribute of the table cell
2887 public $style = null;
2890 * @var array Attributes of additional HTML attributes for the <td> element
2892 public $attributes = array();
2895 * Constructs a table cell
2897 * @param string $text
2899 public function __construct($text = null) {
2900 $this->text = $text;
2901 $this->attributes['class'] = '';
2906 * Component representing a paging bar.
2908 * @copyright 2009 Nicolas Connault
2909 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2910 * @since Moodle 2.0
2911 * @package core
2912 * @category output
2914 class paging_bar implements renderable, templatable {
2917 * @var int The maximum number of pagelinks to display.
2919 public $maxdisplay = 18;
2922 * @var int The total number of entries to be pages through..
2924 public $totalcount;
2927 * @var int The page you are currently viewing.
2929 public $page;
2932 * @var int The number of entries that should be shown per page.
2934 public $perpage;
2937 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2938 * an equals sign and the page number.
2939 * If this is a moodle_url object then the pagevar param will be replaced by
2940 * the page no, for each page.
2942 public $baseurl;
2945 * @var string This is the variable name that you use for the pagenumber in your
2946 * code (ie. 'tablepage', 'blogpage', etc)
2948 public $pagevar;
2951 * @var string A HTML link representing the "previous" page.
2953 public $previouslink = null;
2956 * @var string A HTML link representing the "next" page.
2958 public $nextlink = null;
2961 * @var string A HTML link representing the first page.
2963 public $firstlink = null;
2966 * @var string A HTML link representing the last page.
2968 public $lastlink = null;
2971 * @var array An array of strings. One of them is just a string: the current page
2973 public $pagelinks = array();
2976 * Constructor paging_bar with only the required params.
2978 * @param int $totalcount The total number of entries available to be paged through
2979 * @param int $page The page you are currently viewing
2980 * @param int $perpage The number of entries that should be shown per page
2981 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2982 * @param string $pagevar name of page parameter that holds the page number
2984 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2985 $this->totalcount = $totalcount;
2986 $this->page = $page;
2987 $this->perpage = $perpage;
2988 $this->baseurl = $baseurl;
2989 $this->pagevar = $pagevar;
2993 * Prepares the paging bar for output.
2995 * This method validates the arguments set up for the paging bar and then
2996 * produces fragments of HTML to assist display later on.
2998 * @param renderer_base $output
2999 * @param moodle_page $page
3000 * @param string $target
3001 * @throws coding_exception
3003 public function prepare(renderer_base $output, moodle_page $page, $target) {
3004 if (!isset($this->totalcount) || is_null($this->totalcount)) {
3005 throw new coding_exception('paging_bar requires a totalcount value.');
3007 if (!isset($this->page) || is_null($this->page)) {
3008 throw new coding_exception('paging_bar requires a page value.');
3010 if (empty($this->perpage)) {
3011 throw new coding_exception('paging_bar requires a perpage value.');
3013 if (empty($this->baseurl)) {
3014 throw new coding_exception('paging_bar requires a baseurl value.');
3017 if ($this->totalcount > $this->perpage) {
3018 $pagenum = $this->page - 1;
3020 if ($this->page > 0) {
3021 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
3024 if ($this->perpage > 0) {
3025 $lastpage = ceil($this->totalcount / $this->perpage);
3026 } else {
3027 $lastpage = 1;
3030 if ($this->page > round(($this->maxdisplay/3)*2)) {
3031 $currpage = $this->page - round($this->maxdisplay/3);
3033 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
3034 } else {
3035 $currpage = 0;
3038 $displaycount = $displaypage = 0;
3040 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3041 $displaypage = $currpage + 1;
3043 if ($this->page == $currpage) {
3044 $this->pagelinks[] = html_writer::span($displaypage, 'current-page');
3045 } else {
3046 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
3047 $this->pagelinks[] = $pagelink;
3050 $displaycount++;
3051 $currpage++;
3054 if ($currpage < $lastpage) {
3055 $lastpageactual = $lastpage - 1;
3056 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
3059 $pagenum = $this->page + 1;
3061 if ($pagenum != $lastpage) {
3062 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
3068 * Export for template.
3070 * @param renderer_base $output The renderer.
3071 * @return stdClass
3073 public function export_for_template(renderer_base $output) {
3074 $data = new stdClass();
3075 $data->previous = null;
3076 $data->next = null;
3077 $data->first = null;
3078 $data->last = null;
3079 $data->label = get_string('page');
3080 $data->pages = [];
3081 $data->haspages = $this->totalcount > $this->perpage;
3082 $data->pagesize = $this->perpage;
3084 if (!$data->haspages) {
3085 return $data;
3088 if ($this->page > 0) {
3089 $data->previous = [
3090 'page' => $this->page,
3091 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page - 1]))->out(false)
3095 $currpage = 0;
3096 if ($this->page > round(($this->maxdisplay / 3) * 2)) {
3097 $currpage = $this->page - round($this->maxdisplay / 3);
3098 $data->first = [
3099 'page' => 1,
3100 'url' => (new moodle_url($this->baseurl, [$this->pagevar => 0]))->out(false)
3104 $lastpage = 1;
3105 if ($this->perpage > 0) {
3106 $lastpage = ceil($this->totalcount / $this->perpage);
3109 $displaycount = 0;
3110 $displaypage = 0;
3111 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3112 $displaypage = $currpage + 1;
3114 $iscurrent = $this->page == $currpage;
3115 $link = new moodle_url($this->baseurl, [$this->pagevar => $currpage]);
3117 $data->pages[] = [
3118 'page' => $displaypage,
3119 'active' => $iscurrent,
3120 'url' => $iscurrent ? null : $link->out(false)
3123 $displaycount++;
3124 $currpage++;
3127 if ($currpage < $lastpage) {
3128 $data->last = [
3129 'page' => $lastpage,
3130 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $lastpage - 1]))->out(false)
3134 if ($this->page + 1 != $lastpage) {
3135 $data->next = [
3136 'page' => $this->page + 2,
3137 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page + 1]))->out(false)
3141 return $data;
3146 * Component representing initials bar.
3148 * @copyright 2017 Ilya Tregubov
3149 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3150 * @since Moodle 3.3
3151 * @package core
3152 * @category output
3154 class initials_bar implements renderable, templatable {
3157 * @var string Currently selected letter.
3159 public $current;
3162 * @var string Class name to add to this initial bar.
3164 public $class;
3167 * @var string The name to put in front of this initial bar.
3169 public $title;
3172 * @var string URL parameter name for this initial.
3174 public $urlvar;
3177 * @var string URL object.
3179 public $url;
3182 * @var array An array of letters in the alphabet.
3184 public $alpha;
3187 * Constructor initials_bar with only the required params.
3189 * @param string $current the currently selected letter.
3190 * @param string $class class name to add to this initial bar.
3191 * @param string $title the name to put in front of this initial bar.
3192 * @param string $urlvar URL parameter name for this initial.
3193 * @param string $url URL object.
3194 * @param array $alpha of letters in the alphabet.
3196 public function __construct($current, $class, $title, $urlvar, $url, $alpha = null) {
3197 $this->current = $current;
3198 $this->class = $class;
3199 $this->title = $title;
3200 $this->urlvar = $urlvar;
3201 $this->url = $url;
3202 $this->alpha = $alpha;
3206 * Export for template.
3208 * @param renderer_base $output The renderer.
3209 * @return stdClass
3211 public function export_for_template(renderer_base $output) {
3212 $data = new stdClass();
3214 if ($this->alpha == null) {
3215 $this->alpha = explode(',', get_string('alphabet', 'langconfig'));
3218 if ($this->current == 'all') {
3219 $this->current = '';
3222 // We want to find a letter grouping size which suits the language so
3223 // find the largest group size which is less than 15 chars.
3224 // The choice of 15 chars is the largest number of chars that reasonably
3225 // fits on the smallest supported screen size. By always using a max number
3226 // of groups which is a factor of 2, we always get nice wrapping, and the
3227 // last row is always the shortest.
3228 $groupsize = count($this->alpha);
3229 $groups = 1;
3230 while ($groupsize > 15) {
3231 $groups *= 2;
3232 $groupsize = ceil(count($this->alpha) / $groups);
3235 $groupsizelimit = 0;
3236 $groupnumber = 0;
3237 foreach ($this->alpha as $letter) {
3238 if ($groupsizelimit++ > 0 && $groupsizelimit % $groupsize == 1) {
3239 $groupnumber++;
3241 $groupletter = new stdClass();
3242 $groupletter->name = $letter;
3243 $groupletter->url = $this->url->out(false, array($this->urlvar => $letter));
3244 if ($letter == $this->current) {
3245 $groupletter->selected = $this->current;
3247 if (!isset($data->group[$groupnumber])) {
3248 $data->group[$groupnumber] = new stdClass();
3250 $data->group[$groupnumber]->letter[] = $groupletter;
3253 $data->class = $this->class;
3254 $data->title = $this->title;
3255 $data->url = $this->url->out(false, array($this->urlvar => ''));
3256 $data->current = $this->current;
3257 $data->all = get_string('all');
3259 return $data;
3264 * This class represents how a block appears on a page.
3266 * During output, each block instance is asked to return a block_contents object,
3267 * those are then passed to the $OUTPUT->block function for display.
3269 * contents should probably be generated using a moodle_block_..._renderer.
3271 * Other block-like things that need to appear on the page, for example the
3272 * add new block UI, are also represented as block_contents objects.
3274 * @copyright 2009 Tim Hunt
3275 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3276 * @since Moodle 2.0
3277 * @package core
3278 * @category output
3280 class block_contents {
3282 /** Used when the block cannot be collapsed **/
3283 const NOT_HIDEABLE = 0;
3285 /** Used when the block can be collapsed but currently is not **/
3286 const VISIBLE = 1;
3288 /** Used when the block has been collapsed **/
3289 const HIDDEN = 2;
3292 * @var int Used to set $skipid.
3294 protected static $idcounter = 1;
3297 * @var int All the blocks (or things that look like blocks) printed on
3298 * a page are given a unique number that can be used to construct id="" attributes.
3299 * This is set automatically be the {@link prepare()} method.
3300 * Do not try to set it manually.
3302 public $skipid;
3305 * @var int If this is the contents of a real block, this should be set
3306 * to the block_instance.id. Otherwise this should be set to 0.
3308 public $blockinstanceid = 0;
3311 * @var int If this is a real block instance, and there is a corresponding
3312 * block_position.id for the block on this page, this should be set to that id.
3313 * Otherwise it should be 0.
3315 public $blockpositionid = 0;
3318 * @var array An array of attribute => value pairs that are put on the outer div of this
3319 * block. {@link $id} and {@link $classes} attributes should be set separately.
3321 public $attributes;
3324 * @var string The title of this block. If this came from user input, it should already
3325 * have had format_string() processing done on it. This will be output inside
3326 * <h2> tags. Please do not cause invalid XHTML.
3328 public $title = '';
3331 * @var string The label to use when the block does not, or will not have a visible title.
3332 * You should never set this as well as title... it will just be ignored.
3334 public $arialabel = '';
3337 * @var string HTML for the content
3339 public $content = '';
3342 * @var array An alternative to $content, it you want a list of things with optional icons.
3344 public $footer = '';
3347 * @var string Any small print that should appear under the block to explain
3348 * to the teacher about the block, for example 'This is a sticky block that was
3349 * added in the system context.'
3351 public $annotation = '';
3354 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
3355 * the user can toggle whether this block is visible.
3357 public $collapsible = self::NOT_HIDEABLE;
3360 * Set this to true if the block is dockable.
3361 * @var bool
3363 public $dockable = false;
3366 * @var array A (possibly empty) array of editing controls. Each element of
3367 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
3368 * $icon is the icon name. Fed to $OUTPUT->image_url.
3370 public $controls = array();
3374 * Create new instance of block content
3375 * @param array $attributes
3377 public function __construct(array $attributes = null) {
3378 $this->skipid = self::$idcounter;
3379 self::$idcounter += 1;
3381 if ($attributes) {
3382 // standard block
3383 $this->attributes = $attributes;
3384 } else {
3385 // simple "fake" blocks used in some modules and "Add new block" block
3386 $this->attributes = array('class'=>'block');
3391 * Add html class to block
3393 * @param string $class
3395 public function add_class($class) {
3396 $this->attributes['class'] .= ' '.$class;
3400 * Check if the block is a fake block.
3402 * @return boolean
3404 public function is_fake() {
3405 return isset($this->attributes['data-block']) && $this->attributes['data-block'] == '_fake';
3411 * This class represents a target for where a block can go when it is being moved.
3413 * This needs to be rendered as a form with the given hidden from fields, and
3414 * clicking anywhere in the form should submit it. The form action should be
3415 * $PAGE->url.
3417 * @copyright 2009 Tim Hunt
3418 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3419 * @since Moodle 2.0
3420 * @package core
3421 * @category output
3423 class block_move_target {
3426 * @var moodle_url Move url
3428 public $url;
3431 * Constructor
3432 * @param moodle_url $url
3434 public function __construct(moodle_url $url) {
3435 $this->url = $url;
3440 * Custom menu item
3442 * This class is used to represent one item within a custom menu that may or may
3443 * not have children.
3445 * @copyright 2010 Sam Hemelryk
3446 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3447 * @since Moodle 2.0
3448 * @package core
3449 * @category output
3451 class custom_menu_item implements renderable, templatable {
3454 * @var string The text to show for the item
3456 protected $text;
3459 * @var moodle_url The link to give the icon if it has no children
3461 protected $url;
3464 * @var string A title to apply to the item. By default the text
3466 protected $title;
3469 * @var int A sort order for the item, not necessary if you order things in
3470 * the CFG var.
3472 protected $sort;
3475 * @var custom_menu_item A reference to the parent for this item or NULL if
3476 * it is a top level item
3478 protected $parent;
3481 * @var array A array in which to store children this item has.
3483 protected $children = array();
3486 * @var int A reference to the sort var of the last child that was added
3488 protected $lastsort = 0;
3490 /** @var array Array of other HTML attributes for the custom menu item. */
3491 protected $attributes = [];
3494 * Constructs the new custom menu item
3496 * @param string $text
3497 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
3498 * @param string $title A title to apply to this item [Optional]
3499 * @param int $sort A sort or to use if we need to sort differently [Optional]
3500 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
3501 * belongs to, only if the child has a parent. [Optional]
3502 * @param array $attributes Array of other HTML attributes for the custom menu item.
3504 public function __construct($text, moodle_url $url = null, $title = null, $sort = null, custom_menu_item $parent = null,
3505 array $attributes = []) {
3506 $this->text = $text;
3507 $this->url = $url;
3508 $this->title = $title;
3509 $this->sort = (int)$sort;
3510 $this->parent = $parent;
3511 $this->attributes = $attributes;
3515 * Adds a custom menu item as a child of this node given its properties.
3517 * @param string $text
3518 * @param moodle_url $url
3519 * @param string $title
3520 * @param int $sort
3521 * @param array $attributes Array of other HTML attributes for the custom menu item.
3522 * @return custom_menu_item
3524 public function add($text, moodle_url $url = null, $title = null, $sort = null, $attributes = []) {
3525 $key = count($this->children);
3526 if (empty($sort)) {
3527 $sort = $this->lastsort + 1;
3529 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this, $attributes);
3530 $this->lastsort = (int)$sort;
3531 return $this->children[$key];
3535 * Removes a custom menu item that is a child or descendant to the current menu.
3537 * Returns true if child was found and removed.
3539 * @param custom_menu_item $menuitem
3540 * @return bool
3542 public function remove_child(custom_menu_item $menuitem) {
3543 $removed = false;
3544 if (($key = array_search($menuitem, $this->children)) !== false) {
3545 unset($this->children[$key]);
3546 $this->children = array_values($this->children);
3547 $removed = true;
3548 } else {
3549 foreach ($this->children as $child) {
3550 if ($removed = $child->remove_child($menuitem)) {
3551 break;
3555 return $removed;
3559 * Returns the text for this item
3560 * @return string
3562 public function get_text() {
3563 return $this->text;
3567 * Returns the url for this item
3568 * @return moodle_url
3570 public function get_url() {
3571 return $this->url;
3575 * Returns the title for this item
3576 * @return string
3578 public function get_title() {
3579 return $this->title;
3583 * Sorts and returns the children for this item
3584 * @return array
3586 public function get_children() {
3587 $this->sort();
3588 return $this->children;
3592 * Gets the sort order for this child
3593 * @return int
3595 public function get_sort_order() {
3596 return $this->sort;
3600 * Gets the parent this child belong to
3601 * @return custom_menu_item
3603 public function get_parent() {
3604 return $this->parent;
3608 * Sorts the children this item has
3610 public function sort() {
3611 usort($this->children, array('custom_menu','sort_custom_menu_items'));
3615 * Returns true if this item has any children
3616 * @return bool
3618 public function has_children() {
3619 return (count($this->children) > 0);
3623 * Sets the text for the node
3624 * @param string $text
3626 public function set_text($text) {
3627 $this->text = (string)$text;
3631 * Sets the title for the node
3632 * @param string $title
3634 public function set_title($title) {
3635 $this->title = (string)$title;
3639 * Sets the url for the node
3640 * @param moodle_url $url
3642 public function set_url(moodle_url $url) {
3643 $this->url = $url;
3647 * Export this data so it can be used as the context for a mustache template.
3649 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
3650 * @return array
3652 public function export_for_template(renderer_base $output) {
3653 global $CFG;
3655 require_once($CFG->libdir . '/externallib.php');
3657 $syscontext = context_system::instance();
3659 $context = new stdClass();
3660 $context->moremenuid = uniqid();
3661 $context->text = external_format_string($this->text, $syscontext->id);
3662 $context->url = $this->url ? $this->url->out() : null;
3663 // No need for the title if it's the same with text.
3664 if ($this->text !== $this->title) {
3665 // Show the title attribute only if it's different from the text.
3666 $context->title = external_format_string($this->title, $syscontext->id);
3668 $context->sort = $this->sort;
3669 if (!empty($this->attributes)) {
3670 $context->attributes = $this->attributes;
3672 $context->children = array();
3673 if (preg_match("/^#+$/", $this->text)) {
3674 $context->divider = true;
3676 $context->haschildren = !empty($this->children) && (count($this->children) > 0);
3677 foreach ($this->children as $child) {
3678 $child = $child->export_for_template($output);
3679 array_push($context->children, $child);
3682 return $context;
3687 * Custom menu class
3689 * This class is used to operate a custom menu that can be rendered for the page.
3690 * The custom menu is built using $CFG->custommenuitems and is a structured collection
3691 * of custom_menu_item nodes that can be rendered by the core renderer.
3693 * To configure the custom menu:
3694 * Settings: Administration > Appearance > Themes > Theme settings
3696 * @copyright 2010 Sam Hemelryk
3697 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3698 * @since Moodle 2.0
3699 * @package core
3700 * @category output
3702 class custom_menu extends custom_menu_item {
3705 * @var string The language we should render for, null disables multilang support.
3707 protected $currentlanguage = null;
3710 * Creates the custom menu
3712 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
3713 * @param string $currentlanguage the current language code, null disables multilang support
3715 public function __construct($definition = '', $currentlanguage = null) {
3716 $this->currentlanguage = $currentlanguage;
3717 parent::__construct('root'); // create virtual root element of the menu
3718 if (!empty($definition)) {
3719 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
3724 * Overrides the children of this custom menu. Useful when getting children
3725 * from $CFG->custommenuitems
3727 * @param array $children
3729 public function override_children(array $children) {
3730 $this->children = array();
3731 foreach ($children as $child) {
3732 if ($child instanceof custom_menu_item) {
3733 $this->children[] = $child;
3739 * Converts a string into a structured array of custom_menu_items which can
3740 * then be added to a custom menu.
3742 * Structure:
3743 * text|url|title|langs
3744 * The number of hyphens at the start determines the depth of the item. The
3745 * languages are optional, comma separated list of languages the line is for.
3747 * Example structure:
3748 * First level first item|http://www.moodle.com/
3749 * -Second level first item|http://www.moodle.com/partners/
3750 * -Second level second item|http://www.moodle.com/hq/
3751 * --Third level first item|http://www.moodle.com/jobs/
3752 * -Second level third item|http://www.moodle.com/development/
3753 * First level second item|http://www.moodle.com/feedback/
3754 * First level third item
3755 * English only|http://moodle.com|English only item|en
3756 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
3759 * @static
3760 * @param string $text the menu items definition
3761 * @param string $language the language code, null disables multilang support
3762 * @return array
3764 public static function convert_text_to_menu_nodes($text, $language = null) {
3765 $root = new custom_menu();
3766 $lastitem = $root;
3767 $lastdepth = 0;
3768 $hiddenitems = array();
3769 $lines = explode("\n", $text);
3770 foreach ($lines as $linenumber => $line) {
3771 $line = trim($line);
3772 if (strlen($line) == 0) {
3773 continue;
3775 // Parse item settings.
3776 $itemtext = null;
3777 $itemurl = null;
3778 $itemtitle = null;
3779 $itemvisible = true;
3780 $settings = explode('|', $line);
3781 foreach ($settings as $i => $setting) {
3782 $setting = trim($setting);
3783 if (!empty($setting)) {
3784 switch ($i) {
3785 case 0: // Menu text.
3786 $itemtext = ltrim($setting, '-');
3787 break;
3788 case 1: // URL.
3789 try {
3790 $itemurl = new moodle_url($setting);
3791 } catch (moodle_exception $exception) {
3792 // We're not actually worried about this, we don't want to mess up the display
3793 // just for a wrongly entered URL.
3794 $itemurl = null;
3796 break;
3797 case 2: // Title attribute.
3798 $itemtitle = $setting;
3799 break;
3800 case 3: // Language.
3801 if (!empty($language)) {
3802 $itemlanguages = array_map('trim', explode(',', $setting));
3803 $itemvisible &= in_array($language, $itemlanguages);
3805 break;
3809 // Get depth of new item.
3810 preg_match('/^(\-*)/', $line, $match);
3811 $itemdepth = strlen($match[1]) + 1;
3812 // Find parent item for new item.
3813 while (($lastdepth - $itemdepth) >= 0) {
3814 $lastitem = $lastitem->get_parent();
3815 $lastdepth--;
3817 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1);
3818 $lastdepth++;
3819 if (!$itemvisible) {
3820 $hiddenitems[] = $lastitem;
3823 foreach ($hiddenitems as $item) {
3824 $item->parent->remove_child($item);
3826 return $root->get_children();
3830 * Sorts two custom menu items
3832 * This function is designed to be used with the usort method
3833 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
3835 * @static
3836 * @param custom_menu_item $itema
3837 * @param custom_menu_item $itemb
3838 * @return int
3840 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
3841 $itema = $itema->get_sort_order();
3842 $itemb = $itemb->get_sort_order();
3843 if ($itema == $itemb) {
3844 return 0;
3846 return ($itema > $itemb) ? +1 : -1;
3851 * Stores one tab
3853 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3854 * @package core
3856 class tabobject implements renderable, templatable {
3857 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
3858 var $id;
3859 /** @var moodle_url|string link */
3860 var $link;
3861 /** @var string text on the tab */
3862 var $text;
3863 /** @var string title under the link, by defaul equals to text */
3864 var $title;
3865 /** @var bool whether to display a link under the tab name when it's selected */
3866 var $linkedwhenselected = false;
3867 /** @var bool whether the tab is inactive */
3868 var $inactive = false;
3869 /** @var bool indicates that this tab's child is selected */
3870 var $activated = false;
3871 /** @var bool indicates that this tab is selected */
3872 var $selected = false;
3873 /** @var array stores children tabobjects */
3874 var $subtree = array();
3875 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
3876 var $level = 1;
3879 * Constructor
3881 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
3882 * @param string|moodle_url $link
3883 * @param string $text text on the tab
3884 * @param string $title title under the link, by defaul equals to text
3885 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
3887 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
3888 $this->id = $id;
3889 $this->link = $link;
3890 $this->text = $text;
3891 $this->title = $title ? $title : $text;
3892 $this->linkedwhenselected = $linkedwhenselected;
3896 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
3898 * @param string $selected the id of the selected tab (whatever row it's on),
3899 * if null marks all tabs as unselected
3900 * @return bool whether this tab is selected or contains selected tab in its subtree
3902 protected function set_selected($selected) {
3903 if ((string)$selected === (string)$this->id) {
3904 $this->selected = true;
3905 // This tab is selected. No need to travel through subtree.
3906 return true;
3908 foreach ($this->subtree as $subitem) {
3909 if ($subitem->set_selected($selected)) {
3910 // This tab has child that is selected. Mark it as activated. No need to check other children.
3911 $this->activated = true;
3912 return true;
3915 return false;
3919 * Travels through tree and finds a tab with specified id
3921 * @param string $id
3922 * @return tabtree|null
3924 public function find($id) {
3925 if ((string)$this->id === (string)$id) {
3926 return $this;
3928 foreach ($this->subtree as $tab) {
3929 if ($obj = $tab->find($id)) {
3930 return $obj;
3933 return null;
3937 * Allows to mark each tab's level in the tree before rendering.
3939 * @param int $level
3941 protected function set_level($level) {
3942 $this->level = $level;
3943 foreach ($this->subtree as $tab) {
3944 $tab->set_level($level + 1);
3949 * Export for template.
3951 * @param renderer_base $output Renderer.
3952 * @return object
3954 public function export_for_template(renderer_base $output) {
3955 if ($this->inactive || ($this->selected && !$this->linkedwhenselected) || $this->activated) {
3956 $link = null;
3957 } else {
3958 $link = $this->link;
3960 $active = $this->activated || $this->selected;
3962 return (object) [
3963 'id' => $this->id,
3964 'link' => is_object($link) ? $link->out(false) : $link,
3965 'text' => $this->text,
3966 'title' => $this->title,
3967 'inactive' => !$active && $this->inactive,
3968 'active' => $active,
3969 'level' => $this->level,
3976 * Renderable for the main page header.
3978 * @package core
3979 * @category output
3980 * @since 2.9
3981 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
3982 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3984 class context_header implements renderable {
3987 * @var string $heading Main heading.
3989 public $heading;
3991 * @var int $headinglevel Main heading 'h' tag level.
3993 public $headinglevel;
3995 * @var string|null $imagedata HTML code for the picture in the page header.
3997 public $imagedata;
3999 * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
4000 * array elements - title => alternate text for the image, or if no image is available the button text.
4001 * url => Link for the button to head to. Should be a moodle_url.
4002 * image => location to the image, or name of the image in /pix/t/{image name}.
4003 * linkattributes => additional attributes for the <a href> element.
4004 * page => page object. Don't include if the image is an external image.
4006 public $additionalbuttons;
4008 * @var string $prefix A string that is before the title.
4010 public $prefix;
4013 * Constructor.
4015 * @param string $heading Main heading data.
4016 * @param int $headinglevel Main heading 'h' tag level.
4017 * @param string|null $imagedata HTML code for the picture in the page header.
4018 * @param string $additionalbuttons Buttons for the header e.g. Messaging button for the user header.
4019 * @param string $prefix Text that precedes the heading.
4021 public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null, $prefix = null) {
4023 $this->heading = $heading;
4024 $this->headinglevel = $headinglevel;
4025 $this->imagedata = $imagedata;
4026 $this->additionalbuttons = $additionalbuttons;
4027 // If we have buttons then format them.
4028 if (isset($this->additionalbuttons)) {
4029 $this->format_button_images();
4031 $this->prefix = $prefix;
4035 * Adds an array element for a formatted image.
4037 protected function format_button_images() {
4039 foreach ($this->additionalbuttons as $buttontype => $button) {
4040 $page = $button['page'];
4041 // If no image is provided then just use the title.
4042 if (!isset($button['image'])) {
4043 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['title'];
4044 } else {
4045 // Check to see if this is an internal Moodle icon.
4046 $internalimage = $page->theme->resolve_image_location('t/' . $button['image'], 'moodle');
4047 if ($internalimage) {
4048 $this->additionalbuttons[$buttontype]['formattedimage'] = 't/' . $button['image'];
4049 } else {
4050 // Treat as an external image.
4051 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['image'];
4055 if (isset($button['linkattributes']['class'])) {
4056 $class = $button['linkattributes']['class'] . ' btn';
4057 } else {
4058 $class = 'btn';
4060 // Add the bootstrap 'btn' class for formatting.
4061 $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
4062 array('class' => $class));
4068 * Stores tabs list
4070 * Example how to print a single line tabs:
4071 * $rows = array(
4072 * new tabobject(...),
4073 * new tabobject(...)
4074 * );
4075 * echo $OUTPUT->tabtree($rows, $selectedid);
4077 * Multiple row tabs may not look good on some devices but if you want to use them
4078 * you can specify ->subtree for the active tabobject.
4080 * @copyright 2013 Marina Glancy
4081 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4082 * @since Moodle 2.5
4083 * @package core
4084 * @category output
4086 class tabtree extends tabobject {
4088 * Constuctor
4090 * It is highly recommended to call constructor when list of tabs is already
4091 * populated, this way you ensure that selected and inactive tabs are located
4092 * and attribute level is set correctly.
4094 * @param array $tabs array of tabs, each of them may have it's own ->subtree
4095 * @param string|null $selected which tab to mark as selected, all parent tabs will
4096 * automatically be marked as activated
4097 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4098 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
4100 public function __construct($tabs, $selected = null, $inactive = null) {
4101 $this->subtree = $tabs;
4102 if ($selected !== null) {
4103 $this->set_selected($selected);
4105 if ($inactive !== null) {
4106 if (is_array($inactive)) {
4107 foreach ($inactive as $id) {
4108 if ($tab = $this->find($id)) {
4109 $tab->inactive = true;
4112 } else if ($tab = $this->find($inactive)) {
4113 $tab->inactive = true;
4116 $this->set_level(0);
4120 * Export for template.
4122 * @param renderer_base $output Renderer.
4123 * @return object
4125 public function export_for_template(renderer_base $output) {
4126 $tabs = [];
4127 $secondrow = false;
4129 foreach ($this->subtree as $tab) {
4130 $tabs[] = $tab->export_for_template($output);
4131 if (!empty($tab->subtree) && ($tab->level == 0 || $tab->selected || $tab->activated)) {
4132 $secondrow = new tabtree($tab->subtree);
4136 return (object) [
4137 'tabs' => $tabs,
4138 'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false
4144 * An action menu.
4146 * This action menu component takes a series of primary and secondary actions.
4147 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
4148 * down menu.
4150 * @package core
4151 * @category output
4152 * @copyright 2013 Sam Hemelryk
4153 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4155 class action_menu implements renderable, templatable {
4158 * Top right alignment.
4160 const TL = 1;
4163 * Top right alignment.
4165 const TR = 2;
4168 * Top right alignment.
4170 const BL = 3;
4173 * Top right alignment.
4175 const BR = 4;
4178 * The instance number. This is unique to this instance of the action menu.
4179 * @var int
4181 protected $instance = 0;
4184 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
4185 * @var array
4187 protected $primaryactions = array();
4190 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
4191 * @var array
4193 protected $secondaryactions = array();
4196 * An array of attributes added to the container of the action menu.
4197 * Initialised with defaults during construction.
4198 * @var array
4200 public $attributes = array();
4202 * An array of attributes added to the container of the primary actions.
4203 * Initialised with defaults during construction.
4204 * @var array
4206 public $attributesprimary = array();
4208 * An array of attributes added to the container of the secondary actions.
4209 * Initialised with defaults during construction.
4210 * @var array
4212 public $attributessecondary = array();
4215 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
4216 * @var array
4218 public $actiontext = null;
4221 * The string to use for the accessible label for the menu.
4222 * @var array
4224 public $actionlabel = null;
4227 * An icon to use for the toggling the secondary menu (dropdown).
4228 * @var pix_icon
4230 public $actionicon;
4233 * Any text to use for the toggling the secondary menu (dropdown).
4234 * @var string
4236 public $menutrigger = '';
4239 * Any extra classes for toggling to the secondary menu.
4240 * @var string
4242 public $triggerextraclasses = '';
4245 * Place the action menu before all other actions.
4246 * @var bool
4248 public $prioritise = false;
4251 * Dropdown menu alignment class.
4252 * @var string
4254 public $dropdownalignment = '';
4257 * Constructs the action menu with the given items.
4259 * @param array $actions An array of actions (action_menu_link|pix_icon|string).
4261 public function __construct(array $actions = array()) {
4262 static $initialised = 0;
4263 $this->instance = $initialised;
4264 $initialised++;
4266 $this->attributes = array(
4267 'id' => 'action-menu-'.$this->instance,
4268 'class' => 'moodle-actionmenu',
4269 'data-enhance' => 'moodle-core-actionmenu'
4271 $this->attributesprimary = array(
4272 'id' => 'action-menu-'.$this->instance.'-menubar',
4273 'class' => 'menubar',
4275 $this->attributessecondary = array(
4276 'id' => 'action-menu-'.$this->instance.'-menu',
4277 'class' => 'menu',
4278 'data-rel' => 'menu-content',
4279 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
4280 'role' => 'menu'
4282 $this->dropdownalignment = 'dropdown-menu-right';
4283 foreach ($actions as $action) {
4284 $this->add($action);
4289 * Sets the label for the menu trigger.
4291 * @param string $label The text
4293 public function set_action_label($label) {
4294 $this->actionlabel = $label;
4298 * Sets the menu trigger text.
4300 * @param string $trigger The text
4301 * @param string $extraclasses Extra classes to style the secondary menu toggle.
4303 public function set_menu_trigger($trigger, $extraclasses = '') {
4304 $this->menutrigger = $trigger;
4305 $this->triggerextraclasses = $extraclasses;
4309 * Return true if there is at least one visible link in the menu.
4311 * @return bool
4313 public function is_empty() {
4314 return !count($this->primaryactions) && !count($this->secondaryactions);
4318 * Initialises JS required fore the action menu.
4319 * The JS is only required once as it manages all action menu's on the page.
4321 * @param moodle_page $page
4323 public function initialise_js(moodle_page $page) {
4324 static $initialised = false;
4325 if (!$initialised) {
4326 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
4327 $initialised = true;
4332 * Adds an action to this action menu.
4334 * @param action_menu_link|pix_icon|string $action
4336 public function add($action) {
4337 if ($action instanceof action_link) {
4338 if ($action->primary) {
4339 $this->add_primary_action($action);
4340 } else {
4341 $this->add_secondary_action($action);
4343 } else if ($action instanceof pix_icon) {
4344 $this->add_primary_action($action);
4345 } else {
4346 $this->add_secondary_action($action);
4351 * Adds a primary action to the action menu.
4353 * @param action_menu_link|action_link|pix_icon|string $action
4355 public function add_primary_action($action) {
4356 if ($action instanceof action_link || $action instanceof pix_icon) {
4357 $action->attributes['role'] = 'menuitem';
4358 $action->attributes['tabindex'] = '-1';
4359 if ($action instanceof action_menu_link) {
4360 $action->actionmenu = $this;
4363 $this->primaryactions[] = $action;
4367 * Adds a secondary action to the action menu.
4369 * @param action_link|pix_icon|string $action
4371 public function add_secondary_action($action) {
4372 if ($action instanceof action_link || $action instanceof pix_icon) {
4373 $action->attributes['role'] = 'menuitem';
4374 $action->attributes['tabindex'] = '-1';
4375 if ($action instanceof action_menu_link) {
4376 $action->actionmenu = $this;
4379 $this->secondaryactions[] = $action;
4383 * Returns the primary actions ready to be rendered.
4385 * @param core_renderer $output The renderer to use for getting icons.
4386 * @return array
4388 public function get_primary_actions(core_renderer $output = null) {
4389 global $OUTPUT;
4390 if ($output === null) {
4391 $output = $OUTPUT;
4393 $pixicon = $this->actionicon;
4394 $linkclasses = array('toggle-display');
4396 $title = '';
4397 if (!empty($this->menutrigger)) {
4398 $pixicon = '<b class="caret"></b>';
4399 $linkclasses[] = 'textmenu';
4400 } else {
4401 $title = new lang_string('actionsmenu', 'moodle');
4402 $this->actionicon = new pix_icon(
4403 't/edit_menu',
4405 'moodle',
4406 array('class' => 'iconsmall actionmenu', 'title' => '')
4408 $pixicon = $this->actionicon;
4410 if ($pixicon instanceof renderable) {
4411 $pixicon = $output->render($pixicon);
4412 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
4413 $title = $pixicon->attributes['alt'];
4416 $string = '';
4417 if ($this->actiontext) {
4418 $string = $this->actiontext;
4420 $label = '';
4421 if ($this->actionlabel) {
4422 $label = $this->actionlabel;
4423 } else {
4424 $label = $title;
4426 $actions = $this->primaryactions;
4427 $attributes = array(
4428 'class' => implode(' ', $linkclasses),
4429 'title' => $title,
4430 'aria-label' => $label,
4431 'id' => 'action-menu-toggle-'.$this->instance,
4432 'role' => 'menuitem',
4433 'tabindex' => '-1',
4435 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
4436 if ($this->prioritise) {
4437 array_unshift($actions, $link);
4438 } else {
4439 $actions[] = $link;
4441 return $actions;
4445 * Returns the secondary actions ready to be rendered.
4446 * @return array
4448 public function get_secondary_actions() {
4449 return $this->secondaryactions;
4453 * Sets the selector that should be used to find the owning node of this menu.
4454 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
4456 public function set_owner_selector($selector) {
4457 $this->attributes['data-owner'] = $selector;
4461 * Sets the alignment of the dialogue in relation to button used to toggle it.
4463 * @deprecated since Moodle 4.0
4465 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4466 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4468 public function set_alignment($dialogue, $button) {
4469 debugging('The method action_menu::set_alignment() is deprecated, use action_menu::set_menu_left()', DEBUG_DEVELOPER);
4470 if (isset($this->attributessecondary['data-align'])) {
4471 // We've already got one set, lets remove the old class so as to avoid troubles.
4472 $class = $this->attributessecondary['class'];
4473 $search = 'align-'.$this->attributessecondary['data-align'];
4474 $this->attributessecondary['class'] = str_replace($search, '', $class);
4476 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
4477 $this->attributessecondary['data-align'] = $align;
4478 $this->attributessecondary['class'] .= ' align-'.$align;
4482 * Returns a string to describe the alignment.
4484 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4485 * @return string
4487 protected function get_align_string($align) {
4488 switch ($align) {
4489 case self::TL :
4490 return 'tl';
4491 case self::TR :
4492 return 'tr';
4493 case self::BL :
4494 return 'bl';
4495 case self::BR :
4496 return 'br';
4497 default :
4498 return 'tl';
4503 * Aligns the left corner of the dropdown.
4506 public function set_menu_left() {
4507 $this->dropdownalignment = 'dropdown-menu-left';
4511 * Sets a constraint for the dialogue.
4513 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
4514 * element the constraint identifies.
4516 * This is required whenever the action menu is displayed inside any CSS element with the .no-overflow class
4517 * (flexible_table and any of it's child classes are a likely candidate).
4519 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
4521 public function set_constraint($ancestorselector) {
4522 $this->attributessecondary['data-constraint'] = $ancestorselector;
4526 * If you call this method the action menu will be displayed but will not be enhanced.
4528 * By not displaying the menu enhanced all items will be displayed in a single row.
4530 * @deprecated since Moodle 3.2
4532 public function do_not_enhance() {
4533 debugging('The method action_menu::do_not_enhance() is deprecated, use a list of action_icon instead.', DEBUG_DEVELOPER);
4537 * Returns true if this action menu will be enhanced.
4539 * @return bool
4541 public function will_be_enhanced() {
4542 return isset($this->attributes['data-enhance']);
4546 * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
4548 * This property can be useful when the action menu is displayed within a parent element that is either floated
4549 * or relatively positioned.
4550 * In that situation the width of the menu is determined by the width of the parent element which may not be large
4551 * enough for the menu items without them wrapping.
4552 * This disables the wrapping so that the menu takes on the width of the longest item.
4554 * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
4556 public function set_nowrap_on_items($value = true) {
4557 $class = 'nowrap-items';
4558 if (!empty($this->attributes['class'])) {
4559 $pos = strpos($this->attributes['class'], $class);
4560 if ($value === true && $pos === false) {
4561 // The value is true and the class has not been set yet. Add it.
4562 $this->attributes['class'] .= ' '.$class;
4563 } else if ($value === false && $pos !== false) {
4564 // The value is false and the class has been set. Remove it.
4565 $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class));
4567 } else if ($value) {
4568 // The value is true and the class has not been set yet. Add it.
4569 $this->attributes['class'] = $class;
4574 * Export for template.
4576 * @param renderer_base $output The renderer.
4577 * @return stdClass
4579 public function export_for_template(renderer_base $output) {
4580 $data = new stdClass();
4581 // Assign a role of menubar to this action menu when:
4582 // - it contains 2 or more primary actions; or
4583 // - if it contains a primary action and secondary actions.
4584 if (count($this->primaryactions) > 1 || (!empty($this->primaryactions) && !empty($this->secondaryactions))) {
4585 $this->attributes['role'] = 'menubar';
4587 $attributes = $this->attributes;
4588 $attributesprimary = $this->attributesprimary;
4589 $attributessecondary = $this->attributessecondary;
4591 $data->instance = $this->instance;
4593 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
4594 unset($attributes['class']);
4596 $data->attributes = array_map(function($key, $value) {
4597 return [ 'name' => $key, 'value' => $value ];
4598 }, array_keys($attributes), $attributes);
4600 $primary = new stdClass();
4601 $primary->title = '';
4602 $primary->prioritise = $this->prioritise;
4604 $primary->classes = isset($attributesprimary['class']) ? $attributesprimary['class'] : '';
4605 unset($attributesprimary['class']);
4606 $primary->attributes = array_map(function($key, $value) {
4607 return [ 'name' => $key, 'value' => $value ];
4608 }, array_keys($attributesprimary), $attributesprimary);
4610 $actionicon = $this->actionicon;
4611 if (!empty($this->menutrigger)) {
4612 $primary->menutrigger = $this->menutrigger;
4613 $primary->triggerextraclasses = $this->triggerextraclasses;
4614 if ($this->actionlabel) {
4615 $primary->title = $this->actionlabel;
4616 } else if ($this->actiontext) {
4617 $primary->title = $this->actiontext;
4618 } else {
4619 $primary->title = strip_tags($this->menutrigger);
4621 } else {
4622 $primary->title = get_string('actionsmenu');
4623 $iconattributes = ['class' => 'iconsmall actionmenu', 'title' => $primary->title];
4624 $actionicon = new pix_icon('t/edit_menu', '', 'moodle', $iconattributes);
4627 // If the menu trigger is within the menubar, assign a role of menuitem. Otherwise, assign as a button.
4628 $primary->triggerrole = 'button';
4629 if (isset($attributes['role']) && $attributes['role'] === 'menubar') {
4630 $primary->triggerrole = 'menuitem';
4633 if ($actionicon instanceof pix_icon) {
4634 $primary->icon = $actionicon->export_for_pix();
4635 if (!empty($actionicon->attributes['alt'])) {
4636 $primary->title = $actionicon->attributes['alt'];
4638 } else {
4639 $primary->iconraw = $actionicon ? $output->render($actionicon) : '';
4642 $primary->actiontext = $this->actiontext ? (string) $this->actiontext : '';
4643 $primary->items = array_map(function($item) use ($output) {
4644 $data = (object) [];
4645 if ($item instanceof action_menu_link) {
4646 $data->actionmenulink = $item->export_for_template($output);
4647 } else if ($item instanceof action_menu_filler) {
4648 $data->actionmenufiller = $item->export_for_template($output);
4649 } else if ($item instanceof action_link) {
4650 $data->actionlink = $item->export_for_template($output);
4651 } else if ($item instanceof pix_icon) {
4652 $data->pixicon = $item->export_for_template($output);
4653 } else {
4654 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4656 return $data;
4657 }, $this->primaryactions);
4659 $secondary = new stdClass();
4660 $secondary->classes = isset($attributessecondary['class']) ? $attributessecondary['class'] : '';
4661 unset($attributessecondary['class']);
4662 $secondary->attributes = array_map(function($key, $value) {
4663 return [ 'name' => $key, 'value' => $value ];
4664 }, array_keys($attributessecondary), $attributessecondary);
4665 $secondary->items = array_map(function($item) use ($output) {
4666 $data = (object) [];
4667 if ($item instanceof action_menu_link) {
4668 $data->actionmenulink = $item->export_for_template($output);
4669 } else if ($item instanceof action_menu_filler) {
4670 $data->actionmenufiller = $item->export_for_template($output);
4671 } else if ($item instanceof action_link) {
4672 $data->actionlink = $item->export_for_template($output);
4673 } else if ($item instanceof pix_icon) {
4674 $data->pixicon = $item->export_for_template($output);
4675 } else {
4676 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4678 return $data;
4679 }, $this->secondaryactions);
4681 $data->primary = $primary;
4682 $data->secondary = $secondary;
4683 $data->dropdownalignment = $this->dropdownalignment;
4685 return $data;
4691 * An action menu filler
4693 * @package core
4694 * @category output
4695 * @copyright 2013 Andrew Nicols
4696 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4698 class action_menu_filler extends action_link implements renderable {
4701 * True if this is a primary action. False if not.
4702 * @var bool
4704 public $primary = true;
4707 * Constructs the object.
4709 public function __construct() {
4710 $this->attributes['id'] = html_writer::random_id('action_link');
4715 * An action menu action
4717 * @package core
4718 * @category output
4719 * @copyright 2013 Sam Hemelryk
4720 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4722 class action_menu_link extends action_link implements renderable {
4725 * True if this is a primary action. False if not.
4726 * @var bool
4728 public $primary = true;
4731 * The action menu this link has been added to.
4732 * @var action_menu
4734 public $actionmenu = null;
4737 * The number of instances of this action menu link (and its subclasses).
4738 * @var int
4740 protected static $instance = 1;
4743 * Constructs the object.
4745 * @param moodle_url $url The URL for the action.
4746 * @param pix_icon|null $icon The icon to represent the action.
4747 * @param string $text The text to represent the action.
4748 * @param bool $primary Whether this is a primary action or not.
4749 * @param array $attributes Any attribtues associated with the action.
4751 public function __construct(moodle_url $url, ?pix_icon $icon, $text, $primary = true, array $attributes = array()) {
4752 parent::__construct($url, $text, null, $attributes, $icon);
4753 $this->primary = (bool)$primary;
4754 $this->add_class('menu-action');
4755 $this->attributes['role'] = 'menuitem';
4759 * Export for template.
4761 * @param renderer_base $output The renderer.
4762 * @return stdClass
4764 public function export_for_template(renderer_base $output) {
4765 $data = parent::export_for_template($output);
4766 $data->instance = self::$instance++;
4768 // Ignore what the parent did with the attributes, except for ID and class.
4769 $data->attributes = [];
4770 $attributes = $this->attributes;
4771 unset($attributes['id']);
4772 unset($attributes['class']);
4774 // Handle text being a renderable.
4775 if ($this->text instanceof renderable) {
4776 $data->text = $this->render($this->text);
4779 $data->showtext = (!$this->icon || $this->primary === false);
4781 $data->icon = null;
4782 if ($this->icon) {
4783 $icon = $this->icon;
4784 if ($this->primary || !$this->actionmenu->will_be_enhanced()) {
4785 $attributes['title'] = $data->text;
4787 $data->icon = $icon ? $icon->export_for_pix() : null;
4790 $data->disabled = !empty($attributes['disabled']);
4791 unset($attributes['disabled']);
4793 $data->attributes = array_map(function($key, $value) {
4794 return [
4795 'name' => $key,
4796 'value' => $value
4798 }, array_keys($attributes), $attributes);
4800 return $data;
4805 * A primary action menu action
4807 * @package core
4808 * @category output
4809 * @copyright 2013 Sam Hemelryk
4810 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4812 class action_menu_link_primary extends action_menu_link {
4814 * Constructs the object.
4816 * @param moodle_url $url
4817 * @param pix_icon|null $icon
4818 * @param string $text
4819 * @param array $attributes
4821 public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) {
4822 parent::__construct($url, $icon, $text, true, $attributes);
4827 * A secondary action menu action
4829 * @package core
4830 * @category output
4831 * @copyright 2013 Sam Hemelryk
4832 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4834 class action_menu_link_secondary extends action_menu_link {
4836 * Constructs the object.
4838 * @param moodle_url $url
4839 * @param pix_icon|null $icon
4840 * @param string $text
4841 * @param array $attributes
4843 public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) {
4844 parent::__construct($url, $icon, $text, false, $attributes);
4849 * Represents a set of preferences groups.
4851 * @package core
4852 * @category output
4853 * @copyright 2015 Frédéric Massart - FMCorz.net
4854 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4856 class preferences_groups implements renderable {
4859 * Array of preferences_group.
4860 * @var array
4862 public $groups;
4865 * Constructor.
4866 * @param array $groups of preferences_group
4868 public function __construct($groups) {
4869 $this->groups = $groups;
4875 * Represents a group of preferences page link.
4877 * @package core
4878 * @category output
4879 * @copyright 2015 Frédéric Massart - FMCorz.net
4880 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4882 class preferences_group implements renderable {
4885 * Title of the group.
4886 * @var string
4888 public $title;
4891 * Array of navigation_node.
4892 * @var array
4894 public $nodes;
4897 * Constructor.
4898 * @param string $title The title.
4899 * @param array $nodes of navigation_node.
4901 public function __construct($title, $nodes) {
4902 $this->title = $title;
4903 $this->nodes = $nodes;
4908 * Progress bar class.
4910 * Manages the display of a progress bar.
4912 * To use this class.
4913 * - construct
4914 * - call create (or use the 3rd param to the constructor)
4915 * - call update or update_full() or update() repeatedly
4917 * @copyright 2008 jamiesensei
4918 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4919 * @package core
4920 * @category output
4922 class progress_bar implements renderable, templatable {
4923 /** @var string html id */
4924 private $html_id;
4925 /** @var int total width */
4926 private $width;
4927 /** @var int last percentage printed */
4928 private $percent = 0;
4929 /** @var int time when last printed */
4930 private $lastupdate = 0;
4931 /** @var int when did we start printing this */
4932 private $time_start = 0;
4935 * Constructor
4937 * Prints JS code if $autostart true.
4939 * @param string $htmlid The container ID.
4940 * @param int $width The suggested width.
4941 * @param bool $autostart Whether to start the progress bar right away.
4943 public function __construct($htmlid = '', $width = 500, $autostart = false) {
4944 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
4945 debugging('progress_bar used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', DEBUG_DEVELOPER);
4948 if (!empty($htmlid)) {
4949 $this->html_id = $htmlid;
4950 } else {
4951 $this->html_id = 'pbar_'.uniqid();
4954 $this->width = $width;
4956 if ($autostart) {
4957 $this->create();
4962 * Getter for ID
4963 * @return string id
4965 public function get_id() : string {
4966 return $this->html_id;
4970 * Create a new progress bar, this function will output html.
4972 * @return void Echo's output
4974 public function create() {
4975 global $OUTPUT;
4977 $this->time_start = microtime(true);
4979 flush();
4980 echo $OUTPUT->render($this);
4981 flush();
4985 * Update the progress bar.
4987 * @param int $percent From 1-100.
4988 * @param string $msg The message.
4989 * @return void Echo's output
4990 * @throws coding_exception
4992 private function _update($percent, $msg) {
4993 global $OUTPUT;
4995 if (empty($this->time_start)) {
4996 throw new coding_exception('You must call create() (or use the $autostart ' .
4997 'argument to the constructor) before you try updating the progress bar.');
5000 $estimate = $this->estimate($percent);
5002 if ($estimate === null) {
5003 // Always do the first and last updates.
5004 } else if ($estimate == 0) {
5005 // Always do the last updates.
5006 } else if ($this->lastupdate + 20 < time()) {
5007 // We must update otherwise browser would time out.
5008 } else if (round($this->percent, 2) === round($percent, 2)) {
5009 // No significant change, no need to update anything.
5010 return;
5013 $estimatemsg = '';
5014 if ($estimate != 0 && is_numeric($estimate)) {
5015 $estimatemsg = format_time(round($estimate));
5018 $this->percent = $percent;
5019 $this->lastupdate = microtime(true);
5021 echo $OUTPUT->render_progress_bar_update($this->html_id, sprintf("%.1f", $this->percent), $msg, $estimatemsg);
5022 flush();
5026 * Estimate how much time it is going to take.
5028 * @param int $pt From 1-100.
5029 * @return mixed Null (unknown), or int.
5031 private function estimate($pt) {
5032 if ($this->lastupdate == 0) {
5033 return null;
5035 if ($pt < 0.00001) {
5036 return null; // We do not know yet how long it will take.
5038 if ($pt > 99.99999) {
5039 return 0; // Nearly done, right?
5041 $consumed = microtime(true) - $this->time_start;
5042 if ($consumed < 0.001) {
5043 return null;
5046 return (100 - $pt) * ($consumed / $pt);
5050 * Update progress bar according percent.
5052 * @param int $percent From 1-100.
5053 * @param string $msg The message needed to be shown.
5055 public function update_full($percent, $msg) {
5056 $percent = max(min($percent, 100), 0);
5057 $this->_update($percent, $msg);
5061 * Update progress bar according the number of tasks.
5063 * @param int $cur Current task number.
5064 * @param int $total Total task number.
5065 * @param string $msg The message needed to be shown.
5067 public function update($cur, $total, $msg) {
5068 $percent = ($cur / $total) * 100;
5069 $this->update_full($percent, $msg);
5073 * Restart the progress bar.
5075 public function restart() {
5076 $this->percent = 0;
5077 $this->lastupdate = 0;
5078 $this->time_start = 0;
5082 * Export for template.
5084 * @param renderer_base $output The renderer.
5085 * @return array
5087 public function export_for_template(renderer_base $output) {
5088 return [
5089 'id' => $this->html_id,
5090 'width' => $this->width,