Moodle release 4.0.8
[moodle.git] / lib / outputcomponents.php
blob02f6cbe13fa9b9925fa07b4e92f29f1f1b4ce541
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 $actionurl = new moodle_url($this->url, ['sesskey' => sesskey()]);
925 $data->params = $actionurl->export_params_for_template();
927 // Button actions.
928 $actions = $this->actions;
929 $data->actions = array_map(function($action) use ($output) {
930 return $action->export_for_template($output);
931 }, $actions);
932 $data->hasactions = !empty($data->actions);
934 return $data;
940 * Simple form with just one select field that gets submitted automatically.
942 * If JS not enabled small go button is printed too.
944 * @copyright 2009 Petr Skoda
945 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
946 * @since Moodle 2.0
947 * @package core
948 * @category output
950 class single_select implements renderable, templatable {
953 * @var moodle_url Target url - includes hidden fields
955 var $url;
958 * @var string Name of the select element.
960 var $name;
963 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
964 * it is also possible to specify optgroup as complex label array ex.:
965 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
966 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
968 var $options;
971 * @var string Selected option
973 var $selected;
976 * @var array Nothing selected
978 var $nothing;
981 * @var array Extra select field attributes
983 var $attributes = array();
986 * @var string Button label
988 var $label = '';
991 * @var array Button label's attributes
993 var $labelattributes = array();
996 * @var string Form submit method post or get
998 var $method = 'get';
1001 * @var string Wrapping div class
1003 var $class = 'singleselect';
1006 * @var bool True if button disabled, false if normal
1008 var $disabled = false;
1011 * @var string Button tooltip
1013 var $tooltip = null;
1016 * @var string Form id
1018 var $formid = null;
1021 * @var help_icon The help icon for this element.
1023 var $helpicon = null;
1026 * Constructor
1027 * @param moodle_url $url form action target, includes hidden fields
1028 * @param string $name name of selection field - the changing parameter in url
1029 * @param array $options list of options
1030 * @param string $selected selected element
1031 * @param array $nothing
1032 * @param string $formid
1034 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1035 $this->url = $url;
1036 $this->name = $name;
1037 $this->options = $options;
1038 $this->selected = $selected;
1039 $this->nothing = $nothing;
1040 $this->formid = $formid;
1044 * Shortcut for adding a JS confirm dialog when the button is clicked.
1045 * The message must be a yes/no question.
1047 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
1049 public function add_confirm_action($confirmmessage) {
1050 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
1054 * Add action to the button.
1056 * @param component_action $action
1058 public function add_action(component_action $action) {
1059 $this->actions[] = $action;
1063 * Adds help icon.
1065 * @deprecated since Moodle 2.0
1067 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1068 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1072 * Adds help icon.
1074 * @param string $identifier The keyword that defines a help page
1075 * @param string $component
1077 public function set_help_icon($identifier, $component = 'moodle') {
1078 $this->helpicon = new help_icon($identifier, $component);
1082 * Sets select's label
1084 * @param string $label
1085 * @param array $attributes (optional)
1087 public function set_label($label, $attributes = array()) {
1088 $this->label = $label;
1089 $this->labelattributes = $attributes;
1094 * Export data.
1096 * @param renderer_base $output Renderer.
1097 * @return stdClass
1099 public function export_for_template(renderer_base $output) {
1100 $attributes = $this->attributes;
1102 $data = new stdClass();
1103 $data->name = $this->name;
1104 $data->method = $this->method;
1105 $data->action = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
1106 $data->classes = $this->class;
1107 $data->label = $this->label;
1108 $data->disabled = $this->disabled;
1109 $data->title = $this->tooltip;
1110 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('single_select_f');
1111 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('single_select');
1113 // Select element attributes.
1114 // Unset attributes that are already predefined in the template.
1115 unset($attributes['id']);
1116 unset($attributes['class']);
1117 unset($attributes['name']);
1118 unset($attributes['title']);
1119 unset($attributes['disabled']);
1121 // Map the attributes.
1122 $data->attributes = array_map(function($key) use ($attributes) {
1123 return ['name' => $key, 'value' => $attributes[$key]];
1124 }, array_keys($attributes));
1126 // Form parameters.
1127 $actionurl = new moodle_url($this->url, ['sesskey' => sesskey()]);
1128 $data->params = $actionurl->export_params_for_template();
1130 // Select options.
1131 $hasnothing = false;
1132 if (is_string($this->nothing) && $this->nothing !== '') {
1133 $nothing = ['' => $this->nothing];
1134 $hasnothing = true;
1135 $nothingkey = '';
1136 } else if (is_array($this->nothing)) {
1137 $nothingvalue = reset($this->nothing);
1138 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1139 $nothing = [key($this->nothing) => get_string('choosedots')];
1140 } else {
1141 $nothing = $this->nothing;
1143 $hasnothing = true;
1144 $nothingkey = key($this->nothing);
1146 if ($hasnothing) {
1147 $options = $nothing + $this->options;
1148 } else {
1149 $options = $this->options;
1152 foreach ($options as $value => $name) {
1153 if (is_array($options[$value])) {
1154 foreach ($options[$value] as $optgroupname => $optgroupvalues) {
1155 $sublist = [];
1156 foreach ($optgroupvalues as $optvalue => $optname) {
1157 $option = [
1158 'value' => $optvalue,
1159 'name' => $optname,
1160 'selected' => strval($this->selected) === strval($optvalue),
1163 if ($hasnothing && $nothingkey === $optvalue) {
1164 $option['ignore'] = 'data-ignore';
1167 $sublist[] = $option;
1169 $data->options[] = [
1170 'name' => $optgroupname,
1171 'optgroup' => true,
1172 'options' => $sublist
1175 } else {
1176 $option = [
1177 'value' => $value,
1178 'name' => $options[$value],
1179 'selected' => strval($this->selected) === strval($value),
1180 'optgroup' => false
1183 if ($hasnothing && $nothingkey === $value) {
1184 $option['ignore'] = 'data-ignore';
1187 $data->options[] = $option;
1191 // Label attributes.
1192 $data->labelattributes = [];
1193 // Unset label attributes that are already in the template.
1194 unset($this->labelattributes['for']);
1195 // Map the label attributes.
1196 foreach ($this->labelattributes as $key => $value) {
1197 $data->labelattributes[] = ['name' => $key, 'value' => $value];
1200 // Help icon.
1201 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1203 return $data;
1208 * Simple URL selection widget description.
1210 * @copyright 2009 Petr Skoda
1211 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1212 * @since Moodle 2.0
1213 * @package core
1214 * @category output
1216 class url_select implements renderable, templatable {
1218 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
1219 * it is also possible to specify optgroup as complex label array ex.:
1220 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1221 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1223 var $urls;
1226 * @var string Selected option
1228 var $selected;
1231 * @var array Nothing selected
1233 var $nothing;
1236 * @var array Extra select field attributes
1238 var $attributes = array();
1241 * @var string Button label
1243 var $label = '';
1246 * @var array Button label's attributes
1248 var $labelattributes = array();
1251 * @var string Wrapping div class
1253 var $class = 'urlselect';
1256 * @var bool True if button disabled, false if normal
1258 var $disabled = false;
1261 * @var string Button tooltip
1263 var $tooltip = null;
1266 * @var string Form id
1268 var $formid = null;
1271 * @var help_icon The help icon for this element.
1273 var $helpicon = null;
1276 * @var string If set, makes button visible with given name for button
1278 var $showbutton = null;
1281 * Constructor
1282 * @param array $urls list of options
1283 * @param string $selected selected element
1284 * @param array $nothing
1285 * @param string $formid
1286 * @param string $showbutton Set to text of button if it should be visible
1287 * or null if it should be hidden (hidden version always has text 'go')
1289 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
1290 $this->urls = $urls;
1291 $this->selected = $selected;
1292 $this->nothing = $nothing;
1293 $this->formid = $formid;
1294 $this->showbutton = $showbutton;
1298 * Adds help icon.
1300 * @deprecated since Moodle 2.0
1302 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1303 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1307 * Adds help icon.
1309 * @param string $identifier The keyword that defines a help page
1310 * @param string $component
1312 public function set_help_icon($identifier, $component = 'moodle') {
1313 $this->helpicon = new help_icon($identifier, $component);
1317 * Sets select's label
1319 * @param string $label
1320 * @param array $attributes (optional)
1322 public function set_label($label, $attributes = array()) {
1323 $this->label = $label;
1324 $this->labelattributes = $attributes;
1328 * Clean a URL.
1330 * @param string $value The URL.
1331 * @return The cleaned URL.
1333 protected function clean_url($value) {
1334 global $CFG;
1336 if (empty($value)) {
1337 // Nothing.
1339 } else if (strpos($value, $CFG->wwwroot . '/') === 0) {
1340 $value = str_replace($CFG->wwwroot, '', $value);
1342 } else if (strpos($value, '/') !== 0) {
1343 debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER);
1346 return $value;
1350 * Flatten the options for Mustache.
1352 * This also cleans the URLs.
1354 * @param array $options The options.
1355 * @param array $nothing The nothing option.
1356 * @return array
1358 protected function flatten_options($options, $nothing) {
1359 $flattened = [];
1361 foreach ($options as $value => $option) {
1362 if (is_array($option)) {
1363 foreach ($option as $groupname => $optoptions) {
1364 if (!isset($flattened[$groupname])) {
1365 $flattened[$groupname] = [
1366 'name' => $groupname,
1367 'isgroup' => true,
1368 'options' => []
1371 foreach ($optoptions as $optvalue => $optoption) {
1372 $cleanedvalue = $this->clean_url($optvalue);
1373 $flattened[$groupname]['options'][$cleanedvalue] = [
1374 'name' => $optoption,
1375 'value' => $cleanedvalue,
1376 'selected' => $this->selected == $optvalue,
1381 } else {
1382 $cleanedvalue = $this->clean_url($value);
1383 $flattened[$cleanedvalue] = [
1384 'name' => $option,
1385 'value' => $cleanedvalue,
1386 'selected' => $this->selected == $value,
1391 if (!empty($nothing)) {
1392 $value = key($nothing);
1393 $name = reset($nothing);
1394 $flattened = [
1395 $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value]
1396 ] + $flattened;
1399 // Make non-associative array.
1400 foreach ($flattened as $key => $value) {
1401 if (!empty($value['options'])) {
1402 $flattened[$key]['options'] = array_values($value['options']);
1405 $flattened = array_values($flattened);
1407 return $flattened;
1411 * Export for template.
1413 * @param renderer_base $output Renderer.
1414 * @return stdClass
1416 public function export_for_template(renderer_base $output) {
1417 $attributes = $this->attributes;
1419 $data = new stdClass();
1420 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('url_select_f');
1421 $data->classes = $this->class;
1422 $data->label = $this->label;
1423 $data->disabled = $this->disabled;
1424 $data->title = $this->tooltip;
1425 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('url_select');
1426 $data->sesskey = sesskey();
1427 $data->action = (new moodle_url('/course/jumpto.php'))->out(false);
1429 // Remove attributes passed as property directly.
1430 unset($attributes['class']);
1431 unset($attributes['id']);
1432 unset($attributes['name']);
1433 unset($attributes['title']);
1434 unset($attributes['disabled']);
1436 $data->showbutton = $this->showbutton;
1438 // Select options.
1439 $nothing = false;
1440 if (is_string($this->nothing) && $this->nothing !== '') {
1441 $nothing = ['' => $this->nothing];
1442 } else if (is_array($this->nothing)) {
1443 $nothingvalue = reset($this->nothing);
1444 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1445 $nothing = [key($this->nothing) => get_string('choosedots')];
1446 } else {
1447 $nothing = $this->nothing;
1450 $data->options = $this->flatten_options($this->urls, $nothing);
1452 // Label attributes.
1453 $data->labelattributes = [];
1454 // Unset label attributes that are already in the template.
1455 unset($this->labelattributes['for']);
1456 // Map the label attributes.
1457 foreach ($this->labelattributes as $key => $value) {
1458 $data->labelattributes[] = ['name' => $key, 'value' => $value];
1461 // Help icon.
1462 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1464 // Finally all the remaining attributes.
1465 $data->attributes = [];
1466 foreach ($attributes as $key => $value) {
1467 $data->attributes[] = ['name' => $key, 'value' => $value];
1470 return $data;
1475 * Data structure describing html link with special action attached.
1477 * @copyright 2010 Petr Skoda
1478 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1479 * @since Moodle 2.0
1480 * @package core
1481 * @category output
1483 class action_link implements renderable {
1486 * @var moodle_url Href url
1488 public $url;
1491 * @var string Link text HTML fragment
1493 public $text;
1496 * @var array HTML attributes
1498 public $attributes;
1501 * @var array List of actions attached to link
1503 public $actions;
1506 * @var pix_icon Optional pix icon to render with the link
1508 public $icon;
1511 * Constructor
1512 * @param moodle_url $url
1513 * @param string $text HTML fragment
1514 * @param component_action $action
1515 * @param array $attributes associative array of html link attributes + disabled
1516 * @param pix_icon $icon optional pix_icon to render with the link text
1518 public function __construct(moodle_url $url,
1519 $text,
1520 component_action $action=null,
1521 array $attributes=null,
1522 pix_icon $icon=null) {
1523 $this->url = clone($url);
1524 $this->text = $text;
1525 if (empty($attributes['id'])) {
1526 $attributes['id'] = html_writer::random_id('action_link');
1528 $this->attributes = (array)$attributes;
1529 if ($action) {
1530 $this->add_action($action);
1532 $this->icon = $icon;
1536 * Add action to the link.
1538 * @param component_action $action
1540 public function add_action(component_action $action) {
1541 $this->actions[] = $action;
1545 * Adds a CSS class to this action link object
1546 * @param string $class
1548 public function add_class($class) {
1549 if (empty($this->attributes['class'])) {
1550 $this->attributes['class'] = $class;
1551 } else {
1552 $this->attributes['class'] .= ' ' . $class;
1557 * Returns true if the specified class has been added to this link.
1558 * @param string $class
1559 * @return bool
1561 public function has_class($class) {
1562 return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
1566 * Return the rendered HTML for the icon. Useful for rendering action links in a template.
1567 * @return string
1569 public function get_icon_html() {
1570 global $OUTPUT;
1571 if (!$this->icon) {
1572 return '';
1574 return $OUTPUT->render($this->icon);
1578 * Export for template.
1580 * @param renderer_base $output The renderer.
1581 * @return stdClass
1583 public function export_for_template(renderer_base $output) {
1584 $data = new stdClass();
1585 $attributes = $this->attributes;
1587 $data->id = $attributes['id'];
1588 unset($attributes['id']);
1590 $data->disabled = !empty($attributes['disabled']);
1591 unset($attributes['disabled']);
1593 $data->text = $this->text instanceof renderable ? $output->render($this->text) : (string) $this->text;
1594 $data->url = $this->url ? $this->url->out(false) : '';
1595 $data->icon = $this->icon ? $this->icon->export_for_pix() : null;
1596 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
1597 unset($attributes['class']);
1599 $data->attributes = array_map(function($key, $value) {
1600 return [
1601 'name' => $key,
1602 'value' => $value
1604 }, array_keys($attributes), $attributes);
1606 $data->actions = array_map(function($action) use ($output) {
1607 return $action->export_for_template($output);
1608 }, !empty($this->actions) ? $this->actions : []);
1609 $data->hasactions = !empty($this->actions);
1611 return $data;
1616 * Simple html output class
1618 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1619 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1620 * @since Moodle 2.0
1621 * @package core
1622 * @category output
1624 class html_writer {
1627 * Outputs a tag with attributes and contents
1629 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1630 * @param string $contents What goes between the opening and closing tags
1631 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1632 * @return string HTML fragment
1634 public static function tag($tagname, $contents, array $attributes = null) {
1635 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1639 * Outputs an opening tag with attributes
1641 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1642 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1643 * @return string HTML fragment
1645 public static function start_tag($tagname, array $attributes = null) {
1646 return '<' . $tagname . self::attributes($attributes) . '>';
1650 * Outputs a closing tag
1652 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1653 * @return string HTML fragment
1655 public static function end_tag($tagname) {
1656 return '</' . $tagname . '>';
1660 * Outputs an empty tag with attributes
1662 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1663 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1664 * @return string HTML fragment
1666 public static function empty_tag($tagname, array $attributes = null) {
1667 return '<' . $tagname . self::attributes($attributes) . ' />';
1671 * Outputs a tag, but only if the contents are not empty
1673 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1674 * @param string $contents What goes between the opening and closing tags
1675 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1676 * @return string HTML fragment
1678 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1679 if ($contents === '' || is_null($contents)) {
1680 return '';
1682 return self::tag($tagname, $contents, $attributes);
1686 * Outputs a HTML attribute and value
1688 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1689 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1690 * @return string HTML fragment
1692 public static function attribute($name, $value) {
1693 if ($value instanceof moodle_url) {
1694 return ' ' . $name . '="' . $value->out() . '"';
1697 // special case, we do not want these in output
1698 if ($value === null) {
1699 return '';
1702 // no sloppy trimming here!
1703 return ' ' . $name . '="' . s($value) . '"';
1707 * Outputs a list of HTML attributes and values
1709 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1710 * The values will be escaped with {@link s()}
1711 * @return string HTML fragment
1713 public static function attributes(array $attributes = null) {
1714 $attributes = (array)$attributes;
1715 $output = '';
1716 foreach ($attributes as $name => $value) {
1717 $output .= self::attribute($name, $value);
1719 return $output;
1723 * Generates a simple image tag with attributes.
1725 * @param string $src The source of image
1726 * @param string $alt The alternate text for image
1727 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1728 * @return string HTML fragment
1730 public static function img($src, $alt, array $attributes = null) {
1731 $attributes = (array)$attributes;
1732 $attributes['src'] = $src;
1733 $attributes['alt'] = $alt;
1735 return self::empty_tag('img', $attributes);
1739 * Generates random html element id.
1741 * @staticvar int $counter
1742 * @staticvar type $uniq
1743 * @param string $base A string fragment that will be included in the random ID.
1744 * @return string A unique ID
1746 public static function random_id($base='random') {
1747 static $counter = 0;
1748 static $uniq;
1750 if (!isset($uniq)) {
1751 $uniq = uniqid();
1754 $counter++;
1755 return $base.$uniq.$counter;
1759 * Generates a simple html link
1761 * @param string|moodle_url $url The URL
1762 * @param string $text The text
1763 * @param array $attributes HTML attributes
1764 * @return string HTML fragment
1766 public static function link($url, $text, array $attributes = null) {
1767 $attributes = (array)$attributes;
1768 $attributes['href'] = $url;
1769 return self::tag('a', $text, $attributes);
1773 * Generates a simple checkbox with optional label
1775 * @param string $name The name of the checkbox
1776 * @param string $value The value of the checkbox
1777 * @param bool $checked Whether the checkbox is checked
1778 * @param string $label The label for the checkbox
1779 * @param array $attributes Any attributes to apply to the checkbox
1780 * @param array $labelattributes Any attributes to apply to the label, if present
1781 * @return string html fragment
1783 public static function checkbox($name, $value, $checked = true, $label = '',
1784 array $attributes = null, array $labelattributes = null) {
1785 $attributes = (array) $attributes;
1786 $output = '';
1788 if ($label !== '' and !is_null($label)) {
1789 if (empty($attributes['id'])) {
1790 $attributes['id'] = self::random_id('checkbox_');
1793 $attributes['type'] = 'checkbox';
1794 $attributes['value'] = $value;
1795 $attributes['name'] = $name;
1796 $attributes['checked'] = $checked ? 'checked' : null;
1798 $output .= self::empty_tag('input', $attributes);
1800 if ($label !== '' and !is_null($label)) {
1801 $labelattributes = (array) $labelattributes;
1802 $labelattributes['for'] = $attributes['id'];
1803 $output .= self::tag('label', $label, $labelattributes);
1806 return $output;
1810 * Generates a simple select yes/no form field
1812 * @param string $name name of select element
1813 * @param bool $selected
1814 * @param array $attributes - html select element attributes
1815 * @return string HTML fragment
1817 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1818 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1819 return self::select($options, $name, $selected, null, $attributes);
1823 * Generates a simple select form field
1825 * Note this function does HTML escaping on the optgroup labels, but not on the choice labels.
1827 * @param array $options associative array value=>label ex.:
1828 * array(1=>'One, 2=>Two)
1829 * it is also possible to specify optgroup as complex label array ex.:
1830 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1831 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1832 * @param string $name name of select element
1833 * @param string|array $selected value or array of values depending on multiple attribute
1834 * @param array|bool $nothing add nothing selected option, or false of not added
1835 * @param array $attributes html select element attributes
1836 * @return string HTML fragment
1838 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1839 $attributes = (array)$attributes;
1840 if (is_array($nothing)) {
1841 foreach ($nothing as $k=>$v) {
1842 if ($v === 'choose' or $v === 'choosedots') {
1843 $nothing[$k] = get_string('choosedots');
1846 $options = $nothing + $options; // keep keys, do not override
1848 } else if (is_string($nothing) and $nothing !== '') {
1849 // BC
1850 $options = array(''=>$nothing) + $options;
1853 // we may accept more values if multiple attribute specified
1854 $selected = (array)$selected;
1855 foreach ($selected as $k=>$v) {
1856 $selected[$k] = (string)$v;
1859 if (!isset($attributes['id'])) {
1860 $id = 'menu'.$name;
1861 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1862 $id = str_replace('[', '', $id);
1863 $id = str_replace(']', '', $id);
1864 $attributes['id'] = $id;
1867 if (!isset($attributes['class'])) {
1868 $class = 'menu'.$name;
1869 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1870 $class = str_replace('[', '', $class);
1871 $class = str_replace(']', '', $class);
1872 $attributes['class'] = $class;
1874 $attributes['class'] = 'select custom-select ' . $attributes['class']; // Add 'select' selector always.
1876 $attributes['name'] = $name;
1878 if (!empty($attributes['disabled'])) {
1879 $attributes['disabled'] = 'disabled';
1880 } else {
1881 unset($attributes['disabled']);
1884 $output = '';
1885 foreach ($options as $value=>$label) {
1886 if (is_array($label)) {
1887 // ignore key, it just has to be unique
1888 $output .= self::select_optgroup(key($label), current($label), $selected);
1889 } else {
1890 $output .= self::select_option($label, $value, $selected);
1893 return self::tag('select', $output, $attributes);
1897 * Returns HTML to display a select box option.
1899 * @param string $label The label to display as the option.
1900 * @param string|int $value The value the option represents
1901 * @param array $selected An array of selected options
1902 * @return string HTML fragment
1904 private static function select_option($label, $value, array $selected) {
1905 $attributes = array();
1906 $value = (string)$value;
1907 if (in_array($value, $selected, true)) {
1908 $attributes['selected'] = 'selected';
1910 $attributes['value'] = $value;
1911 return self::tag('option', $label, $attributes);
1915 * Returns HTML to display a select box option group.
1917 * @param string $groupname The label to use for the group
1918 * @param array $options The options in the group
1919 * @param array $selected An array of selected values.
1920 * @return string HTML fragment.
1922 private static function select_optgroup($groupname, $options, array $selected) {
1923 if (empty($options)) {
1924 return '';
1926 $attributes = array('label'=>$groupname);
1927 $output = '';
1928 foreach ($options as $value=>$label) {
1929 $output .= self::select_option($label, $value, $selected);
1931 return self::tag('optgroup', $output, $attributes);
1935 * This is a shortcut for making an hour selector menu.
1937 * @param string $type The type of selector (years, months, days, hours, minutes)
1938 * @param string $name fieldname
1939 * @param int $currenttime A default timestamp in GMT
1940 * @param int $step minute spacing
1941 * @param array $attributes - html select element attributes
1942 * @return HTML fragment
1944 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1945 global $OUTPUT;
1947 if (!$currenttime) {
1948 $currenttime = time();
1950 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1951 $currentdate = $calendartype->timestamp_to_date_array($currenttime);
1952 $userdatetype = $type;
1953 $timeunits = array();
1955 switch ($type) {
1956 case 'years':
1957 $timeunits = $calendartype->get_years();
1958 $userdatetype = 'year';
1959 break;
1960 case 'months':
1961 $timeunits = $calendartype->get_months();
1962 $userdatetype = 'month';
1963 $currentdate['month'] = (int)$currentdate['mon'];
1964 break;
1965 case 'days':
1966 $timeunits = $calendartype->get_days();
1967 $userdatetype = 'mday';
1968 break;
1969 case 'hours':
1970 for ($i=0; $i<=23; $i++) {
1971 $timeunits[$i] = sprintf("%02d",$i);
1973 break;
1974 case 'minutes':
1975 if ($step != 1) {
1976 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1979 for ($i=0; $i<=59; $i+=$step) {
1980 $timeunits[$i] = sprintf("%02d",$i);
1982 break;
1983 default:
1984 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1987 $attributes = (array) $attributes;
1988 $data = (object) [
1989 'name' => $name,
1990 'id' => !empty($attributes['id']) ? $attributes['id'] : self::random_id('ts_'),
1991 'label' => get_string(substr($type, 0, -1), 'form'),
1992 'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) {
1993 return [
1994 'name' => $timeunits[$value],
1995 'value' => $value,
1996 'selected' => $currentdate[$userdatetype] == $value
1998 }, array_keys($timeunits)),
2001 unset($attributes['id']);
2002 unset($attributes['name']);
2003 $data->attributes = array_map(function($name) use ($attributes) {
2004 return [
2005 'name' => $name,
2006 'value' => $attributes[$name]
2008 }, array_keys($attributes));
2010 return $OUTPUT->render_from_template('core/select_time', $data);
2014 * Shortcut for quick making of lists
2016 * Note: 'list' is a reserved keyword ;-)
2018 * @param array $items
2019 * @param array $attributes
2020 * @param string $tag ul or ol
2021 * @return string
2023 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
2024 $output = html_writer::start_tag($tag, $attributes)."\n";
2025 foreach ($items as $item) {
2026 $output .= html_writer::tag('li', $item)."\n";
2028 $output .= html_writer::end_tag($tag);
2029 return $output;
2033 * Returns hidden input fields created from url parameters.
2035 * @param moodle_url $url
2036 * @param array $exclude list of excluded parameters
2037 * @return string HTML fragment
2039 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
2040 $exclude = (array)$exclude;
2041 $params = $url->params();
2042 foreach ($exclude as $key) {
2043 unset($params[$key]);
2046 $output = '';
2047 foreach ($params as $key => $value) {
2048 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
2049 $output .= self::empty_tag('input', $attributes)."\n";
2051 return $output;
2055 * Generate a script tag containing the the specified code.
2057 * @param string $jscode the JavaScript code
2058 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
2059 * @return string HTML, the code wrapped in <script> tags.
2061 public static function script($jscode, $url=null) {
2062 if ($jscode) {
2063 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n") . "\n";
2065 } else if ($url) {
2066 return self::tag('script', '', ['src' => $url]) . "\n";
2068 } else {
2069 return '';
2074 * Renders HTML table
2076 * This method may modify the passed instance by adding some default properties if they are not set yet.
2077 * If this is not what you want, you should make a full clone of your data before passing them to this
2078 * method. In most cases this is not an issue at all so we do not clone by default for performance
2079 * and memory consumption reasons.
2081 * @param html_table $table data to be rendered
2082 * @return string HTML code
2084 public static function table(html_table $table) {
2085 // prepare table data and populate missing properties with reasonable defaults
2086 if (!empty($table->align)) {
2087 foreach ($table->align as $key => $aa) {
2088 if ($aa) {
2089 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
2090 } else {
2091 $table->align[$key] = null;
2095 if (!empty($table->size)) {
2096 foreach ($table->size as $key => $ss) {
2097 if ($ss) {
2098 $table->size[$key] = 'width:'. $ss .';';
2099 } else {
2100 $table->size[$key] = null;
2104 if (!empty($table->wrap)) {
2105 foreach ($table->wrap as $key => $ww) {
2106 if ($ww) {
2107 $table->wrap[$key] = 'white-space:nowrap;';
2108 } else {
2109 $table->wrap[$key] = '';
2113 if (!empty($table->head)) {
2114 foreach ($table->head as $key => $val) {
2115 if (!isset($table->align[$key])) {
2116 $table->align[$key] = null;
2118 if (!isset($table->size[$key])) {
2119 $table->size[$key] = null;
2121 if (!isset($table->wrap[$key])) {
2122 $table->wrap[$key] = null;
2127 if (empty($table->attributes['class'])) {
2128 $table->attributes['class'] = 'generaltable';
2130 if (!empty($table->tablealign)) {
2131 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
2134 // explicitly assigned properties override those defined via $table->attributes
2135 $table->attributes['class'] = trim($table->attributes['class']);
2136 $attributes = array_merge($table->attributes, array(
2137 'id' => $table->id,
2138 'width' => $table->width,
2139 'summary' => $table->summary,
2140 'cellpadding' => $table->cellpadding,
2141 'cellspacing' => $table->cellspacing,
2143 $output = html_writer::start_tag('table', $attributes) . "\n";
2145 $countcols = 0;
2147 // Output a caption if present.
2148 if (!empty($table->caption)) {
2149 $captionattributes = array();
2150 if ($table->captionhide) {
2151 $captionattributes['class'] = 'accesshide';
2153 $output .= html_writer::tag(
2154 'caption',
2155 $table->caption,
2156 $captionattributes
2160 if (!empty($table->head)) {
2161 $countcols = count($table->head);
2163 $output .= html_writer::start_tag('thead', array()) . "\n";
2164 $output .= html_writer::start_tag('tr', array()) . "\n";
2165 $keys = array_keys($table->head);
2166 $lastkey = end($keys);
2168 foreach ($table->head as $key => $heading) {
2169 // Convert plain string headings into html_table_cell objects
2170 if (!($heading instanceof html_table_cell)) {
2171 $headingtext = $heading;
2172 $heading = new html_table_cell();
2173 $heading->text = $headingtext;
2174 $heading->header = true;
2177 if ($heading->header !== false) {
2178 $heading->header = true;
2181 $tagtype = 'td';
2182 if ($heading->header && (string)$heading->text != '') {
2183 $tagtype = 'th';
2186 $heading->attributes['class'] .= ' header c' . $key;
2187 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
2188 $heading->colspan = $table->headspan[$key];
2189 $countcols += $table->headspan[$key] - 1;
2192 if ($key == $lastkey) {
2193 $heading->attributes['class'] .= ' lastcol';
2195 if (isset($table->colclasses[$key])) {
2196 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
2198 $heading->attributes['class'] = trim($heading->attributes['class']);
2199 $attributes = array_merge($heading->attributes, [
2200 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
2201 'colspan' => $heading->colspan,
2204 if ($tagtype == 'th') {
2205 $attributes['scope'] = !empty($heading->scope) ? $heading->scope : 'col';
2208 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
2210 $output .= html_writer::end_tag('tr') . "\n";
2211 $output .= html_writer::end_tag('thead') . "\n";
2213 if (empty($table->data)) {
2214 // For valid XHTML strict every table must contain either a valid tr
2215 // or a valid tbody... both of which must contain a valid td
2216 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
2217 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
2218 $output .= html_writer::end_tag('tbody');
2222 if (!empty($table->data)) {
2223 $keys = array_keys($table->data);
2224 $lastrowkey = end($keys);
2225 $output .= html_writer::start_tag('tbody', array());
2227 foreach ($table->data as $key => $row) {
2228 if (($row === 'hr') && ($countcols)) {
2229 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
2230 } else {
2231 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
2232 if (!($row instanceof html_table_row)) {
2233 $newrow = new html_table_row();
2235 foreach ($row as $cell) {
2236 if (!($cell instanceof html_table_cell)) {
2237 $cell = new html_table_cell($cell);
2239 $newrow->cells[] = $cell;
2241 $row = $newrow;
2244 if (isset($table->rowclasses[$key])) {
2245 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
2248 if ($key == $lastrowkey) {
2249 $row->attributes['class'] .= ' lastrow';
2252 // Explicitly assigned properties should override those defined in the attributes.
2253 $row->attributes['class'] = trim($row->attributes['class']);
2254 $trattributes = array_merge($row->attributes, array(
2255 'id' => $row->id,
2256 'style' => $row->style,
2258 $output .= html_writer::start_tag('tr', $trattributes) . "\n";
2259 $keys2 = array_keys($row->cells);
2260 $lastkey = end($keys2);
2262 $gotlastkey = false; //flag for sanity checking
2263 foreach ($row->cells as $key => $cell) {
2264 if ($gotlastkey) {
2265 //This should never happen. Why do we have a cell after the last cell?
2266 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
2269 if (!($cell instanceof html_table_cell)) {
2270 $mycell = new html_table_cell();
2271 $mycell->text = $cell;
2272 $cell = $mycell;
2275 if (($cell->header === true) && empty($cell->scope)) {
2276 $cell->scope = 'row';
2279 if (isset($table->colclasses[$key])) {
2280 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
2283 $cell->attributes['class'] .= ' cell c' . $key;
2284 if ($key == $lastkey) {
2285 $cell->attributes['class'] .= ' lastcol';
2286 $gotlastkey = true;
2288 $tdstyle = '';
2289 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
2290 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
2291 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
2292 $cell->attributes['class'] = trim($cell->attributes['class']);
2293 $tdattributes = array_merge($cell->attributes, array(
2294 'style' => $tdstyle . $cell->style,
2295 'colspan' => $cell->colspan,
2296 'rowspan' => $cell->rowspan,
2297 'id' => $cell->id,
2298 'abbr' => $cell->abbr,
2299 'scope' => $cell->scope,
2301 $tagtype = 'td';
2302 if ($cell->header === true) {
2303 $tagtype = 'th';
2305 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
2308 $output .= html_writer::end_tag('tr') . "\n";
2310 $output .= html_writer::end_tag('tbody') . "\n";
2312 $output .= html_writer::end_tag('table') . "\n";
2314 if ($table->responsive) {
2315 return self::div($output, 'table-responsive');
2318 return $output;
2322 * Renders form element label
2324 * By default, the label is suffixed with a label separator defined in the
2325 * current language pack (colon by default in the English lang pack).
2326 * Adding the colon can be explicitly disabled if needed. Label separators
2327 * are put outside the label tag itself so they are not read by
2328 * screenreaders (accessibility).
2330 * Parameter $for explicitly associates the label with a form control. When
2331 * set, the value of this attribute must be the same as the value of
2332 * the id attribute of the form control in the same document. When null,
2333 * the label being defined is associated with the control inside the label
2334 * element.
2336 * @param string $text content of the label tag
2337 * @param string|null $for id of the element this label is associated with, null for no association
2338 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
2339 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
2340 * @return string HTML of the label element
2342 public static function label($text, $for, $colonize = true, array $attributes=array()) {
2343 if (!is_null($for)) {
2344 $attributes = array_merge($attributes, array('for' => $for));
2346 $text = trim($text);
2347 $label = self::tag('label', $text, $attributes);
2349 // TODO MDL-12192 $colonize disabled for now yet
2350 // if (!empty($text) and $colonize) {
2351 // // the $text may end with the colon already, though it is bad string definition style
2352 // $colon = get_string('labelsep', 'langconfig');
2353 // if (!empty($colon)) {
2354 // $trimmed = trim($colon);
2355 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
2356 // //debugging('The label text should not end with colon or other label separator,
2357 // // please fix the string definition.', DEBUG_DEVELOPER);
2358 // } else {
2359 // $label .= $colon;
2360 // }
2361 // }
2362 // }
2364 return $label;
2368 * Combines a class parameter with other attributes. Aids in code reduction
2369 * because the class parameter is very frequently used.
2371 * If the class attribute is specified both in the attributes and in the
2372 * class parameter, the two values are combined with a space between.
2374 * @param string $class Optional CSS class (or classes as space-separated list)
2375 * @param array $attributes Optional other attributes as array
2376 * @return array Attributes (or null if still none)
2378 private static function add_class($class = '', array $attributes = null) {
2379 if ($class !== '') {
2380 $classattribute = array('class' => $class);
2381 if ($attributes) {
2382 if (array_key_exists('class', $attributes)) {
2383 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
2384 } else {
2385 $attributes = $classattribute + $attributes;
2387 } else {
2388 $attributes = $classattribute;
2391 return $attributes;
2395 * Creates a <div> tag. (Shortcut function.)
2397 * @param string $content HTML content of tag
2398 * @param string $class Optional CSS class (or classes as space-separated list)
2399 * @param array $attributes Optional other attributes as array
2400 * @return string HTML code for div
2402 public static function div($content, $class = '', array $attributes = null) {
2403 return self::tag('div', $content, self::add_class($class, $attributes));
2407 * Starts a <div> tag. (Shortcut function.)
2409 * @param string $class Optional CSS class (or classes as space-separated list)
2410 * @param array $attributes Optional other attributes as array
2411 * @return string HTML code for open div tag
2413 public static function start_div($class = '', array $attributes = null) {
2414 return self::start_tag('div', self::add_class($class, $attributes));
2418 * Ends a <div> tag. (Shortcut function.)
2420 * @return string HTML code for close div tag
2422 public static function end_div() {
2423 return self::end_tag('div');
2427 * Creates a <span> tag. (Shortcut function.)
2429 * @param string $content HTML content of tag
2430 * @param string $class Optional CSS class (or classes as space-separated list)
2431 * @param array $attributes Optional other attributes as array
2432 * @return string HTML code for span
2434 public static function span($content, $class = '', array $attributes = null) {
2435 return self::tag('span', $content, self::add_class($class, $attributes));
2439 * Starts a <span> tag. (Shortcut function.)
2441 * @param string $class Optional CSS class (or classes as space-separated list)
2442 * @param array $attributes Optional other attributes as array
2443 * @return string HTML code for open span tag
2445 public static function start_span($class = '', array $attributes = null) {
2446 return self::start_tag('span', self::add_class($class, $attributes));
2450 * Ends a <span> tag. (Shortcut function.)
2452 * @return string HTML code for close span tag
2454 public static function end_span() {
2455 return self::end_tag('span');
2460 * Simple javascript output class
2462 * @copyright 2010 Petr Skoda
2463 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2464 * @since Moodle 2.0
2465 * @package core
2466 * @category output
2468 class js_writer {
2471 * Returns javascript code calling the function
2473 * @param string $function function name, can be complex like Y.Event.purgeElement
2474 * @param array $arguments parameters
2475 * @param int $delay execution delay in seconds
2476 * @return string JS code fragment
2478 public static function function_call($function, array $arguments = null, $delay=0) {
2479 if ($arguments) {
2480 $arguments = array_map('json_encode', convert_to_array($arguments));
2481 $arguments = implode(', ', $arguments);
2482 } else {
2483 $arguments = '';
2485 $js = "$function($arguments);";
2487 if ($delay) {
2488 $delay = $delay * 1000; // in miliseconds
2489 $js = "setTimeout(function() { $js }, $delay);";
2491 return $js . "\n";
2495 * Special function which adds Y as first argument of function call.
2497 * @param string $function The function to call
2498 * @param array $extraarguments Any arguments to pass to it
2499 * @return string Some JS code
2501 public static function function_call_with_Y($function, array $extraarguments = null) {
2502 if ($extraarguments) {
2503 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
2504 $arguments = 'Y, ' . implode(', ', $extraarguments);
2505 } else {
2506 $arguments = 'Y';
2508 return "$function($arguments);\n";
2512 * Returns JavaScript code to initialise a new object
2514 * @param string $var If it is null then no var is assigned the new object.
2515 * @param string $class The class to initialise an object for.
2516 * @param array $arguments An array of args to pass to the init method.
2517 * @param array $requirements Any modules required for this class.
2518 * @param int $delay The delay before initialisation. 0 = no delay.
2519 * @return string Some JS code
2521 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
2522 if (is_array($arguments)) {
2523 $arguments = array_map('json_encode', convert_to_array($arguments));
2524 $arguments = implode(', ', $arguments);
2527 if ($var === null) {
2528 $js = "new $class(Y, $arguments);";
2529 } else if (strpos($var, '.')!==false) {
2530 $js = "$var = new $class(Y, $arguments);";
2531 } else {
2532 $js = "var $var = new $class(Y, $arguments);";
2535 if ($delay) {
2536 $delay = $delay * 1000; // in miliseconds
2537 $js = "setTimeout(function() { $js }, $delay);";
2540 if (count($requirements) > 0) {
2541 $requirements = implode("', '", $requirements);
2542 $js = "Y.use('$requirements', function(Y){ $js });";
2544 return $js."\n";
2548 * Returns code setting value to variable
2550 * @param string $name
2551 * @param mixed $value json serialised value
2552 * @param bool $usevar add var definition, ignored for nested properties
2553 * @return string JS code fragment
2555 public static function set_variable($name, $value, $usevar = true) {
2556 $output = '';
2558 if ($usevar) {
2559 if (strpos($name, '.')) {
2560 $output .= '';
2561 } else {
2562 $output .= 'var ';
2566 $output .= "$name = ".json_encode($value).";";
2568 return $output;
2572 * Writes event handler attaching code
2574 * @param array|string $selector standard YUI selector for elements, may be
2575 * array or string, element id is in the form "#idvalue"
2576 * @param string $event A valid DOM event (click, mousedown, change etc.)
2577 * @param string $function The name of the function to call
2578 * @param array $arguments An optional array of argument parameters to pass to the function
2579 * @return string JS code fragment
2581 public static function event_handler($selector, $event, $function, array $arguments = null) {
2582 $selector = json_encode($selector);
2583 $output = "Y.on('$event', $function, $selector, null";
2584 if (!empty($arguments)) {
2585 $output .= ', ' . json_encode($arguments);
2587 return $output . ");\n";
2592 * Holds all the information required to render a <table> by {@link core_renderer::table()}
2594 * Example of usage:
2595 * $t = new html_table();
2596 * ... // set various properties of the object $t as described below
2597 * echo html_writer::table($t);
2599 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
2600 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2601 * @since Moodle 2.0
2602 * @package core
2603 * @category output
2605 class html_table {
2608 * @var string Value to use for the id attribute of the table
2610 public $id = null;
2613 * @var array Attributes of HTML attributes for the <table> element
2615 public $attributes = array();
2618 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
2619 * For more control over the rendering of the headers, an array of html_table_cell objects
2620 * can be passed instead of an array of strings.
2622 * Example of usage:
2623 * $t->head = array('Student', 'Grade');
2625 public $head;
2628 * @var array An array that can be used to make a heading span multiple columns.
2629 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
2630 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
2632 * Example of usage:
2633 * $t->headspan = array(2,1);
2635 public $headspan;
2638 * @var array An array of column alignments.
2639 * The value is used as CSS 'text-align' property. Therefore, possible
2640 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
2641 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
2643 * Examples of usage:
2644 * $t->align = array(null, 'right');
2645 * or
2646 * $t->align[1] = 'right';
2648 public $align;
2651 * @var array The value is used as CSS 'size' property.
2653 * Examples of usage:
2654 * $t->size = array('50%', '50%');
2655 * or
2656 * $t->size[1] = '120px';
2658 public $size;
2661 * @var array An array of wrapping information.
2662 * The only possible value is 'nowrap' that sets the
2663 * CSS property 'white-space' to the value 'nowrap' in the given column.
2665 * Example of usage:
2666 * $t->wrap = array(null, 'nowrap');
2668 public $wrap;
2671 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2672 * $head specified, the string 'hr' (for horizontal ruler) can be used
2673 * instead of an array of cells data resulting in a divider rendered.
2675 * Example of usage with array of arrays:
2676 * $row1 = array('Harry Potter', '76 %');
2677 * $row2 = array('Hermione Granger', '100 %');
2678 * $t->data = array($row1, $row2);
2680 * Example with array of html_table_row objects: (used for more fine-grained control)
2681 * $cell1 = new html_table_cell();
2682 * $cell1->text = 'Harry Potter';
2683 * $cell1->colspan = 2;
2684 * $row1 = new html_table_row();
2685 * $row1->cells[] = $cell1;
2686 * $cell2 = new html_table_cell();
2687 * $cell2->text = 'Hermione Granger';
2688 * $cell3 = new html_table_cell();
2689 * $cell3->text = '100 %';
2690 * $row2 = new html_table_row();
2691 * $row2->cells = array($cell2, $cell3);
2692 * $t->data = array($row1, $row2);
2694 public $data = [];
2697 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2698 * @var string Width of the table, percentage of the page preferred.
2700 public $width = null;
2703 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2704 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2706 public $tablealign = null;
2709 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2710 * @var int Padding on each cell, in pixels
2712 public $cellpadding = null;
2715 * @var int Spacing between cells, in pixels
2716 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2718 public $cellspacing = null;
2721 * @var array Array of classes to add to particular rows, space-separated string.
2722 * Class 'lastrow' is added automatically for the last row in the table.
2724 * Example of usage:
2725 * $t->rowclasses[9] = 'tenth'
2727 public $rowclasses;
2730 * @var array An array of classes to add to every cell in a particular column,
2731 * space-separated string. Class 'cell' is added automatically by the renderer.
2732 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2733 * respectively. Class 'lastcol' is added automatically for all last cells
2734 * in a row.
2736 * Example of usage:
2737 * $t->colclasses = array(null, 'grade');
2739 public $colclasses;
2742 * @var string Description of the contents for screen readers.
2744 * The "summary" attribute on the "table" element is not supported in HTML5.
2745 * Consider describing the structure of the table in a "caption" element or in a "figure" element containing the table;
2746 * or, simplify the structure of the table so that no description is needed.
2748 * @deprecated since Moodle 3.9.
2750 public $summary;
2753 * @var string Caption for the table, typically a title.
2755 * Example of usage:
2756 * $t->caption = "TV Guide";
2758 public $caption;
2761 * @var bool Whether to hide the table's caption from sighted users.
2763 * Example of usage:
2764 * $t->caption = "TV Guide";
2765 * $t->captionhide = true;
2767 public $captionhide = false;
2769 /** @var bool Whether to make the table to be scrolled horizontally with ease. Make table responsive across all viewports. */
2770 public $responsive = true;
2773 * Constructor
2775 public function __construct() {
2776 $this->attributes['class'] = '';
2781 * Component representing a table row.
2783 * @copyright 2009 Nicolas Connault
2784 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2785 * @since Moodle 2.0
2786 * @package core
2787 * @category output
2789 class html_table_row {
2792 * @var string Value to use for the id attribute of the row.
2794 public $id = null;
2797 * @var array Array of html_table_cell objects
2799 public $cells = array();
2802 * @var string Value to use for the style attribute of the table row
2804 public $style = null;
2807 * @var array Attributes of additional HTML attributes for the <tr> element
2809 public $attributes = array();
2812 * Constructor
2813 * @param array $cells
2815 public function __construct(array $cells=null) {
2816 $this->attributes['class'] = '';
2817 $cells = (array)$cells;
2818 foreach ($cells as $cell) {
2819 if ($cell instanceof html_table_cell) {
2820 $this->cells[] = $cell;
2821 } else {
2822 $this->cells[] = new html_table_cell($cell);
2829 * Component representing a table cell.
2831 * @copyright 2009 Nicolas Connault
2832 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2833 * @since Moodle 2.0
2834 * @package core
2835 * @category output
2837 class html_table_cell {
2840 * @var string Value to use for the id attribute of the cell.
2842 public $id = null;
2845 * @var string The contents of the cell.
2847 public $text;
2850 * @var string Abbreviated version of the contents of the cell.
2852 public $abbr = null;
2855 * @var int Number of columns this cell should span.
2857 public $colspan = null;
2860 * @var int Number of rows this cell should span.
2862 public $rowspan = null;
2865 * @var string Defines a way to associate header cells and data cells in a table.
2867 public $scope = null;
2870 * @var bool Whether or not this cell is a header cell.
2872 public $header = null;
2875 * @var string Value to use for the style attribute of the table cell
2877 public $style = null;
2880 * @var array Attributes of additional HTML attributes for the <td> element
2882 public $attributes = array();
2885 * Constructs a table cell
2887 * @param string $text
2889 public function __construct($text = null) {
2890 $this->text = $text;
2891 $this->attributes['class'] = '';
2896 * Component representing a paging bar.
2898 * @copyright 2009 Nicolas Connault
2899 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2900 * @since Moodle 2.0
2901 * @package core
2902 * @category output
2904 class paging_bar implements renderable, templatable {
2907 * @var int The maximum number of pagelinks to display.
2909 public $maxdisplay = 18;
2912 * @var int The total number of entries to be pages through..
2914 public $totalcount;
2917 * @var int The page you are currently viewing.
2919 public $page;
2922 * @var int The number of entries that should be shown per page.
2924 public $perpage;
2927 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2928 * an equals sign and the page number.
2929 * If this is a moodle_url object then the pagevar param will be replaced by
2930 * the page no, for each page.
2932 public $baseurl;
2935 * @var string This is the variable name that you use for the pagenumber in your
2936 * code (ie. 'tablepage', 'blogpage', etc)
2938 public $pagevar;
2941 * @var string A HTML link representing the "previous" page.
2943 public $previouslink = null;
2946 * @var string A HTML link representing the "next" page.
2948 public $nextlink = null;
2951 * @var string A HTML link representing the first page.
2953 public $firstlink = null;
2956 * @var string A HTML link representing the last page.
2958 public $lastlink = null;
2961 * @var array An array of strings. One of them is just a string: the current page
2963 public $pagelinks = array();
2966 * Constructor paging_bar with only the required params.
2968 * @param int $totalcount The total number of entries available to be paged through
2969 * @param int $page The page you are currently viewing
2970 * @param int $perpage The number of entries that should be shown per page
2971 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2972 * @param string $pagevar name of page parameter that holds the page number
2974 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2975 $this->totalcount = $totalcount;
2976 $this->page = $page;
2977 $this->perpage = $perpage;
2978 $this->baseurl = $baseurl;
2979 $this->pagevar = $pagevar;
2983 * Prepares the paging bar for output.
2985 * This method validates the arguments set up for the paging bar and then
2986 * produces fragments of HTML to assist display later on.
2988 * @param renderer_base $output
2989 * @param moodle_page $page
2990 * @param string $target
2991 * @throws coding_exception
2993 public function prepare(renderer_base $output, moodle_page $page, $target) {
2994 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2995 throw new coding_exception('paging_bar requires a totalcount value.');
2997 if (!isset($this->page) || is_null($this->page)) {
2998 throw new coding_exception('paging_bar requires a page value.');
3000 if (empty($this->perpage)) {
3001 throw new coding_exception('paging_bar requires a perpage value.');
3003 if (empty($this->baseurl)) {
3004 throw new coding_exception('paging_bar requires a baseurl value.');
3007 if ($this->totalcount > $this->perpage) {
3008 $pagenum = $this->page - 1;
3010 if ($this->page > 0) {
3011 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
3014 if ($this->perpage > 0) {
3015 $lastpage = ceil($this->totalcount / $this->perpage);
3016 } else {
3017 $lastpage = 1;
3020 if ($this->page > round(($this->maxdisplay/3)*2)) {
3021 $currpage = $this->page - round($this->maxdisplay/3);
3023 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
3024 } else {
3025 $currpage = 0;
3028 $displaycount = $displaypage = 0;
3030 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3031 $displaypage = $currpage + 1;
3033 if ($this->page == $currpage) {
3034 $this->pagelinks[] = html_writer::span($displaypage, 'current-page');
3035 } else {
3036 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
3037 $this->pagelinks[] = $pagelink;
3040 $displaycount++;
3041 $currpage++;
3044 if ($currpage < $lastpage) {
3045 $lastpageactual = $lastpage - 1;
3046 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
3049 $pagenum = $this->page + 1;
3051 if ($pagenum != $lastpage) {
3052 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
3058 * Export for template.
3060 * @param renderer_base $output The renderer.
3061 * @return stdClass
3063 public function export_for_template(renderer_base $output) {
3064 $data = new stdClass();
3065 $data->previous = null;
3066 $data->next = null;
3067 $data->first = null;
3068 $data->last = null;
3069 $data->label = get_string('page');
3070 $data->pages = [];
3071 $data->haspages = $this->totalcount > $this->perpage;
3072 $data->pagesize = $this->perpage;
3074 if (!$data->haspages) {
3075 return $data;
3078 if ($this->page > 0) {
3079 $data->previous = [
3080 'page' => $this->page,
3081 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page - 1]))->out(false)
3085 $currpage = 0;
3086 if ($this->page > round(($this->maxdisplay / 3) * 2)) {
3087 $currpage = $this->page - round($this->maxdisplay / 3);
3088 $data->first = [
3089 'page' => 1,
3090 'url' => (new moodle_url($this->baseurl, [$this->pagevar => 0]))->out(false)
3094 $lastpage = 1;
3095 if ($this->perpage > 0) {
3096 $lastpage = ceil($this->totalcount / $this->perpage);
3099 $displaycount = 0;
3100 $displaypage = 0;
3101 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3102 $displaypage = $currpage + 1;
3104 $iscurrent = $this->page == $currpage;
3105 $link = new moodle_url($this->baseurl, [$this->pagevar => $currpage]);
3107 $data->pages[] = [
3108 'page' => $displaypage,
3109 'active' => $iscurrent,
3110 'url' => $iscurrent ? null : $link->out(false)
3113 $displaycount++;
3114 $currpage++;
3117 if ($currpage < $lastpage) {
3118 $data->last = [
3119 'page' => $lastpage,
3120 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $lastpage - 1]))->out(false)
3124 if ($this->page + 1 != $lastpage) {
3125 $data->next = [
3126 'page' => $this->page + 2,
3127 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page + 1]))->out(false)
3131 return $data;
3136 * Component representing initials bar.
3138 * @copyright 2017 Ilya Tregubov
3139 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3140 * @since Moodle 3.3
3141 * @package core
3142 * @category output
3144 class initials_bar implements renderable, templatable {
3147 * @var string Currently selected letter.
3149 public $current;
3152 * @var string Class name to add to this initial bar.
3154 public $class;
3157 * @var string The name to put in front of this initial bar.
3159 public $title;
3162 * @var string URL parameter name for this initial.
3164 public $urlvar;
3167 * @var string URL object.
3169 public $url;
3172 * @var array An array of letters in the alphabet.
3174 public $alpha;
3177 * Constructor initials_bar with only the required params.
3179 * @param string $current the currently selected letter.
3180 * @param string $class class name to add to this initial bar.
3181 * @param string $title the name to put in front of this initial bar.
3182 * @param string $urlvar URL parameter name for this initial.
3183 * @param string $url URL object.
3184 * @param array $alpha of letters in the alphabet.
3186 public function __construct($current, $class, $title, $urlvar, $url, $alpha = null) {
3187 $this->current = $current;
3188 $this->class = $class;
3189 $this->title = $title;
3190 $this->urlvar = $urlvar;
3191 $this->url = $url;
3192 $this->alpha = $alpha;
3196 * Export for template.
3198 * @param renderer_base $output The renderer.
3199 * @return stdClass
3201 public function export_for_template(renderer_base $output) {
3202 $data = new stdClass();
3204 if ($this->alpha == null) {
3205 $this->alpha = explode(',', get_string('alphabet', 'langconfig'));
3208 if ($this->current == 'all') {
3209 $this->current = '';
3212 // We want to find a letter grouping size which suits the language so
3213 // find the largest group size which is less than 15 chars.
3214 // The choice of 15 chars is the largest number of chars that reasonably
3215 // fits on the smallest supported screen size. By always using a max number
3216 // of groups which is a factor of 2, we always get nice wrapping, and the
3217 // last row is always the shortest.
3218 $groupsize = count($this->alpha);
3219 $groups = 1;
3220 while ($groupsize > 15) {
3221 $groups *= 2;
3222 $groupsize = ceil(count($this->alpha) / $groups);
3225 $groupsizelimit = 0;
3226 $groupnumber = 0;
3227 foreach ($this->alpha as $letter) {
3228 if ($groupsizelimit++ > 0 && $groupsizelimit % $groupsize == 1) {
3229 $groupnumber++;
3231 $groupletter = new stdClass();
3232 $groupletter->name = $letter;
3233 $groupletter->url = $this->url->out(false, array($this->urlvar => $letter));
3234 if ($letter == $this->current) {
3235 $groupletter->selected = $this->current;
3237 if (!isset($data->group[$groupnumber])) {
3238 $data->group[$groupnumber] = new stdClass();
3240 $data->group[$groupnumber]->letter[] = $groupletter;
3243 $data->class = $this->class;
3244 $data->title = $this->title;
3245 $data->url = $this->url->out(false, array($this->urlvar => ''));
3246 $data->current = $this->current;
3247 $data->all = get_string('all');
3249 return $data;
3254 * This class represents how a block appears on a page.
3256 * During output, each block instance is asked to return a block_contents object,
3257 * those are then passed to the $OUTPUT->block function for display.
3259 * contents should probably be generated using a moodle_block_..._renderer.
3261 * Other block-like things that need to appear on the page, for example the
3262 * add new block UI, are also represented as block_contents objects.
3264 * @copyright 2009 Tim Hunt
3265 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3266 * @since Moodle 2.0
3267 * @package core
3268 * @category output
3270 class block_contents {
3272 /** Used when the block cannot be collapsed **/
3273 const NOT_HIDEABLE = 0;
3275 /** Used when the block can be collapsed but currently is not **/
3276 const VISIBLE = 1;
3278 /** Used when the block has been collapsed **/
3279 const HIDDEN = 2;
3282 * @var int Used to set $skipid.
3284 protected static $idcounter = 1;
3287 * @var int All the blocks (or things that look like blocks) printed on
3288 * a page are given a unique number that can be used to construct id="" attributes.
3289 * This is set automatically be the {@link prepare()} method.
3290 * Do not try to set it manually.
3292 public $skipid;
3295 * @var int If this is the contents of a real block, this should be set
3296 * to the block_instance.id. Otherwise this should be set to 0.
3298 public $blockinstanceid = 0;
3301 * @var int If this is a real block instance, and there is a corresponding
3302 * block_position.id for the block on this page, this should be set to that id.
3303 * Otherwise it should be 0.
3305 public $blockpositionid = 0;
3308 * @var array An array of attribute => value pairs that are put on the outer div of this
3309 * block. {@link $id} and {@link $classes} attributes should be set separately.
3311 public $attributes;
3314 * @var string The title of this block. If this came from user input, it should already
3315 * have had format_string() processing done on it. This will be output inside
3316 * <h2> tags. Please do not cause invalid XHTML.
3318 public $title = '';
3321 * @var string The label to use when the block does not, or will not have a visible title.
3322 * You should never set this as well as title... it will just be ignored.
3324 public $arialabel = '';
3327 * @var string HTML for the content
3329 public $content = '';
3332 * @var array An alternative to $content, it you want a list of things with optional icons.
3334 public $footer = '';
3337 * @var string Any small print that should appear under the block to explain
3338 * to the teacher about the block, for example 'This is a sticky block that was
3339 * added in the system context.'
3341 public $annotation = '';
3344 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
3345 * the user can toggle whether this block is visible.
3347 public $collapsible = self::NOT_HIDEABLE;
3350 * Set this to true if the block is dockable.
3351 * @var bool
3353 public $dockable = false;
3356 * @var array A (possibly empty) array of editing controls. Each element of
3357 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
3358 * $icon is the icon name. Fed to $OUTPUT->image_url.
3360 public $controls = array();
3364 * Create new instance of block content
3365 * @param array $attributes
3367 public function __construct(array $attributes = null) {
3368 $this->skipid = self::$idcounter;
3369 self::$idcounter += 1;
3371 if ($attributes) {
3372 // standard block
3373 $this->attributes = $attributes;
3374 } else {
3375 // simple "fake" blocks used in some modules and "Add new block" block
3376 $this->attributes = array('class'=>'block');
3381 * Add html class to block
3383 * @param string $class
3385 public function add_class($class) {
3386 $this->attributes['class'] .= ' '.$class;
3390 * Check if the block is a fake block.
3392 * @return boolean
3394 public function is_fake() {
3395 return isset($this->attributes['data-block']) && $this->attributes['data-block'] == '_fake';
3401 * This class represents a target for where a block can go when it is being moved.
3403 * This needs to be rendered as a form with the given hidden from fields, and
3404 * clicking anywhere in the form should submit it. The form action should be
3405 * $PAGE->url.
3407 * @copyright 2009 Tim Hunt
3408 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3409 * @since Moodle 2.0
3410 * @package core
3411 * @category output
3413 class block_move_target {
3416 * @var moodle_url Move url
3418 public $url;
3421 * Constructor
3422 * @param moodle_url $url
3424 public function __construct(moodle_url $url) {
3425 $this->url = $url;
3430 * Custom menu item
3432 * This class is used to represent one item within a custom menu that may or may
3433 * not have children.
3435 * @copyright 2010 Sam Hemelryk
3436 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3437 * @since Moodle 2.0
3438 * @package core
3439 * @category output
3441 class custom_menu_item implements renderable, templatable {
3444 * @var string The text to show for the item
3446 protected $text;
3449 * @var moodle_url The link to give the icon if it has no children
3451 protected $url;
3454 * @var string A title to apply to the item. By default the text
3456 protected $title;
3459 * @var int A sort order for the item, not necessary if you order things in
3460 * the CFG var.
3462 protected $sort;
3465 * @var custom_menu_item A reference to the parent for this item or NULL if
3466 * it is a top level item
3468 protected $parent;
3471 * @var array A array in which to store children this item has.
3473 protected $children = array();
3476 * @var int A reference to the sort var of the last child that was added
3478 protected $lastsort = 0;
3480 /** @var array Array of other HTML attributes for the custom menu item. */
3481 protected $attributes = [];
3484 * Constructs the new custom menu item
3486 * @param string $text
3487 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
3488 * @param string $title A title to apply to this item [Optional]
3489 * @param int $sort A sort or to use if we need to sort differently [Optional]
3490 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
3491 * belongs to, only if the child has a parent. [Optional]
3492 * @param array $attributes Array of other HTML attributes for the custom menu item.
3494 public function __construct($text, moodle_url $url = null, $title = null, $sort = null, custom_menu_item $parent = null,
3495 array $attributes = []) {
3496 $this->text = $text;
3497 $this->url = $url;
3498 $this->title = $title;
3499 $this->sort = (int)$sort;
3500 $this->parent = $parent;
3501 $this->attributes = $attributes;
3505 * Adds a custom menu item as a child of this node given its properties.
3507 * @param string $text
3508 * @param moodle_url $url
3509 * @param string $title
3510 * @param int $sort
3511 * @param array $attributes Array of other HTML attributes for the custom menu item.
3512 * @return custom_menu_item
3514 public function add($text, moodle_url $url = null, $title = null, $sort = null, $attributes = []) {
3515 $key = count($this->children);
3516 if (empty($sort)) {
3517 $sort = $this->lastsort + 1;
3519 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this, $attributes);
3520 $this->lastsort = (int)$sort;
3521 return $this->children[$key];
3525 * Removes a custom menu item that is a child or descendant to the current menu.
3527 * Returns true if child was found and removed.
3529 * @param custom_menu_item $menuitem
3530 * @return bool
3532 public function remove_child(custom_menu_item $menuitem) {
3533 $removed = false;
3534 if (($key = array_search($menuitem, $this->children)) !== false) {
3535 unset($this->children[$key]);
3536 $this->children = array_values($this->children);
3537 $removed = true;
3538 } else {
3539 foreach ($this->children as $child) {
3540 if ($removed = $child->remove_child($menuitem)) {
3541 break;
3545 return $removed;
3549 * Returns the text for this item
3550 * @return string
3552 public function get_text() {
3553 return $this->text;
3557 * Returns the url for this item
3558 * @return moodle_url
3560 public function get_url() {
3561 return $this->url;
3565 * Returns the title for this item
3566 * @return string
3568 public function get_title() {
3569 return $this->title;
3573 * Sorts and returns the children for this item
3574 * @return array
3576 public function get_children() {
3577 $this->sort();
3578 return $this->children;
3582 * Gets the sort order for this child
3583 * @return int
3585 public function get_sort_order() {
3586 return $this->sort;
3590 * Gets the parent this child belong to
3591 * @return custom_menu_item
3593 public function get_parent() {
3594 return $this->parent;
3598 * Sorts the children this item has
3600 public function sort() {
3601 usort($this->children, array('custom_menu','sort_custom_menu_items'));
3605 * Returns true if this item has any children
3606 * @return bool
3608 public function has_children() {
3609 return (count($this->children) > 0);
3613 * Sets the text for the node
3614 * @param string $text
3616 public function set_text($text) {
3617 $this->text = (string)$text;
3621 * Sets the title for the node
3622 * @param string $title
3624 public function set_title($title) {
3625 $this->title = (string)$title;
3629 * Sets the url for the node
3630 * @param moodle_url $url
3632 public function set_url(moodle_url $url) {
3633 $this->url = $url;
3637 * Export this data so it can be used as the context for a mustache template.
3639 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
3640 * @return array
3642 public function export_for_template(renderer_base $output) {
3643 global $CFG;
3645 require_once($CFG->libdir . '/externallib.php');
3647 $syscontext = context_system::instance();
3649 $context = new stdClass();
3650 $context->moremenuid = uniqid();
3651 $context->text = external_format_string($this->text, $syscontext->id);
3652 $context->url = $this->url ? $this->url->out() : null;
3653 // No need for the title if it's the same with text.
3654 if ($this->text !== $this->title) {
3655 // Show the title attribute only if it's different from the text.
3656 $context->title = external_format_string($this->title, $syscontext->id);
3658 $context->sort = $this->sort;
3659 if (!empty($this->attributes)) {
3660 $context->attributes = $this->attributes;
3662 $context->children = array();
3663 if (preg_match("/^#+$/", $this->text)) {
3664 $context->divider = true;
3666 $context->haschildren = !empty($this->children) && (count($this->children) > 0);
3667 foreach ($this->children as $child) {
3668 $child = $child->export_for_template($output);
3669 array_push($context->children, $child);
3672 return $context;
3677 * Custom menu class
3679 * This class is used to operate a custom menu that can be rendered for the page.
3680 * The custom menu is built using $CFG->custommenuitems and is a structured collection
3681 * of custom_menu_item nodes that can be rendered by the core renderer.
3683 * To configure the custom menu:
3684 * Settings: Administration > Appearance > Themes > Theme settings
3686 * @copyright 2010 Sam Hemelryk
3687 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3688 * @since Moodle 2.0
3689 * @package core
3690 * @category output
3692 class custom_menu extends custom_menu_item {
3695 * @var string The language we should render for, null disables multilang support.
3697 protected $currentlanguage = null;
3700 * Creates the custom menu
3702 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
3703 * @param string $currentlanguage the current language code, null disables multilang support
3705 public function __construct($definition = '', $currentlanguage = null) {
3706 $this->currentlanguage = $currentlanguage;
3707 parent::__construct('root'); // create virtual root element of the menu
3708 if (!empty($definition)) {
3709 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
3714 * Overrides the children of this custom menu. Useful when getting children
3715 * from $CFG->custommenuitems
3717 * @param array $children
3719 public function override_children(array $children) {
3720 $this->children = array();
3721 foreach ($children as $child) {
3722 if ($child instanceof custom_menu_item) {
3723 $this->children[] = $child;
3729 * Converts a string into a structured array of custom_menu_items which can
3730 * then be added to a custom menu.
3732 * Structure:
3733 * text|url|title|langs
3734 * The number of hyphens at the start determines the depth of the item. The
3735 * languages are optional, comma separated list of languages the line is for.
3737 * Example structure:
3738 * First level first item|http://www.moodle.com/
3739 * -Second level first item|http://www.moodle.com/partners/
3740 * -Second level second item|http://www.moodle.com/hq/
3741 * --Third level first item|http://www.moodle.com/jobs/
3742 * -Second level third item|http://www.moodle.com/development/
3743 * First level second item|http://www.moodle.com/feedback/
3744 * First level third item
3745 * English only|http://moodle.com|English only item|en
3746 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
3749 * @static
3750 * @param string $text the menu items definition
3751 * @param string $language the language code, null disables multilang support
3752 * @return array
3754 public static function convert_text_to_menu_nodes($text, $language = null) {
3755 $root = new custom_menu();
3756 $lastitem = $root;
3757 $lastdepth = 0;
3758 $hiddenitems = array();
3759 $lines = explode("\n", $text);
3760 foreach ($lines as $linenumber => $line) {
3761 $line = trim($line);
3762 if (strlen($line) == 0) {
3763 continue;
3765 // Parse item settings.
3766 $itemtext = null;
3767 $itemurl = null;
3768 $itemtitle = null;
3769 $itemvisible = true;
3770 $settings = explode('|', $line);
3771 foreach ($settings as $i => $setting) {
3772 $setting = trim($setting);
3773 if (!empty($setting)) {
3774 switch ($i) {
3775 case 0: // Menu text.
3776 $itemtext = ltrim($setting, '-');
3777 break;
3778 case 1: // URL.
3779 try {
3780 $itemurl = new moodle_url($setting);
3781 } catch (moodle_exception $exception) {
3782 // We're not actually worried about this, we don't want to mess up the display
3783 // just for a wrongly entered URL.
3784 $itemurl = null;
3786 break;
3787 case 2: // Title attribute.
3788 $itemtitle = $setting;
3789 break;
3790 case 3: // Language.
3791 if (!empty($language)) {
3792 $itemlanguages = array_map('trim', explode(',', $setting));
3793 $itemvisible &= in_array($language, $itemlanguages);
3795 break;
3799 // Get depth of new item.
3800 preg_match('/^(\-*)/', $line, $match);
3801 $itemdepth = strlen($match[1]) + 1;
3802 // Find parent item for new item.
3803 while (($lastdepth - $itemdepth) >= 0) {
3804 $lastitem = $lastitem->get_parent();
3805 $lastdepth--;
3807 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1);
3808 $lastdepth++;
3809 if (!$itemvisible) {
3810 $hiddenitems[] = $lastitem;
3813 foreach ($hiddenitems as $item) {
3814 $item->parent->remove_child($item);
3816 return $root->get_children();
3820 * Sorts two custom menu items
3822 * This function is designed to be used with the usort method
3823 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
3825 * @static
3826 * @param custom_menu_item $itema
3827 * @param custom_menu_item $itemb
3828 * @return int
3830 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
3831 $itema = $itema->get_sort_order();
3832 $itemb = $itemb->get_sort_order();
3833 if ($itema == $itemb) {
3834 return 0;
3836 return ($itema > $itemb) ? +1 : -1;
3841 * Stores one tab
3843 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3844 * @package core
3846 class tabobject implements renderable, templatable {
3847 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
3848 var $id;
3849 /** @var moodle_url|string link */
3850 var $link;
3851 /** @var string text on the tab */
3852 var $text;
3853 /** @var string title under the link, by defaul equals to text */
3854 var $title;
3855 /** @var bool whether to display a link under the tab name when it's selected */
3856 var $linkedwhenselected = false;
3857 /** @var bool whether the tab is inactive */
3858 var $inactive = false;
3859 /** @var bool indicates that this tab's child is selected */
3860 var $activated = false;
3861 /** @var bool indicates that this tab is selected */
3862 var $selected = false;
3863 /** @var array stores children tabobjects */
3864 var $subtree = array();
3865 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
3866 var $level = 1;
3869 * Constructor
3871 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
3872 * @param string|moodle_url $link
3873 * @param string $text text on the tab
3874 * @param string $title title under the link, by defaul equals to text
3875 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
3877 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
3878 $this->id = $id;
3879 $this->link = $link;
3880 $this->text = $text;
3881 $this->title = $title ? $title : $text;
3882 $this->linkedwhenselected = $linkedwhenselected;
3886 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
3888 * @param string $selected the id of the selected tab (whatever row it's on),
3889 * if null marks all tabs as unselected
3890 * @return bool whether this tab is selected or contains selected tab in its subtree
3892 protected function set_selected($selected) {
3893 if ((string)$selected === (string)$this->id) {
3894 $this->selected = true;
3895 // This tab is selected. No need to travel through subtree.
3896 return true;
3898 foreach ($this->subtree as $subitem) {
3899 if ($subitem->set_selected($selected)) {
3900 // This tab has child that is selected. Mark it as activated. No need to check other children.
3901 $this->activated = true;
3902 return true;
3905 return false;
3909 * Travels through tree and finds a tab with specified id
3911 * @param string $id
3912 * @return tabtree|null
3914 public function find($id) {
3915 if ((string)$this->id === (string)$id) {
3916 return $this;
3918 foreach ($this->subtree as $tab) {
3919 if ($obj = $tab->find($id)) {
3920 return $obj;
3923 return null;
3927 * Allows to mark each tab's level in the tree before rendering.
3929 * @param int $level
3931 protected function set_level($level) {
3932 $this->level = $level;
3933 foreach ($this->subtree as $tab) {
3934 $tab->set_level($level + 1);
3939 * Export for template.
3941 * @param renderer_base $output Renderer.
3942 * @return object
3944 public function export_for_template(renderer_base $output) {
3945 if ($this->inactive || ($this->selected && !$this->linkedwhenselected) || $this->activated) {
3946 $link = null;
3947 } else {
3948 $link = $this->link;
3950 $active = $this->activated || $this->selected;
3952 return (object) [
3953 'id' => $this->id,
3954 'link' => is_object($link) ? $link->out(false) : $link,
3955 'text' => $this->text,
3956 'title' => $this->title,
3957 'inactive' => !$active && $this->inactive,
3958 'active' => $active,
3959 'level' => $this->level,
3966 * Renderable for the main page header.
3968 * @package core
3969 * @category output
3970 * @since 2.9
3971 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
3972 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3974 class context_header implements renderable {
3977 * @var string $heading Main heading.
3979 public $heading;
3981 * @var int $headinglevel Main heading 'h' tag level.
3983 public $headinglevel;
3985 * @var string|null $imagedata HTML code for the picture in the page header.
3987 public $imagedata;
3989 * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
3990 * array elements - title => alternate text for the image, or if no image is available the button text.
3991 * url => Link for the button to head to. Should be a moodle_url.
3992 * image => location to the image, or name of the image in /pix/t/{image name}.
3993 * linkattributes => additional attributes for the <a href> element.
3994 * page => page object. Don't include if the image is an external image.
3996 public $additionalbuttons;
3998 * @var string $prefix A string that is before the title.
4000 public $prefix;
4003 * Constructor.
4005 * @param string $heading Main heading data.
4006 * @param int $headinglevel Main heading 'h' tag level.
4007 * @param string|null $imagedata HTML code for the picture in the page header.
4008 * @param string $additionalbuttons Buttons for the header e.g. Messaging button for the user header.
4009 * @param string $prefix Text that precedes the heading.
4011 public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null, $prefix = null) {
4013 $this->heading = $heading;
4014 $this->headinglevel = $headinglevel;
4015 $this->imagedata = $imagedata;
4016 $this->additionalbuttons = $additionalbuttons;
4017 // If we have buttons then format them.
4018 if (isset($this->additionalbuttons)) {
4019 $this->format_button_images();
4021 $this->prefix = $prefix;
4025 * Adds an array element for a formatted image.
4027 protected function format_button_images() {
4029 foreach ($this->additionalbuttons as $buttontype => $button) {
4030 $page = $button['page'];
4031 // If no image is provided then just use the title.
4032 if (!isset($button['image'])) {
4033 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['title'];
4034 } else {
4035 // Check to see if this is an internal Moodle icon.
4036 $internalimage = $page->theme->resolve_image_location('t/' . $button['image'], 'moodle');
4037 if ($internalimage) {
4038 $this->additionalbuttons[$buttontype]['formattedimage'] = 't/' . $button['image'];
4039 } else {
4040 // Treat as an external image.
4041 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['image'];
4045 if (isset($button['linkattributes']['class'])) {
4046 $class = $button['linkattributes']['class'] . ' btn';
4047 } else {
4048 $class = 'btn';
4050 // Add the bootstrap 'btn' class for formatting.
4051 $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
4052 array('class' => $class));
4058 * Stores tabs list
4060 * Example how to print a single line tabs:
4061 * $rows = array(
4062 * new tabobject(...),
4063 * new tabobject(...)
4064 * );
4065 * echo $OUTPUT->tabtree($rows, $selectedid);
4067 * Multiple row tabs may not look good on some devices but if you want to use them
4068 * you can specify ->subtree for the active tabobject.
4070 * @copyright 2013 Marina Glancy
4071 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4072 * @since Moodle 2.5
4073 * @package core
4074 * @category output
4076 class tabtree extends tabobject {
4078 * Constuctor
4080 * It is highly recommended to call constructor when list of tabs is already
4081 * populated, this way you ensure that selected and inactive tabs are located
4082 * and attribute level is set correctly.
4084 * @param array $tabs array of tabs, each of them may have it's own ->subtree
4085 * @param string|null $selected which tab to mark as selected, all parent tabs will
4086 * automatically be marked as activated
4087 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4088 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
4090 public function __construct($tabs, $selected = null, $inactive = null) {
4091 $this->subtree = $tabs;
4092 if ($selected !== null) {
4093 $this->set_selected($selected);
4095 if ($inactive !== null) {
4096 if (is_array($inactive)) {
4097 foreach ($inactive as $id) {
4098 if ($tab = $this->find($id)) {
4099 $tab->inactive = true;
4102 } else if ($tab = $this->find($inactive)) {
4103 $tab->inactive = true;
4106 $this->set_level(0);
4110 * Export for template.
4112 * @param renderer_base $output Renderer.
4113 * @return object
4115 public function export_for_template(renderer_base $output) {
4116 $tabs = [];
4117 $secondrow = false;
4119 foreach ($this->subtree as $tab) {
4120 $tabs[] = $tab->export_for_template($output);
4121 if (!empty($tab->subtree) && ($tab->level == 0 || $tab->selected || $tab->activated)) {
4122 $secondrow = new tabtree($tab->subtree);
4126 return (object) [
4127 'tabs' => $tabs,
4128 'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false
4134 * An action menu.
4136 * This action menu component takes a series of primary and secondary actions.
4137 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
4138 * down menu.
4140 * @package core
4141 * @category output
4142 * @copyright 2013 Sam Hemelryk
4143 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4145 class action_menu implements renderable, templatable {
4148 * Top right alignment.
4150 const TL = 1;
4153 * Top right alignment.
4155 const TR = 2;
4158 * Top right alignment.
4160 const BL = 3;
4163 * Top right alignment.
4165 const BR = 4;
4168 * The instance number. This is unique to this instance of the action menu.
4169 * @var int
4171 protected $instance = 0;
4174 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
4175 * @var array
4177 protected $primaryactions = array();
4180 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
4181 * @var array
4183 protected $secondaryactions = array();
4186 * An array of attributes added to the container of the action menu.
4187 * Initialised with defaults during construction.
4188 * @var array
4190 public $attributes = array();
4192 * An array of attributes added to the container of the primary actions.
4193 * Initialised with defaults during construction.
4194 * @var array
4196 public $attributesprimary = array();
4198 * An array of attributes added to the container of the secondary actions.
4199 * Initialised with defaults during construction.
4200 * @var array
4202 public $attributessecondary = array();
4205 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
4206 * @var array
4208 public $actiontext = null;
4211 * The string to use for the accessible label for the menu.
4212 * @var array
4214 public $actionlabel = null;
4217 * An icon to use for the toggling the secondary menu (dropdown).
4218 * @var pix_icon
4220 public $actionicon;
4223 * Any text to use for the toggling the secondary menu (dropdown).
4224 * @var string
4226 public $menutrigger = '';
4229 * Any extra classes for toggling to the secondary menu.
4230 * @var string
4232 public $triggerextraclasses = '';
4235 * Place the action menu before all other actions.
4236 * @var bool
4238 public $prioritise = false;
4241 * Dropdown menu alignment class.
4242 * @var string
4244 public $dropdownalignment = '';
4247 * Constructs the action menu with the given items.
4249 * @param array $actions An array of actions (action_menu_link|pix_icon|string).
4251 public function __construct(array $actions = array()) {
4252 static $initialised = 0;
4253 $this->instance = $initialised;
4254 $initialised++;
4256 $this->attributes = array(
4257 'id' => 'action-menu-'.$this->instance,
4258 'class' => 'moodle-actionmenu',
4259 'data-enhance' => 'moodle-core-actionmenu'
4261 $this->attributesprimary = array(
4262 'id' => 'action-menu-'.$this->instance.'-menubar',
4263 'class' => 'menubar',
4265 $this->attributessecondary = array(
4266 'id' => 'action-menu-'.$this->instance.'-menu',
4267 'class' => 'menu',
4268 'data-rel' => 'menu-content',
4269 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
4270 'role' => 'menu'
4272 $this->dropdownalignment = 'dropdown-menu-right';
4273 foreach ($actions as $action) {
4274 $this->add($action);
4279 * Sets the label for the menu trigger.
4281 * @param string $label The text
4283 public function set_action_label($label) {
4284 $this->actionlabel = $label;
4288 * Sets the menu trigger text.
4290 * @param string $trigger The text
4291 * @param string $extraclasses Extra classes to style the secondary menu toggle.
4293 public function set_menu_trigger($trigger, $extraclasses = '') {
4294 $this->menutrigger = $trigger;
4295 $this->triggerextraclasses = $extraclasses;
4299 * Return true if there is at least one visible link in the menu.
4301 * @return bool
4303 public function is_empty() {
4304 return !count($this->primaryactions) && !count($this->secondaryactions);
4308 * Initialises JS required fore the action menu.
4309 * The JS is only required once as it manages all action menu's on the page.
4311 * @param moodle_page $page
4313 public function initialise_js(moodle_page $page) {
4314 static $initialised = false;
4315 if (!$initialised) {
4316 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
4317 $initialised = true;
4322 * Adds an action to this action menu.
4324 * @param action_menu_link|pix_icon|string $action
4326 public function add($action) {
4327 if ($action instanceof action_link) {
4328 if ($action->primary) {
4329 $this->add_primary_action($action);
4330 } else {
4331 $this->add_secondary_action($action);
4333 } else if ($action instanceof pix_icon) {
4334 $this->add_primary_action($action);
4335 } else {
4336 $this->add_secondary_action($action);
4341 * Adds a primary action to the action menu.
4343 * @param action_menu_link|action_link|pix_icon|string $action
4345 public function add_primary_action($action) {
4346 if ($action instanceof action_link || $action instanceof pix_icon) {
4347 $action->attributes['role'] = 'menuitem';
4348 $action->attributes['tabindex'] = '-1';
4349 if ($action instanceof action_menu_link) {
4350 $action->actionmenu = $this;
4353 $this->primaryactions[] = $action;
4357 * Adds a secondary action to the action menu.
4359 * @param action_link|pix_icon|string $action
4361 public function add_secondary_action($action) {
4362 if ($action instanceof action_link || $action instanceof pix_icon) {
4363 $action->attributes['role'] = 'menuitem';
4364 $action->attributes['tabindex'] = '-1';
4365 if ($action instanceof action_menu_link) {
4366 $action->actionmenu = $this;
4369 $this->secondaryactions[] = $action;
4373 * Returns the primary actions ready to be rendered.
4375 * @param core_renderer $output The renderer to use for getting icons.
4376 * @return array
4378 public function get_primary_actions(core_renderer $output = null) {
4379 global $OUTPUT;
4380 if ($output === null) {
4381 $output = $OUTPUT;
4383 $pixicon = $this->actionicon;
4384 $linkclasses = array('toggle-display');
4386 $title = '';
4387 if (!empty($this->menutrigger)) {
4388 $pixicon = '<b class="caret"></b>';
4389 $linkclasses[] = 'textmenu';
4390 } else {
4391 $title = new lang_string('actionsmenu', 'moodle');
4392 $this->actionicon = new pix_icon(
4393 't/edit_menu',
4395 'moodle',
4396 array('class' => 'iconsmall actionmenu', 'title' => '')
4398 $pixicon = $this->actionicon;
4400 if ($pixicon instanceof renderable) {
4401 $pixicon = $output->render($pixicon);
4402 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
4403 $title = $pixicon->attributes['alt'];
4406 $string = '';
4407 if ($this->actiontext) {
4408 $string = $this->actiontext;
4410 $label = '';
4411 if ($this->actionlabel) {
4412 $label = $this->actionlabel;
4413 } else {
4414 $label = $title;
4416 $actions = $this->primaryactions;
4417 $attributes = array(
4418 'class' => implode(' ', $linkclasses),
4419 'title' => $title,
4420 'aria-label' => $label,
4421 'id' => 'action-menu-toggle-'.$this->instance,
4422 'role' => 'menuitem',
4423 'tabindex' => '-1',
4425 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
4426 if ($this->prioritise) {
4427 array_unshift($actions, $link);
4428 } else {
4429 $actions[] = $link;
4431 return $actions;
4435 * Returns the secondary actions ready to be rendered.
4436 * @return array
4438 public function get_secondary_actions() {
4439 return $this->secondaryactions;
4443 * Sets the selector that should be used to find the owning node of this menu.
4444 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
4446 public function set_owner_selector($selector) {
4447 $this->attributes['data-owner'] = $selector;
4451 * Sets the alignment of the dialogue in relation to button used to toggle it.
4453 * @deprecated since Moodle 4.0
4455 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4456 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4458 public function set_alignment($dialogue, $button) {
4459 debugging('The method action_menu::set_alignment() is deprecated, use action_menu::set_menu_left()', DEBUG_DEVELOPER);
4460 if (isset($this->attributessecondary['data-align'])) {
4461 // We've already got one set, lets remove the old class so as to avoid troubles.
4462 $class = $this->attributessecondary['class'];
4463 $search = 'align-'.$this->attributessecondary['data-align'];
4464 $this->attributessecondary['class'] = str_replace($search, '', $class);
4466 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
4467 $this->attributessecondary['data-align'] = $align;
4468 $this->attributessecondary['class'] .= ' align-'.$align;
4472 * Returns a string to describe the alignment.
4474 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4475 * @return string
4477 protected function get_align_string($align) {
4478 switch ($align) {
4479 case self::TL :
4480 return 'tl';
4481 case self::TR :
4482 return 'tr';
4483 case self::BL :
4484 return 'bl';
4485 case self::BR :
4486 return 'br';
4487 default :
4488 return 'tl';
4493 * Aligns the left corner of the dropdown.
4496 public function set_menu_left() {
4497 $this->dropdownalignment = 'dropdown-menu-left';
4501 * Sets a constraint for the dialogue.
4503 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
4504 * element the constraint identifies.
4506 * This is required whenever the action menu is displayed inside any CSS element with the .no-overflow class
4507 * (flexible_table and any of it's child classes are a likely candidate).
4509 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
4511 public function set_constraint($ancestorselector) {
4512 $this->attributessecondary['data-constraint'] = $ancestorselector;
4516 * If you call this method the action menu will be displayed but will not be enhanced.
4518 * By not displaying the menu enhanced all items will be displayed in a single row.
4520 * @deprecated since Moodle 3.2
4522 public function do_not_enhance() {
4523 debugging('The method action_menu::do_not_enhance() is deprecated, use a list of action_icon instead.', DEBUG_DEVELOPER);
4527 * Returns true if this action menu will be enhanced.
4529 * @return bool
4531 public function will_be_enhanced() {
4532 return isset($this->attributes['data-enhance']);
4536 * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
4538 * This property can be useful when the action menu is displayed within a parent element that is either floated
4539 * or relatively positioned.
4540 * In that situation the width of the menu is determined by the width of the parent element which may not be large
4541 * enough for the menu items without them wrapping.
4542 * This disables the wrapping so that the menu takes on the width of the longest item.
4544 * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
4546 public function set_nowrap_on_items($value = true) {
4547 $class = 'nowrap-items';
4548 if (!empty($this->attributes['class'])) {
4549 $pos = strpos($this->attributes['class'], $class);
4550 if ($value === true && $pos === false) {
4551 // The value is true and the class has not been set yet. Add it.
4552 $this->attributes['class'] .= ' '.$class;
4553 } else if ($value === false && $pos !== false) {
4554 // The value is false and the class has been set. Remove it.
4555 $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class));
4557 } else if ($value) {
4558 // The value is true and the class has not been set yet. Add it.
4559 $this->attributes['class'] = $class;
4564 * Export for template.
4566 * @param renderer_base $output The renderer.
4567 * @return stdClass
4569 public function export_for_template(renderer_base $output) {
4570 $data = new stdClass();
4571 // Assign a role of menubar to this action menu when:
4572 // - it contains 2 or more primary actions; or
4573 // - if it contains a primary action and secondary actions.
4574 if (count($this->primaryactions) > 1 || (!empty($this->primaryactions) && !empty($this->secondaryactions))) {
4575 $this->attributes['role'] = 'menubar';
4577 $attributes = $this->attributes;
4578 $attributesprimary = $this->attributesprimary;
4579 $attributessecondary = $this->attributessecondary;
4581 $data->instance = $this->instance;
4583 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
4584 unset($attributes['class']);
4586 $data->attributes = array_map(function($key, $value) {
4587 return [ 'name' => $key, 'value' => $value ];
4588 }, array_keys($attributes), $attributes);
4590 $primary = new stdClass();
4591 $primary->title = '';
4592 $primary->prioritise = $this->prioritise;
4594 $primary->classes = isset($attributesprimary['class']) ? $attributesprimary['class'] : '';
4595 unset($attributesprimary['class']);
4596 $primary->attributes = array_map(function($key, $value) {
4597 return [ 'name' => $key, 'value' => $value ];
4598 }, array_keys($attributesprimary), $attributesprimary);
4600 $actionicon = $this->actionicon;
4601 if (!empty($this->menutrigger)) {
4602 $primary->menutrigger = $this->menutrigger;
4603 $primary->triggerextraclasses = $this->triggerextraclasses;
4604 if ($this->actionlabel) {
4605 $primary->title = $this->actionlabel;
4606 } else if ($this->actiontext) {
4607 $primary->title = $this->actiontext;
4608 } else {
4609 $primary->title = strip_tags($this->menutrigger);
4611 } else {
4612 $primary->title = get_string('actionsmenu');
4613 $iconattributes = ['class' => 'iconsmall actionmenu', 'title' => $primary->title];
4614 $actionicon = new pix_icon('t/edit_menu', '', 'moodle', $iconattributes);
4617 // If the menu trigger is within the menubar, assign a role of menuitem. Otherwise, assign as a button.
4618 $primary->triggerrole = 'button';
4619 if (isset($attributes['role']) && $attributes['role'] === 'menubar') {
4620 $primary->triggerrole = 'menuitem';
4623 if ($actionicon instanceof pix_icon) {
4624 $primary->icon = $actionicon->export_for_pix();
4625 if (!empty($actionicon->attributes['alt'])) {
4626 $primary->title = $actionicon->attributes['alt'];
4628 } else {
4629 $primary->iconraw = $actionicon ? $output->render($actionicon) : '';
4632 $primary->actiontext = $this->actiontext ? (string) $this->actiontext : '';
4633 $primary->items = array_map(function($item) use ($output) {
4634 $data = (object) [];
4635 if ($item instanceof action_menu_link) {
4636 $data->actionmenulink = $item->export_for_template($output);
4637 } else if ($item instanceof action_menu_filler) {
4638 $data->actionmenufiller = $item->export_for_template($output);
4639 } else if ($item instanceof action_link) {
4640 $data->actionlink = $item->export_for_template($output);
4641 } else if ($item instanceof pix_icon) {
4642 $data->pixicon = $item->export_for_template($output);
4643 } else {
4644 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4646 return $data;
4647 }, $this->primaryactions);
4649 $secondary = new stdClass();
4650 $secondary->classes = isset($attributessecondary['class']) ? $attributessecondary['class'] : '';
4651 unset($attributessecondary['class']);
4652 $secondary->attributes = array_map(function($key, $value) {
4653 return [ 'name' => $key, 'value' => $value ];
4654 }, array_keys($attributessecondary), $attributessecondary);
4655 $secondary->items = array_map(function($item) use ($output) {
4656 $data = (object) [];
4657 if ($item instanceof action_menu_link) {
4658 $data->actionmenulink = $item->export_for_template($output);
4659 } else if ($item instanceof action_menu_filler) {
4660 $data->actionmenufiller = $item->export_for_template($output);
4661 } else if ($item instanceof action_link) {
4662 $data->actionlink = $item->export_for_template($output);
4663 } else if ($item instanceof pix_icon) {
4664 $data->pixicon = $item->export_for_template($output);
4665 } else {
4666 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4668 return $data;
4669 }, $this->secondaryactions);
4671 $data->primary = $primary;
4672 $data->secondary = $secondary;
4673 $data->dropdownalignment = $this->dropdownalignment;
4675 return $data;
4681 * An action menu filler
4683 * @package core
4684 * @category output
4685 * @copyright 2013 Andrew Nicols
4686 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4688 class action_menu_filler extends action_link implements renderable {
4691 * True if this is a primary action. False if not.
4692 * @var bool
4694 public $primary = true;
4697 * Constructs the object.
4699 public function __construct() {
4700 $this->attributes['id'] = html_writer::random_id('action_link');
4705 * An action menu action
4707 * @package core
4708 * @category output
4709 * @copyright 2013 Sam Hemelryk
4710 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4712 class action_menu_link extends action_link implements renderable {
4715 * True if this is a primary action. False if not.
4716 * @var bool
4718 public $primary = true;
4721 * The action menu this link has been added to.
4722 * @var action_menu
4724 public $actionmenu = null;
4727 * The number of instances of this action menu link (and its subclasses).
4728 * @var int
4730 protected static $instance = 1;
4733 * Constructs the object.
4735 * @param moodle_url $url The URL for the action.
4736 * @param pix_icon|null $icon The icon to represent the action.
4737 * @param string $text The text to represent the action.
4738 * @param bool $primary Whether this is a primary action or not.
4739 * @param array $attributes Any attribtues associated with the action.
4741 public function __construct(moodle_url $url, ?pix_icon $icon, $text, $primary = true, array $attributes = array()) {
4742 parent::__construct($url, $text, null, $attributes, $icon);
4743 $this->primary = (bool)$primary;
4744 $this->add_class('menu-action');
4745 $this->attributes['role'] = 'menuitem';
4749 * Export for template.
4751 * @param renderer_base $output The renderer.
4752 * @return stdClass
4754 public function export_for_template(renderer_base $output) {
4755 $data = parent::export_for_template($output);
4756 $data->instance = self::$instance++;
4758 // Ignore what the parent did with the attributes, except for ID and class.
4759 $data->attributes = [];
4760 $attributes = $this->attributes;
4761 unset($attributes['id']);
4762 unset($attributes['class']);
4764 // Handle text being a renderable.
4765 if ($this->text instanceof renderable) {
4766 $data->text = $this->render($this->text);
4769 $data->showtext = (!$this->icon || $this->primary === false);
4771 $data->icon = null;
4772 if ($this->icon) {
4773 $icon = $this->icon;
4774 if ($this->primary || !$this->actionmenu->will_be_enhanced()) {
4775 $attributes['title'] = $data->text;
4777 $data->icon = $icon ? $icon->export_for_pix() : null;
4780 $data->disabled = !empty($attributes['disabled']);
4781 unset($attributes['disabled']);
4783 $data->attributes = array_map(function($key, $value) {
4784 return [
4785 'name' => $key,
4786 'value' => $value
4788 }, array_keys($attributes), $attributes);
4790 return $data;
4795 * A primary action menu action
4797 * @package core
4798 * @category output
4799 * @copyright 2013 Sam Hemelryk
4800 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4802 class action_menu_link_primary extends action_menu_link {
4804 * Constructs the object.
4806 * @param moodle_url $url
4807 * @param pix_icon|null $icon
4808 * @param string $text
4809 * @param array $attributes
4811 public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) {
4812 parent::__construct($url, $icon, $text, true, $attributes);
4817 * A secondary action menu action
4819 * @package core
4820 * @category output
4821 * @copyright 2013 Sam Hemelryk
4822 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4824 class action_menu_link_secondary extends action_menu_link {
4826 * Constructs the object.
4828 * @param moodle_url $url
4829 * @param pix_icon|null $icon
4830 * @param string $text
4831 * @param array $attributes
4833 public function __construct(moodle_url $url, ?pix_icon $icon, $text, array $attributes = array()) {
4834 parent::__construct($url, $icon, $text, false, $attributes);
4839 * Represents a set of preferences groups.
4841 * @package core
4842 * @category output
4843 * @copyright 2015 Frédéric Massart - FMCorz.net
4844 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4846 class preferences_groups implements renderable {
4849 * Array of preferences_group.
4850 * @var array
4852 public $groups;
4855 * Constructor.
4856 * @param array $groups of preferences_group
4858 public function __construct($groups) {
4859 $this->groups = $groups;
4865 * Represents a group of preferences page link.
4867 * @package core
4868 * @category output
4869 * @copyright 2015 Frédéric Massart - FMCorz.net
4870 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4872 class preferences_group implements renderable {
4875 * Title of the group.
4876 * @var string
4878 public $title;
4881 * Array of navigation_node.
4882 * @var array
4884 public $nodes;
4887 * Constructor.
4888 * @param string $title The title.
4889 * @param array $nodes of navigation_node.
4891 public function __construct($title, $nodes) {
4892 $this->title = $title;
4893 $this->nodes = $nodes;
4898 * Progress bar class.
4900 * Manages the display of a progress bar.
4902 * To use this class.
4903 * - construct
4904 * - call create (or use the 3rd param to the constructor)
4905 * - call update or update_full() or update() repeatedly
4907 * @copyright 2008 jamiesensei
4908 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4909 * @package core
4910 * @category output
4912 class progress_bar implements renderable, templatable {
4913 /** @var string html id */
4914 private $html_id;
4915 /** @var int total width */
4916 private $width;
4917 /** @var int last percentage printed */
4918 private $percent = 0;
4919 /** @var int time when last printed */
4920 private $lastupdate = 0;
4921 /** @var int when did we start printing this */
4922 private $time_start = 0;
4925 * Constructor
4927 * Prints JS code if $autostart true.
4929 * @param string $htmlid The container ID.
4930 * @param int $width The suggested width.
4931 * @param bool $autostart Whether to start the progress bar right away.
4933 public function __construct($htmlid = '', $width = 500, $autostart = false) {
4934 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
4935 debugging('progress_bar used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', DEBUG_DEVELOPER);
4938 if (!empty($htmlid)) {
4939 $this->html_id = $htmlid;
4940 } else {
4941 $this->html_id = 'pbar_'.uniqid();
4944 $this->width = $width;
4946 if ($autostart) {
4947 $this->create();
4952 * Getter for ID
4953 * @return string id
4955 public function get_id() : string {
4956 return $this->html_id;
4960 * Create a new progress bar, this function will output html.
4962 * @return void Echo's output
4964 public function create() {
4965 global $OUTPUT;
4967 $this->time_start = microtime(true);
4969 flush();
4970 echo $OUTPUT->render($this);
4971 flush();
4975 * Update the progress bar.
4977 * @param int $percent From 1-100.
4978 * @param string $msg The message.
4979 * @return void Echo's output
4980 * @throws coding_exception
4982 private function _update($percent, $msg) {
4983 global $OUTPUT;
4985 if (empty($this->time_start)) {
4986 throw new coding_exception('You must call create() (or use the $autostart ' .
4987 'argument to the constructor) before you try updating the progress bar.');
4990 $estimate = $this->estimate($percent);
4992 if ($estimate === null) {
4993 // Always do the first and last updates.
4994 } else if ($estimate == 0) {
4995 // Always do the last updates.
4996 } else if ($this->lastupdate + 20 < time()) {
4997 // We must update otherwise browser would time out.
4998 } else if (round($this->percent, 2) === round($percent, 2)) {
4999 // No significant change, no need to update anything.
5000 return;
5003 $estimatemsg = '';
5004 if ($estimate != 0 && is_numeric($estimate)) {
5005 $estimatemsg = format_time(round($estimate));
5008 $this->percent = $percent;
5009 $this->lastupdate = microtime(true);
5011 echo $OUTPUT->render_progress_bar_update($this->html_id, sprintf("%.1f", $this->percent), $msg, $estimatemsg);
5012 flush();
5016 * Estimate how much time it is going to take.
5018 * @param int $pt From 1-100.
5019 * @return mixed Null (unknown), or int.
5021 private function estimate($pt) {
5022 if ($this->lastupdate == 0) {
5023 return null;
5025 if ($pt < 0.00001) {
5026 return null; // We do not know yet how long it will take.
5028 if ($pt > 99.99999) {
5029 return 0; // Nearly done, right?
5031 $consumed = microtime(true) - $this->time_start;
5032 if ($consumed < 0.001) {
5033 return null;
5036 return (100 - $pt) * ($consumed / $pt);
5040 * Update progress bar according percent.
5042 * @param int $percent From 1-100.
5043 * @param string $msg The message needed to be shown.
5045 public function update_full($percent, $msg) {
5046 $percent = max(min($percent, 100), 0);
5047 $this->_update($percent, $msg);
5051 * Update progress bar according the number of tasks.
5053 * @param int $cur Current task number.
5054 * @param int $total Total task number.
5055 * @param string $msg The message needed to be shown.
5057 public function update($cur, $total, $msg) {
5058 $percent = ($cur / $total) * 100;
5059 $this->update_full($percent, $msg);
5063 * Restart the progress bar.
5065 public function restart() {
5066 $this->percent = 0;
5067 $this->lastupdate = 0;
5068 $this->time_start = 0;
5072 * Export for template.
5074 * @param renderer_base $output The renderer.
5075 * @return array
5077 public function export_for_template(renderer_base $output) {
5078 return [
5079 'id' => $this->html_id,
5080 'width' => $this->width,