Merge branch 'install_35_STABLE' of https://git.in.moodle.com/amosbot/moodle-install...
[moodle.git] / lib / outputcomponents.php
blob115ed14bfd506ca4306237673098690158c6e41e
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 array List of mandatory fields in user record here. (do not include
154 * TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
156 protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'firstnamephonetic', 'lastnamephonetic',
157 'middlename', 'alternatename', 'imagealt', 'email');
160 * @var stdClass A user object with at least fields all columns specified
161 * in $fields array constant set.
163 public $user;
166 * @var int The course id. Used when constructing the link to the user's
167 * profile, page course id used if not specified.
169 public $courseid;
172 * @var bool Add course profile link to image
174 public $link = true;
177 * @var int Size in pixels. Special values are (true/1 = 100px) and
178 * (false/0 = 35px)
179 * for backward compatibility.
181 public $size = 35;
184 * @var bool Add non-blank alt-text to the image.
185 * Default true, set to false when image alt just duplicates text in screenreaders.
187 public $alttext = true;
190 * @var bool Whether or not to open the link in a popup window.
192 public $popup = false;
195 * @var string Image class attribute
197 public $class = 'userpicture';
200 * @var bool Whether to be visible to screen readers.
202 public $visibletoscreenreaders = true;
205 * @var bool Whether to include the fullname in the user picture link.
207 public $includefullname = false;
210 * User picture constructor.
212 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
213 * It is recommended to add also contextid of the user for performance reasons.
215 public function __construct(stdClass $user) {
216 global $DB;
218 if (empty($user->id)) {
219 throw new coding_exception('User id is required when printing user avatar image.');
222 // only touch the DB if we are missing data and complain loudly...
223 $needrec = false;
224 foreach (self::$fields as $field) {
225 if (!array_key_exists($field, $user)) {
226 $needrec = true;
227 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
228 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
229 break;
233 if ($needrec) {
234 $this->user = $DB->get_record('user', array('id'=>$user->id), self::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
253 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
254 if (!$tableprefix and !$extrafields and !$idalias) {
255 return implode(',', self::$fields);
257 if ($tableprefix) {
258 $tableprefix .= '.';
260 foreach (self::$fields as $field) {
261 if ($field === 'id' and $idalias and $idalias !== 'id') {
262 $fields[$field] = "$tableprefix$field AS $idalias";
263 } else {
264 if ($fieldprefix and $field !== 'id') {
265 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
266 } else {
267 $fields[$field] = "$tableprefix$field";
271 // add extra fields if not already there
272 if ($extrafields) {
273 foreach ($extrafields as $e) {
274 if ($e === 'id' or isset($fields[$e])) {
275 continue;
277 if ($fieldprefix) {
278 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
279 } else {
280 $fields[$e] = "$tableprefix$e";
284 return implode(',', $fields);
288 * Extract the aliased user fields from a given record
290 * Given a record that was previously obtained using {@link self::fields()} with aliases,
291 * this method extracts user related unaliased fields.
293 * @param stdClass $record containing user picture fields
294 * @param array $extrafields extra fields included in the $record
295 * @param string $idalias alias of the id field
296 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
297 * @return stdClass object with unaliased user fields
299 public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
301 if (empty($idalias)) {
302 $idalias = 'id';
305 $return = new stdClass();
307 foreach (self::$fields as $field) {
308 if ($field === 'id') {
309 if (property_exists($record, $idalias)) {
310 $return->id = $record->{$idalias};
312 } else {
313 if (property_exists($record, $fieldprefix.$field)) {
314 $return->{$field} = $record->{$fieldprefix.$field};
318 // add extra fields if not already there
319 if ($extrafields) {
320 foreach ($extrafields as $e) {
321 if ($e === 'id' or property_exists($return, $e)) {
322 continue;
324 $return->{$e} = $record->{$fieldprefix.$e};
328 return $return;
332 * Works out the URL for the users picture.
334 * This method is recommended as it avoids costly redirects of user pictures
335 * if requests are made for non-existent files etc.
337 * @param moodle_page $page
338 * @param renderer_base $renderer
339 * @return moodle_url
341 public function get_url(moodle_page $page, renderer_base $renderer = null) {
342 global $CFG;
344 if (is_null($renderer)) {
345 $renderer = $page->get_renderer('core');
348 // Sort out the filename and size. Size is only required for the gravatar
349 // implementation presently.
350 if (empty($this->size)) {
351 $filename = 'f2';
352 $size = 35;
353 } else if ($this->size === true or $this->size == 1) {
354 $filename = 'f1';
355 $size = 100;
356 } else if ($this->size > 100) {
357 $filename = 'f3';
358 $size = (int)$this->size;
359 } else if ($this->size >= 50) {
360 $filename = 'f1';
361 $size = (int)$this->size;
362 } else {
363 $filename = 'f2';
364 $size = (int)$this->size;
367 $defaulturl = $renderer->image_url('u/'.$filename); // default image
369 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
370 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
371 // Protect images if login required and not logged in;
372 // also if login is required for profile images and is not logged in or guest
373 // do not use require_login() because it is expensive and not suitable here anyway.
374 return $defaulturl;
377 // First try to detect deleted users - but do not read from database for performance reasons!
378 if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
379 // All deleted users should have email replaced by md5 hash,
380 // all active users are expected to have valid email.
381 return $defaulturl;
384 // Did the user upload a picture?
385 if ($this->user->picture > 0) {
386 if (!empty($this->user->contextid)) {
387 $contextid = $this->user->contextid;
388 } else {
389 $context = context_user::instance($this->user->id, IGNORE_MISSING);
390 if (!$context) {
391 // This must be an incorrectly deleted user, all other users have context.
392 return $defaulturl;
394 $contextid = $context->id;
397 $path = '/';
398 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
399 // We append the theme name to the file path if we have it so that
400 // in the circumstance that the profile picture is not available
401 // when the user actually requests it they still get the profile
402 // picture for the correct theme.
403 $path .= $page->theme->name.'/';
405 // Set the image URL to the URL for the uploaded file and return.
406 $url = moodle_url::make_pluginfile_url($contextid, 'user', 'icon', NULL, $path, $filename);
407 $url->param('rev', $this->user->picture);
408 return $url;
411 if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
412 // Normalise the size variable to acceptable bounds
413 if ($size < 1 || $size > 512) {
414 $size = 35;
416 // Hash the users email address
417 $md5 = md5(strtolower(trim($this->user->email)));
418 // Build a gravatar URL with what we know.
420 // Find the best default image URL we can (MDL-35669)
421 if (empty($CFG->gravatardefaulturl)) {
422 $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
423 if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
424 $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
425 } else {
426 $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
428 } else {
429 $gravatardefault = $CFG->gravatardefaulturl;
432 // If the currently requested page is https then we'll return an
433 // https gravatar page.
434 if (is_https()) {
435 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
436 } else {
437 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
441 return $defaulturl;
446 * Data structure representing a help icon.
448 * @copyright 2010 Petr Skoda (info@skodak.org)
449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
450 * @since Moodle 2.0
451 * @package core
452 * @category output
454 class help_icon implements renderable, templatable {
457 * @var string lang pack identifier (without the "_help" suffix),
458 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
459 * must exist.
461 public $identifier;
464 * @var string Component name, the same as in get_string()
466 public $component;
469 * @var string Extra descriptive text next to the icon
471 public $linktext = null;
474 * Constructor
476 * @param string $identifier string for help page title,
477 * string with _help suffix is used for the actual help text.
478 * string with _link suffix is used to create a link to further info (if it exists)
479 * @param string $component
481 public function __construct($identifier, $component) {
482 $this->identifier = $identifier;
483 $this->component = $component;
487 * Verifies that both help strings exists, shows debug warnings if not
489 public function diag_strings() {
490 $sm = get_string_manager();
491 if (!$sm->string_exists($this->identifier, $this->component)) {
492 debugging("Help title string does not exist: [$this->identifier, $this->component]");
494 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
495 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
500 * Export this data so it can be used as the context for a mustache template.
502 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
503 * @return array
505 public function export_for_template(renderer_base $output) {
506 global $CFG;
508 $title = get_string($this->identifier, $this->component);
510 if (empty($this->linktext)) {
511 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
512 } else {
513 $alt = get_string('helpwiththis');
516 $data = get_formatted_help_string($this->identifier, $this->component, false);
518 $data->alt = $alt;
519 $data->icon = (new pix_icon('help', $alt, 'core', ['class' => 'iconhelp']))->export_for_template($output);
520 $data->linktext = $this->linktext;
521 $data->title = get_string('helpprefix2', '', trim($title, ". \t"));
523 $options = [
524 'component' => $this->component,
525 'identifier' => $this->identifier,
526 'lang' => current_language()
529 // Debugging feature lets you display string identifier and component.
530 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
531 $options['strings'] = 1;
534 $data->url = (new moodle_url('/help.php', $options))->out(false);
535 $data->ltr = !right_to_left();
536 return $data;
542 * Data structure representing an icon font.
544 * @copyright 2016 Damyon Wiese
545 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
546 * @package core
547 * @category output
549 class pix_icon_font implements templatable {
552 * @var pix_icon $pixicon The original icon.
554 private $pixicon = null;
557 * @var string $key The mapped key.
559 private $key;
562 * @var bool $mapped The icon could not be mapped.
564 private $mapped;
567 * Constructor
569 * @param pix_icon $pixicon The original icon
571 public function __construct(pix_icon $pixicon) {
572 global $PAGE;
574 $this->pixicon = $pixicon;
575 $this->mapped = false;
576 $iconsystem = \core\output\icon_system::instance();
578 $this->key = $iconsystem->remap_icon_name($pixicon->pix, $pixicon->component);
579 if (!empty($this->key)) {
580 $this->mapped = true;
585 * Return true if this pix_icon was successfully mapped to an icon font.
587 * @return bool
589 public function is_mapped() {
590 return $this->mapped;
594 * Export this data so it can be used as the context for a mustache template.
596 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
597 * @return array
599 public function export_for_template(renderer_base $output) {
601 $pixdata = $this->pixicon->export_for_template($output);
603 $title = isset($this->pixicon->attributes['title']) ? $this->pixicon->attributes['title'] : '';
604 $alt = isset($this->pixicon->attributes['alt']) ? $this->pixicon->attributes['alt'] : '';
605 if (empty($title)) {
606 $title = $alt;
608 $data = array(
609 'extraclasses' => $pixdata['extraclasses'],
610 'title' => $title,
611 'alt' => $alt,
612 'key' => $this->key
615 return $data;
620 * Data structure representing an icon subtype.
622 * @copyright 2016 Damyon Wiese
623 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
624 * @package core
625 * @category output
627 class pix_icon_fontawesome extends pix_icon_font {
632 * Data structure representing an icon.
634 * @copyright 2010 Petr Skoda
635 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
636 * @since Moodle 2.0
637 * @package core
638 * @category output
640 class pix_icon implements renderable, templatable {
643 * @var string The icon name
645 var $pix;
648 * @var string The component the icon belongs to.
650 var $component;
653 * @var array An array of attributes to use on the icon
655 var $attributes = array();
658 * Constructor
660 * @param string $pix short icon name
661 * @param string $alt The alt text to use for the icon
662 * @param string $component component name
663 * @param array $attributes html attributes
665 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
666 global $PAGE;
668 $this->pix = $pix;
669 $this->component = $component;
670 $this->attributes = (array)$attributes;
672 if (empty($this->attributes['class'])) {
673 $this->attributes['class'] = '';
676 // Set an additional class for big icons so that they can be styled properly.
677 if (substr($pix, 0, 2) === 'b/') {
678 $this->attributes['class'] .= ' iconsize-big';
681 // If the alt is empty, don't place it in the attributes, otherwise it will override parent alt text.
682 if (!is_null($alt)) {
683 $this->attributes['alt'] = $alt;
685 // If there is no title, set it to the attribute.
686 if (!isset($this->attributes['title'])) {
687 $this->attributes['title'] = $this->attributes['alt'];
689 } else {
690 unset($this->attributes['alt']);
693 if (empty($this->attributes['title'])) {
694 // Remove the title attribute if empty, we probably want to use the parent node's title
695 // and some browsers might overwrite it with an empty title.
696 unset($this->attributes['title']);
699 // Hide icons from screen readers that have no alt.
700 if (empty($this->attributes['alt'])) {
701 $this->attributes['aria-hidden'] = 'true';
706 * Export this data so it can be used as the context for a mustache template.
708 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
709 * @return array
711 public function export_for_template(renderer_base $output) {
712 $attributes = $this->attributes;
713 $extraclasses = '';
715 foreach ($attributes as $key => $item) {
716 if ($key == 'class') {
717 $extraclasses = $item;
718 unset($attributes[$key]);
719 break;
723 $attributes['src'] = $output->image_url($this->pix, $this->component)->out(false);
724 $templatecontext = array();
725 foreach ($attributes as $name => $value) {
726 $templatecontext[] = array('name' => $name, 'value' => $value);
728 $title = isset($attributes['title']) ? $attributes['title'] : '';
729 if (empty($title)) {
730 $title = isset($attributes['alt']) ? $attributes['alt'] : '';
732 $data = array(
733 'attributes' => $templatecontext,
734 'extraclasses' => $extraclasses
737 return $data;
741 * Much simpler version of export that will produce the data required to render this pix with the
742 * pix helper in a mustache tag.
744 * @return array
746 public function export_for_pix() {
747 $title = isset($this->attributes['title']) ? $this->attributes['title'] : '';
748 if (empty($title)) {
749 $title = isset($this->attributes['alt']) ? $this->attributes['alt'] : '';
751 return [
752 'key' => $this->pix,
753 'component' => $this->component,
754 'title' => $title
760 * Data structure representing an activity icon.
762 * The difference is that activity icons will always render with the standard icon system (no font icons).
764 * @copyright 2017 Damyon Wiese
765 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
766 * @package core
768 class image_icon extends pix_icon {
772 * Data structure representing an emoticon image
774 * @copyright 2010 David Mudrak
775 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
776 * @since Moodle 2.0
777 * @package core
778 * @category output
780 class pix_emoticon extends pix_icon implements renderable {
783 * Constructor
784 * @param string $pix short icon name
785 * @param string $alt alternative text
786 * @param string $component emoticon image provider
787 * @param array $attributes explicit HTML attributes
789 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
790 if (empty($attributes['class'])) {
791 $attributes['class'] = 'emoticon';
793 parent::__construct($pix, $alt, $component, $attributes);
798 * Data structure representing a simple form with only one button.
800 * @copyright 2009 Petr Skoda
801 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
802 * @since Moodle 2.0
803 * @package core
804 * @category output
806 class single_button implements renderable {
809 * @var moodle_url Target url
811 public $url;
814 * @var string Button label
816 public $label;
819 * @var string Form submit method post or get
821 public $method = 'post';
824 * @var string Wrapping div class
826 public $class = 'singlebutton';
829 * @var bool True if button is primary button. Used for styling.
831 public $primary = false;
834 * @var bool True if button disabled, false if normal
836 public $disabled = false;
839 * @var string Button tooltip
841 public $tooltip = null;
844 * @var string Form id
846 public $formid;
849 * @var array List of attached actions
851 public $actions = array();
854 * @var array $params URL Params
856 public $params;
859 * @var string Action id
861 public $actionid;
864 * Constructor
865 * @param moodle_url $url
866 * @param string $label button text
867 * @param string $method get or post submit method
869 public function __construct(moodle_url $url, $label, $method='post', $primary=false) {
870 $this->url = clone($url);
871 $this->label = $label;
872 $this->method = $method;
873 $this->primary = $primary;
877 * Shortcut for adding a JS confirm dialog when the button is clicked.
878 * The message must be a yes/no question.
880 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
882 public function add_confirm_action($confirmmessage) {
883 $this->add_action(new confirm_action($confirmmessage));
887 * Add action to the button.
888 * @param component_action $action
890 public function add_action(component_action $action) {
891 $this->actions[] = $action;
895 * Export data.
897 * @param renderer_base $output Renderer.
898 * @return stdClass
900 public function export_for_template(renderer_base $output) {
901 $url = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
903 $data = new stdClass();
904 $data->id = html_writer::random_id('single_button');
905 $data->formid = $this->formid;
906 $data->method = $this->method;
907 $data->url = $url === '' ? '#' : $url;
908 $data->label = $this->label;
909 $data->classes = $this->class;
910 $data->disabled = $this->disabled;
911 $data->tooltip = $this->tooltip;
912 $data->primary = $this->primary;
914 // Form parameters.
915 $params = $this->url->params();
916 if ($this->method === 'post') {
917 $params['sesskey'] = sesskey();
919 $data->params = array_map(function($key) use ($params) {
920 return ['name' => $key, 'value' => $params[$key]];
921 }, array_keys($params));
923 // Button actions.
924 $actions = $this->actions;
925 $data->actions = array_map(function($action) use ($output) {
926 return $action->export_for_template($output);
927 }, $actions);
928 $data->hasactions = !empty($data->actions);
930 return $data;
936 * Simple form with just one select field that gets submitted automatically.
938 * If JS not enabled small go button is printed too.
940 * @copyright 2009 Petr Skoda
941 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
942 * @since Moodle 2.0
943 * @package core
944 * @category output
946 class single_select implements renderable, templatable {
949 * @var moodle_url Target url - includes hidden fields
951 var $url;
954 * @var string Name of the select element.
956 var $name;
959 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
960 * it is also possible to specify optgroup as complex label array ex.:
961 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
962 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
964 var $options;
967 * @var string Selected option
969 var $selected;
972 * @var array Nothing selected
974 var $nothing;
977 * @var array Extra select field attributes
979 var $attributes = array();
982 * @var string Button label
984 var $label = '';
987 * @var array Button label's attributes
989 var $labelattributes = array();
992 * @var string Form submit method post or get
994 var $method = 'get';
997 * @var string Wrapping div class
999 var $class = 'singleselect';
1002 * @var bool True if button disabled, false if normal
1004 var $disabled = false;
1007 * @var string Button tooltip
1009 var $tooltip = null;
1012 * @var string Form id
1014 var $formid = null;
1017 * @var help_icon The help icon for this element.
1019 var $helpicon = null;
1022 * Constructor
1023 * @param moodle_url $url form action target, includes hidden fields
1024 * @param string $name name of selection field - the changing parameter in url
1025 * @param array $options list of options
1026 * @param string $selected selected element
1027 * @param array $nothing
1028 * @param string $formid
1030 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1031 $this->url = $url;
1032 $this->name = $name;
1033 $this->options = $options;
1034 $this->selected = $selected;
1035 $this->nothing = $nothing;
1036 $this->formid = $formid;
1040 * Shortcut for adding a JS confirm dialog when the button is clicked.
1041 * The message must be a yes/no question.
1043 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
1045 public function add_confirm_action($confirmmessage) {
1046 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
1050 * Add action to the button.
1052 * @param component_action $action
1054 public function add_action(component_action $action) {
1055 $this->actions[] = $action;
1059 * Adds help icon.
1061 * @deprecated since Moodle 2.0
1063 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1064 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1068 * Adds help icon.
1070 * @param string $identifier The keyword that defines a help page
1071 * @param string $component
1073 public function set_help_icon($identifier, $component = 'moodle') {
1074 $this->helpicon = new help_icon($identifier, $component);
1078 * Sets select's label
1080 * @param string $label
1081 * @param array $attributes (optional)
1083 public function set_label($label, $attributes = array()) {
1084 $this->label = $label;
1085 $this->labelattributes = $attributes;
1090 * Export data.
1092 * @param renderer_base $output Renderer.
1093 * @return stdClass
1095 public function export_for_template(renderer_base $output) {
1096 $attributes = $this->attributes;
1098 $data = new stdClass();
1099 $data->name = $this->name;
1100 $data->method = $this->method;
1101 $data->action = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
1102 $data->classes = $this->class;
1103 $data->label = $this->label;
1104 $data->disabled = $this->disabled;
1105 $data->title = $this->tooltip;
1106 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('single_select_f');
1107 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('single_select');
1109 // Select element attributes.
1110 // Unset attributes that are already predefined in the template.
1111 unset($attributes['id']);
1112 unset($attributes['class']);
1113 unset($attributes['name']);
1114 unset($attributes['title']);
1115 unset($attributes['disabled']);
1117 // Map the attributes.
1118 $data->attributes = array_map(function($key) use ($attributes) {
1119 return ['name' => $key, 'value' => $attributes[$key]];
1120 }, array_keys($attributes));
1122 // Form parameters.
1123 $params = $this->url->params();
1124 if ($this->method === 'post') {
1125 $params['sesskey'] = sesskey();
1127 $data->params = array_map(function($key) use ($params) {
1128 return ['name' => $key, 'value' => $params[$key]];
1129 }, array_keys($params));
1131 // Select options.
1132 $hasnothing = false;
1133 if (is_string($this->nothing) && $this->nothing !== '') {
1134 $nothing = ['' => $this->nothing];
1135 $hasnothing = true;
1136 $nothingkey = '';
1137 } else if (is_array($this->nothing)) {
1138 $nothingvalue = reset($this->nothing);
1139 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1140 $nothing = [key($this->nothing) => get_string('choosedots')];
1141 } else {
1142 $nothing = $this->nothing;
1144 $hasnothing = true;
1145 $nothingkey = key($this->nothing);
1147 if ($hasnothing) {
1148 $options = $nothing + $this->options;
1149 } else {
1150 $options = $this->options;
1153 foreach ($options as $value => $name) {
1154 if (is_array($options[$value])) {
1155 foreach ($options[$value] as $optgroupname => $optgroupvalues) {
1156 $sublist = [];
1157 foreach ($optgroupvalues as $optvalue => $optname) {
1158 $option = [
1159 'value' => $optvalue,
1160 'name' => $optname,
1161 'selected' => strval($this->selected) === strval($optvalue),
1164 if ($hasnothing && $nothingkey === $optvalue) {
1165 $option['ignore'] = 'data-ignore';
1168 $sublist[] = $option;
1170 $data->options[] = [
1171 'name' => $optgroupname,
1172 'optgroup' => true,
1173 'options' => $sublist
1176 } else {
1177 $option = [
1178 'value' => $value,
1179 'name' => $options[$value],
1180 'selected' => strval($this->selected) === strval($value),
1181 'optgroup' => false
1184 if ($hasnothing && $nothingkey === $value) {
1185 $option['ignore'] = 'data-ignore';
1188 $data->options[] = $option;
1192 // Label attributes.
1193 $data->labelattributes = [];
1194 // Unset label attributes that are already in the template.
1195 unset($this->labelattributes['for']);
1196 // Map the label attributes.
1197 foreach ($this->labelattributes as $key => $value) {
1198 $data->labelattributes[] = ['name' => $key, 'value' => $value];
1201 // Help icon.
1202 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1204 return $data;
1209 * Simple URL selection widget description.
1211 * @copyright 2009 Petr Skoda
1212 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1213 * @since Moodle 2.0
1214 * @package core
1215 * @category output
1217 class url_select implements renderable, templatable {
1219 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
1220 * it is also possible to specify optgroup as complex label array ex.:
1221 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1222 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1224 var $urls;
1227 * @var string Selected option
1229 var $selected;
1232 * @var array Nothing selected
1234 var $nothing;
1237 * @var array Extra select field attributes
1239 var $attributes = array();
1242 * @var string Button label
1244 var $label = '';
1247 * @var array Button label's attributes
1249 var $labelattributes = array();
1252 * @var string Wrapping div class
1254 var $class = 'urlselect';
1257 * @var bool True if button disabled, false if normal
1259 var $disabled = false;
1262 * @var string Button tooltip
1264 var $tooltip = null;
1267 * @var string Form id
1269 var $formid = null;
1272 * @var help_icon The help icon for this element.
1274 var $helpicon = null;
1277 * @var string If set, makes button visible with given name for button
1279 var $showbutton = null;
1282 * Constructor
1283 * @param array $urls list of options
1284 * @param string $selected selected element
1285 * @param array $nothing
1286 * @param string $formid
1287 * @param string $showbutton Set to text of button if it should be visible
1288 * or null if it should be hidden (hidden version always has text 'go')
1290 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
1291 $this->urls = $urls;
1292 $this->selected = $selected;
1293 $this->nothing = $nothing;
1294 $this->formid = $formid;
1295 $this->showbutton = $showbutton;
1299 * Adds help icon.
1301 * @deprecated since Moodle 2.0
1303 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1304 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1308 * Adds help icon.
1310 * @param string $identifier The keyword that defines a help page
1311 * @param string $component
1313 public function set_help_icon($identifier, $component = 'moodle') {
1314 $this->helpicon = new help_icon($identifier, $component);
1318 * Sets select's label
1320 * @param string $label
1321 * @param array $attributes (optional)
1323 public function set_label($label, $attributes = array()) {
1324 $this->label = $label;
1325 $this->labelattributes = $attributes;
1329 * Clean a URL.
1331 * @param string $value The URL.
1332 * @return The cleaned URL.
1334 protected function clean_url($value) {
1335 global $CFG;
1337 if (empty($value)) {
1338 // Nothing.
1340 } else if (strpos($value, $CFG->wwwroot . '/') === 0) {
1341 $value = str_replace($CFG->wwwroot, '', $value);
1343 } else if (strpos($value, '/') !== 0) {
1344 debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER);
1347 return $value;
1351 * Flatten the options for Mustache.
1353 * This also cleans the URLs.
1355 * @param array $options The options.
1356 * @param array $nothing The nothing option.
1357 * @return array
1359 protected function flatten_options($options, $nothing) {
1360 $flattened = [];
1362 foreach ($options as $value => $option) {
1363 if (is_array($option)) {
1364 foreach ($option as $groupname => $optoptions) {
1365 if (!isset($flattened[$groupname])) {
1366 $flattened[$groupname] = [
1367 'name' => $groupname,
1368 'isgroup' => true,
1369 'options' => []
1372 foreach ($optoptions as $optvalue => $optoption) {
1373 $cleanedvalue = $this->clean_url($optvalue);
1374 $flattened[$groupname]['options'][$cleanedvalue] = [
1375 'name' => $optoption,
1376 'value' => $cleanedvalue,
1377 'selected' => $this->selected == $optvalue,
1382 } else {
1383 $cleanedvalue = $this->clean_url($value);
1384 $flattened[$cleanedvalue] = [
1385 'name' => $option,
1386 'value' => $cleanedvalue,
1387 'selected' => $this->selected == $value,
1392 if (!empty($nothing)) {
1393 $value = key($nothing);
1394 $name = reset($nothing);
1395 $flattened = [
1396 $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value]
1397 ] + $flattened;
1400 // Make non-associative array.
1401 foreach ($flattened as $key => $value) {
1402 if (!empty($value['options'])) {
1403 $flattened[$key]['options'] = array_values($value['options']);
1406 $flattened = array_values($flattened);
1408 return $flattened;
1412 * Export for template.
1414 * @param renderer_base $output Renderer.
1415 * @return stdClass
1417 public function export_for_template(renderer_base $output) {
1418 $attributes = $this->attributes;
1420 $data = new stdClass();
1421 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('url_select_f');
1422 $data->classes = $this->class;
1423 $data->label = $this->label;
1424 $data->disabled = $this->disabled;
1425 $data->title = $this->tooltip;
1426 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('url_select');
1427 $data->sesskey = sesskey();
1428 $data->action = (new moodle_url('/course/jumpto.php'))->out(false);
1430 // Remove attributes passed as property directly.
1431 unset($attributes['class']);
1432 unset($attributes['id']);
1433 unset($attributes['name']);
1434 unset($attributes['title']);
1435 unset($attributes['disabled']);
1437 $data->showbutton = $this->showbutton;
1439 // Select options.
1440 $nothing = false;
1441 if (is_string($this->nothing) && $this->nothing !== '') {
1442 $nothing = ['' => $this->nothing];
1443 } else if (is_array($this->nothing)) {
1444 $nothingvalue = reset($this->nothing);
1445 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1446 $nothing = [key($this->nothing) => get_string('choosedots')];
1447 } else {
1448 $nothing = $this->nothing;
1451 $data->options = $this->flatten_options($this->urls, $nothing);
1453 // Label attributes.
1454 $data->labelattributes = [];
1455 // Unset label attributes that are already in the template.
1456 unset($this->labelattributes['for']);
1457 // Map the label attributes.
1458 foreach ($this->labelattributes as $key => $value) {
1459 $data->labelattributes[] = ['name' => $key, 'value' => $value];
1462 // Help icon.
1463 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1465 // Finally all the remaining attributes.
1466 $data->attributes = [];
1467 foreach ($attributes as $key => $value) {
1468 $data->attributes[] = ['name' => $key, 'value' => $value];
1471 return $data;
1476 * Data structure describing html link with special action attached.
1478 * @copyright 2010 Petr Skoda
1479 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1480 * @since Moodle 2.0
1481 * @package core
1482 * @category output
1484 class action_link implements renderable {
1487 * @var moodle_url Href url
1489 public $url;
1492 * @var string Link text HTML fragment
1494 public $text;
1497 * @var array HTML attributes
1499 public $attributes;
1502 * @var array List of actions attached to link
1504 public $actions;
1507 * @var pix_icon Optional pix icon to render with the link
1509 public $icon;
1512 * Constructor
1513 * @param moodle_url $url
1514 * @param string $text HTML fragment
1515 * @param component_action $action
1516 * @param array $attributes associative array of html link attributes + disabled
1517 * @param pix_icon $icon optional pix_icon to render with the link text
1519 public function __construct(moodle_url $url,
1520 $text,
1521 component_action $action=null,
1522 array $attributes=null,
1523 pix_icon $icon=null) {
1524 $this->url = clone($url);
1525 $this->text = $text;
1526 $this->attributes = (array)$attributes;
1527 if ($action) {
1528 $this->add_action($action);
1530 $this->icon = $icon;
1534 * Add action to the link.
1536 * @param component_action $action
1538 public function add_action(component_action $action) {
1539 $this->actions[] = $action;
1543 * Adds a CSS class to this action link object
1544 * @param string $class
1546 public function add_class($class) {
1547 if (empty($this->attributes['class'])) {
1548 $this->attributes['class'] = $class;
1549 } else {
1550 $this->attributes['class'] .= ' ' . $class;
1555 * Returns true if the specified class has been added to this link.
1556 * @param string $class
1557 * @return bool
1559 public function has_class($class) {
1560 return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
1564 * Return the rendered HTML for the icon. Useful for rendering action links in a template.
1565 * @return string
1567 public function get_icon_html() {
1568 global $OUTPUT;
1569 if (!$this->icon) {
1570 return '';
1572 return $OUTPUT->render($this->icon);
1576 * Export for template.
1578 * @param renderer_base $output The renderer.
1579 * @return stdClass
1581 public function export_for_template(renderer_base $output) {
1582 $data = new stdClass();
1583 $attributes = $this->attributes;
1585 if (empty($attributes['id'])) {
1586 $attributes['id'] = html_writer::random_id('action_link');
1588 $data->id = $attributes['id'];
1589 unset($attributes['id']);
1591 $data->disabled = !empty($attributes['disabled']);
1592 unset($attributes['disabled']);
1594 $data->text = $this->text instanceof renderable ? $output->render($this->text) : (string) $this->text;
1595 $data->url = $this->url ? $this->url->out(false) : '';
1596 $data->icon = $this->icon ? $this->icon->export_for_pix() : null;
1597 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
1598 unset($attributes['class']);
1600 $data->attributes = array_map(function($key, $value) {
1601 return [
1602 'name' => $key,
1603 'value' => $value
1605 }, array_keys($attributes), $attributes);
1607 $data->actions = array_map(function($action) use ($output) {
1608 return $action->export_for_template($output);
1609 }, !empty($this->actions) ? $this->actions : []);
1610 $data->hasactions = !empty($this->actions);
1612 return $data;
1617 * Simple html output class
1619 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1620 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1621 * @since Moodle 2.0
1622 * @package core
1623 * @category output
1625 class html_writer {
1628 * Outputs a tag with attributes and contents
1630 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1631 * @param string $contents What goes between the opening and closing tags
1632 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1633 * @return string HTML fragment
1635 public static function tag($tagname, $contents, array $attributes = null) {
1636 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1640 * Outputs an opening tag with attributes
1642 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1643 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1644 * @return string HTML fragment
1646 public static function start_tag($tagname, array $attributes = null) {
1647 return '<' . $tagname . self::attributes($attributes) . '>';
1651 * Outputs a closing tag
1653 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1654 * @return string HTML fragment
1656 public static function end_tag($tagname) {
1657 return '</' . $tagname . '>';
1661 * Outputs an empty tag with attributes
1663 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1664 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1665 * @return string HTML fragment
1667 public static function empty_tag($tagname, array $attributes = null) {
1668 return '<' . $tagname . self::attributes($attributes) . ' />';
1672 * Outputs a tag, but only if the contents are not empty
1674 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1675 * @param string $contents What goes between the opening and closing tags
1676 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1677 * @return string HTML fragment
1679 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1680 if ($contents === '' || is_null($contents)) {
1681 return '';
1683 return self::tag($tagname, $contents, $attributes);
1687 * Outputs a HTML attribute and value
1689 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1690 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1691 * @return string HTML fragment
1693 public static function attribute($name, $value) {
1694 if ($value instanceof moodle_url) {
1695 return ' ' . $name . '="' . $value->out() . '"';
1698 // special case, we do not want these in output
1699 if ($value === null) {
1700 return '';
1703 // no sloppy trimming here!
1704 return ' ' . $name . '="' . s($value) . '"';
1708 * Outputs a list of HTML attributes and values
1710 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1711 * The values will be escaped with {@link s()}
1712 * @return string HTML fragment
1714 public static function attributes(array $attributes = null) {
1715 $attributes = (array)$attributes;
1716 $output = '';
1717 foreach ($attributes as $name => $value) {
1718 $output .= self::attribute($name, $value);
1720 return $output;
1724 * Generates a simple image tag with attributes.
1726 * @param string $src The source of image
1727 * @param string $alt The alternate text for image
1728 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1729 * @return string HTML fragment
1731 public static function img($src, $alt, array $attributes = null) {
1732 $attributes = (array)$attributes;
1733 $attributes['src'] = $src;
1734 $attributes['alt'] = $alt;
1736 return self::empty_tag('img', $attributes);
1740 * Generates random html element id.
1742 * @staticvar int $counter
1743 * @staticvar type $uniq
1744 * @param string $base A string fragment that will be included in the random ID.
1745 * @return string A unique ID
1747 public static function random_id($base='random') {
1748 static $counter = 0;
1749 static $uniq;
1751 if (!isset($uniq)) {
1752 $uniq = uniqid();
1755 $counter++;
1756 return $base.$uniq.$counter;
1760 * Generates a simple html link
1762 * @param string|moodle_url $url The URL
1763 * @param string $text The text
1764 * @param array $attributes HTML attributes
1765 * @return string HTML fragment
1767 public static function link($url, $text, array $attributes = null) {
1768 $attributes = (array)$attributes;
1769 $attributes['href'] = $url;
1770 return self::tag('a', $text, $attributes);
1774 * Generates a simple checkbox with optional label
1776 * @param string $name The name of the checkbox
1777 * @param string $value The value of the checkbox
1778 * @param bool $checked Whether the checkbox is checked
1779 * @param string $label The label for the checkbox
1780 * @param array $attributes Any attributes to apply to the checkbox
1781 * @return string html fragment
1783 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1784 $attributes = (array)$attributes;
1785 $output = '';
1787 if ($label !== '' and !is_null($label)) {
1788 if (empty($attributes['id'])) {
1789 $attributes['id'] = self::random_id('checkbox_');
1792 $attributes['type'] = 'checkbox';
1793 $attributes['value'] = $value;
1794 $attributes['name'] = $name;
1795 $attributes['checked'] = $checked ? 'checked' : null;
1797 $output .= self::empty_tag('input', $attributes);
1799 if ($label !== '' and !is_null($label)) {
1800 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1803 return $output;
1807 * Generates a simple select yes/no form field
1809 * @param string $name name of select element
1810 * @param bool $selected
1811 * @param array $attributes - html select element attributes
1812 * @return string HTML fragment
1814 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1815 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1816 return self::select($options, $name, $selected, null, $attributes);
1820 * Generates a simple select form field
1822 * @param array $options associative array value=>label ex.:
1823 * array(1=>'One, 2=>Two)
1824 * it is also possible to specify optgroup as complex label array ex.:
1825 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1826 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1827 * @param string $name name of select element
1828 * @param string|array $selected value or array of values depending on multiple attribute
1829 * @param array|bool $nothing add nothing selected option, or false of not added
1830 * @param array $attributes html select element attributes
1831 * @return string HTML fragment
1833 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1834 $attributes = (array)$attributes;
1835 if (is_array($nothing)) {
1836 foreach ($nothing as $k=>$v) {
1837 if ($v === 'choose' or $v === 'choosedots') {
1838 $nothing[$k] = get_string('choosedots');
1841 $options = $nothing + $options; // keep keys, do not override
1843 } else if (is_string($nothing) and $nothing !== '') {
1844 // BC
1845 $options = array(''=>$nothing) + $options;
1848 // we may accept more values if multiple attribute specified
1849 $selected = (array)$selected;
1850 foreach ($selected as $k=>$v) {
1851 $selected[$k] = (string)$v;
1854 if (!isset($attributes['id'])) {
1855 $id = 'menu'.$name;
1856 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1857 $id = str_replace('[', '', $id);
1858 $id = str_replace(']', '', $id);
1859 $attributes['id'] = $id;
1862 if (!isset($attributes['class'])) {
1863 $class = 'menu'.$name;
1864 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1865 $class = str_replace('[', '', $class);
1866 $class = str_replace(']', '', $class);
1867 $attributes['class'] = $class;
1869 $attributes['class'] = 'select custom-select ' . $attributes['class']; // Add 'select' selector always.
1871 $attributes['name'] = $name;
1873 if (!empty($attributes['disabled'])) {
1874 $attributes['disabled'] = 'disabled';
1875 } else {
1876 unset($attributes['disabled']);
1879 $output = '';
1880 foreach ($options as $value=>$label) {
1881 if (is_array($label)) {
1882 // ignore key, it just has to be unique
1883 $output .= self::select_optgroup(key($label), current($label), $selected);
1884 } else {
1885 $output .= self::select_option($label, $value, $selected);
1888 return self::tag('select', $output, $attributes);
1892 * Returns HTML to display a select box option.
1894 * @param string $label The label to display as the option.
1895 * @param string|int $value The value the option represents
1896 * @param array $selected An array of selected options
1897 * @return string HTML fragment
1899 private static function select_option($label, $value, array $selected) {
1900 $attributes = array();
1901 $value = (string)$value;
1902 if (in_array($value, $selected, true)) {
1903 $attributes['selected'] = 'selected';
1905 $attributes['value'] = $value;
1906 return self::tag('option', $label, $attributes);
1910 * Returns HTML to display a select box option group.
1912 * @param string $groupname The label to use for the group
1913 * @param array $options The options in the group
1914 * @param array $selected An array of selected values.
1915 * @return string HTML fragment.
1917 private static function select_optgroup($groupname, $options, array $selected) {
1918 if (empty($options)) {
1919 return '';
1921 $attributes = array('label'=>$groupname);
1922 $output = '';
1923 foreach ($options as $value=>$label) {
1924 $output .= self::select_option($label, $value, $selected);
1926 return self::tag('optgroup', $output, $attributes);
1930 * This is a shortcut for making an hour selector menu.
1932 * @param string $type The type of selector (years, months, days, hours, minutes)
1933 * @param string $name fieldname
1934 * @param int $currenttime A default timestamp in GMT
1935 * @param int $step minute spacing
1936 * @param array $attributes - html select element attributes
1937 * @return HTML fragment
1939 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1940 global $OUTPUT;
1942 if (!$currenttime) {
1943 $currenttime = time();
1945 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1946 $currentdate = $calendartype->timestamp_to_date_array($currenttime);
1947 $userdatetype = $type;
1948 $timeunits = array();
1950 switch ($type) {
1951 case 'years':
1952 $timeunits = $calendartype->get_years();
1953 $userdatetype = 'year';
1954 break;
1955 case 'months':
1956 $timeunits = $calendartype->get_months();
1957 $userdatetype = 'month';
1958 $currentdate['month'] = (int)$currentdate['mon'];
1959 break;
1960 case 'days':
1961 $timeunits = $calendartype->get_days();
1962 $userdatetype = 'mday';
1963 break;
1964 case 'hours':
1965 for ($i=0; $i<=23; $i++) {
1966 $timeunits[$i] = sprintf("%02d",$i);
1968 break;
1969 case 'minutes':
1970 if ($step != 1) {
1971 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1974 for ($i=0; $i<=59; $i+=$step) {
1975 $timeunits[$i] = sprintf("%02d",$i);
1977 break;
1978 default:
1979 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1982 $attributes = (array) $attributes;
1983 $data = (object) [
1984 'name' => $name,
1985 'id' => !empty($attributes['id']) ? $attributes['id'] : self::random_id('ts_'),
1986 'label' => get_string(substr($type, 0, -1), 'form'),
1987 'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) {
1988 return [
1989 'name' => $timeunits[$value],
1990 'value' => $value,
1991 'selected' => $currentdate[$userdatetype] == $value
1993 }, array_keys($timeunits)),
1996 unset($attributes['id']);
1997 unset($attributes['name']);
1998 $data->attributes = array_map(function($name) use ($attributes) {
1999 return [
2000 'name' => $name,
2001 'value' => $attributes[$name]
2003 }, array_keys($attributes));
2005 return $OUTPUT->render_from_template('core/select_time', $data);
2009 * Shortcut for quick making of lists
2011 * Note: 'list' is a reserved keyword ;-)
2013 * @param array $items
2014 * @param array $attributes
2015 * @param string $tag ul or ol
2016 * @return string
2018 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
2019 $output = html_writer::start_tag($tag, $attributes)."\n";
2020 foreach ($items as $item) {
2021 $output .= html_writer::tag('li', $item)."\n";
2023 $output .= html_writer::end_tag($tag);
2024 return $output;
2028 * Returns hidden input fields created from url parameters.
2030 * @param moodle_url $url
2031 * @param array $exclude list of excluded parameters
2032 * @return string HTML fragment
2034 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
2035 $exclude = (array)$exclude;
2036 $params = $url->params();
2037 foreach ($exclude as $key) {
2038 unset($params[$key]);
2041 $output = '';
2042 foreach ($params as $key => $value) {
2043 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
2044 $output .= self::empty_tag('input', $attributes)."\n";
2046 return $output;
2050 * Generate a script tag containing the the specified code.
2052 * @param string $jscode the JavaScript code
2053 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
2054 * @return string HTML, the code wrapped in <script> tags.
2056 public static function script($jscode, $url=null) {
2057 if ($jscode) {
2058 $attributes = array('type'=>'text/javascript');
2059 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
2061 } else if ($url) {
2062 $attributes = array('type'=>'text/javascript', 'src'=>$url);
2063 return self::tag('script', '', $attributes) . "\n";
2065 } else {
2066 return '';
2071 * Renders HTML table
2073 * This method may modify the passed instance by adding some default properties if they are not set yet.
2074 * If this is not what you want, you should make a full clone of your data before passing them to this
2075 * method. In most cases this is not an issue at all so we do not clone by default for performance
2076 * and memory consumption reasons.
2078 * @param html_table $table data to be rendered
2079 * @return string HTML code
2081 public static function table(html_table $table) {
2082 // prepare table data and populate missing properties with reasonable defaults
2083 if (!empty($table->align)) {
2084 foreach ($table->align as $key => $aa) {
2085 if ($aa) {
2086 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
2087 } else {
2088 $table->align[$key] = null;
2092 if (!empty($table->size)) {
2093 foreach ($table->size as $key => $ss) {
2094 if ($ss) {
2095 $table->size[$key] = 'width:'. $ss .';';
2096 } else {
2097 $table->size[$key] = null;
2101 if (!empty($table->wrap)) {
2102 foreach ($table->wrap as $key => $ww) {
2103 if ($ww) {
2104 $table->wrap[$key] = 'white-space:nowrap;';
2105 } else {
2106 $table->wrap[$key] = '';
2110 if (!empty($table->head)) {
2111 foreach ($table->head as $key => $val) {
2112 if (!isset($table->align[$key])) {
2113 $table->align[$key] = null;
2115 if (!isset($table->size[$key])) {
2116 $table->size[$key] = null;
2118 if (!isset($table->wrap[$key])) {
2119 $table->wrap[$key] = null;
2124 if (empty($table->attributes['class'])) {
2125 $table->attributes['class'] = 'generaltable';
2127 if (!empty($table->tablealign)) {
2128 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
2131 // explicitly assigned properties override those defined via $table->attributes
2132 $table->attributes['class'] = trim($table->attributes['class']);
2133 $attributes = array_merge($table->attributes, array(
2134 'id' => $table->id,
2135 'width' => $table->width,
2136 'summary' => $table->summary,
2137 'cellpadding' => $table->cellpadding,
2138 'cellspacing' => $table->cellspacing,
2140 $output = html_writer::start_tag('table', $attributes) . "\n";
2142 $countcols = 0;
2144 // Output a caption if present.
2145 if (!empty($table->caption)) {
2146 $captionattributes = array();
2147 if ($table->captionhide) {
2148 $captionattributes['class'] = 'accesshide';
2150 $output .= html_writer::tag(
2151 'caption',
2152 $table->caption,
2153 $captionattributes
2157 if (!empty($table->head)) {
2158 $countcols = count($table->head);
2160 $output .= html_writer::start_tag('thead', array()) . "\n";
2161 $output .= html_writer::start_tag('tr', array()) . "\n";
2162 $keys = array_keys($table->head);
2163 $lastkey = end($keys);
2165 foreach ($table->head as $key => $heading) {
2166 // Convert plain string headings into html_table_cell objects
2167 if (!($heading instanceof html_table_cell)) {
2168 $headingtext = $heading;
2169 $heading = new html_table_cell();
2170 $heading->text = $headingtext;
2171 $heading->header = true;
2174 if ($heading->header !== false) {
2175 $heading->header = true;
2178 if ($heading->header && empty($heading->scope)) {
2179 $heading->scope = 'col';
2182 $heading->attributes['class'] .= ' header c' . $key;
2183 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
2184 $heading->colspan = $table->headspan[$key];
2185 $countcols += $table->headspan[$key] - 1;
2188 if ($key == $lastkey) {
2189 $heading->attributes['class'] .= ' lastcol';
2191 if (isset($table->colclasses[$key])) {
2192 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
2194 $heading->attributes['class'] = trim($heading->attributes['class']);
2195 $attributes = array_merge($heading->attributes, array(
2196 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
2197 'scope' => $heading->scope,
2198 'colspan' => $heading->colspan,
2201 $tagtype = 'td';
2202 if ($heading->header === true) {
2203 $tagtype = 'th';
2205 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
2207 $output .= html_writer::end_tag('tr') . "\n";
2208 $output .= html_writer::end_tag('thead') . "\n";
2210 if (empty($table->data)) {
2211 // For valid XHTML strict every table must contain either a valid tr
2212 // or a valid tbody... both of which must contain a valid td
2213 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
2214 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
2215 $output .= html_writer::end_tag('tbody');
2219 if (!empty($table->data)) {
2220 $keys = array_keys($table->data);
2221 $lastrowkey = end($keys);
2222 $output .= html_writer::start_tag('tbody', array());
2224 foreach ($table->data as $key => $row) {
2225 if (($row === 'hr') && ($countcols)) {
2226 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
2227 } else {
2228 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
2229 if (!($row instanceof html_table_row)) {
2230 $newrow = new html_table_row();
2232 foreach ($row as $cell) {
2233 if (!($cell instanceof html_table_cell)) {
2234 $cell = new html_table_cell($cell);
2236 $newrow->cells[] = $cell;
2238 $row = $newrow;
2241 if (isset($table->rowclasses[$key])) {
2242 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
2245 if ($key == $lastrowkey) {
2246 $row->attributes['class'] .= ' lastrow';
2249 // Explicitly assigned properties should override those defined in the attributes.
2250 $row->attributes['class'] = trim($row->attributes['class']);
2251 $trattributes = array_merge($row->attributes, array(
2252 'id' => $row->id,
2253 'style' => $row->style,
2255 $output .= html_writer::start_tag('tr', $trattributes) . "\n";
2256 $keys2 = array_keys($row->cells);
2257 $lastkey = end($keys2);
2259 $gotlastkey = false; //flag for sanity checking
2260 foreach ($row->cells as $key => $cell) {
2261 if ($gotlastkey) {
2262 //This should never happen. Why do we have a cell after the last cell?
2263 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
2266 if (!($cell instanceof html_table_cell)) {
2267 $mycell = new html_table_cell();
2268 $mycell->text = $cell;
2269 $cell = $mycell;
2272 if (($cell->header === true) && empty($cell->scope)) {
2273 $cell->scope = 'row';
2276 if (isset($table->colclasses[$key])) {
2277 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
2280 $cell->attributes['class'] .= ' cell c' . $key;
2281 if ($key == $lastkey) {
2282 $cell->attributes['class'] .= ' lastcol';
2283 $gotlastkey = true;
2285 $tdstyle = '';
2286 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
2287 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
2288 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
2289 $cell->attributes['class'] = trim($cell->attributes['class']);
2290 $tdattributes = array_merge($cell->attributes, array(
2291 'style' => $tdstyle . $cell->style,
2292 'colspan' => $cell->colspan,
2293 'rowspan' => $cell->rowspan,
2294 'id' => $cell->id,
2295 'abbr' => $cell->abbr,
2296 'scope' => $cell->scope,
2298 $tagtype = 'td';
2299 if ($cell->header === true) {
2300 $tagtype = 'th';
2302 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
2305 $output .= html_writer::end_tag('tr') . "\n";
2307 $output .= html_writer::end_tag('tbody') . "\n";
2309 $output .= html_writer::end_tag('table') . "\n";
2311 return $output;
2315 * Renders form element label
2317 * By default, the label is suffixed with a label separator defined in the
2318 * current language pack (colon by default in the English lang pack).
2319 * Adding the colon can be explicitly disabled if needed. Label separators
2320 * are put outside the label tag itself so they are not read by
2321 * screenreaders (accessibility).
2323 * Parameter $for explicitly associates the label with a form control. When
2324 * set, the value of this attribute must be the same as the value of
2325 * the id attribute of the form control in the same document. When null,
2326 * the label being defined is associated with the control inside the label
2327 * element.
2329 * @param string $text content of the label tag
2330 * @param string|null $for id of the element this label is associated with, null for no association
2331 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
2332 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
2333 * @return string HTML of the label element
2335 public static function label($text, $for, $colonize = true, array $attributes=array()) {
2336 if (!is_null($for)) {
2337 $attributes = array_merge($attributes, array('for' => $for));
2339 $text = trim($text);
2340 $label = self::tag('label', $text, $attributes);
2342 // TODO MDL-12192 $colonize disabled for now yet
2343 // if (!empty($text) and $colonize) {
2344 // // the $text may end with the colon already, though it is bad string definition style
2345 // $colon = get_string('labelsep', 'langconfig');
2346 // if (!empty($colon)) {
2347 // $trimmed = trim($colon);
2348 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
2349 // //debugging('The label text should not end with colon or other label separator,
2350 // // please fix the string definition.', DEBUG_DEVELOPER);
2351 // } else {
2352 // $label .= $colon;
2353 // }
2354 // }
2355 // }
2357 return $label;
2361 * Combines a class parameter with other attributes. Aids in code reduction
2362 * because the class parameter is very frequently used.
2364 * If the class attribute is specified both in the attributes and in the
2365 * class parameter, the two values are combined with a space between.
2367 * @param string $class Optional CSS class (or classes as space-separated list)
2368 * @param array $attributes Optional other attributes as array
2369 * @return array Attributes (or null if still none)
2371 private static function add_class($class = '', array $attributes = null) {
2372 if ($class !== '') {
2373 $classattribute = array('class' => $class);
2374 if ($attributes) {
2375 if (array_key_exists('class', $attributes)) {
2376 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
2377 } else {
2378 $attributes = $classattribute + $attributes;
2380 } else {
2381 $attributes = $classattribute;
2384 return $attributes;
2388 * Creates a <div> tag. (Shortcut function.)
2390 * @param string $content HTML content of tag
2391 * @param string $class Optional CSS class (or classes as space-separated list)
2392 * @param array $attributes Optional other attributes as array
2393 * @return string HTML code for div
2395 public static function div($content, $class = '', array $attributes = null) {
2396 return self::tag('div', $content, self::add_class($class, $attributes));
2400 * Starts a <div> tag. (Shortcut function.)
2402 * @param string $class Optional CSS class (or classes as space-separated list)
2403 * @param array $attributes Optional other attributes as array
2404 * @return string HTML code for open div tag
2406 public static function start_div($class = '', array $attributes = null) {
2407 return self::start_tag('div', self::add_class($class, $attributes));
2411 * Ends a <div> tag. (Shortcut function.)
2413 * @return string HTML code for close div tag
2415 public static function end_div() {
2416 return self::end_tag('div');
2420 * Creates a <span> tag. (Shortcut function.)
2422 * @param string $content HTML content of tag
2423 * @param string $class Optional CSS class (or classes as space-separated list)
2424 * @param array $attributes Optional other attributes as array
2425 * @return string HTML code for span
2427 public static function span($content, $class = '', array $attributes = null) {
2428 return self::tag('span', $content, self::add_class($class, $attributes));
2432 * Starts a <span> tag. (Shortcut function.)
2434 * @param string $class Optional CSS class (or classes as space-separated list)
2435 * @param array $attributes Optional other attributes as array
2436 * @return string HTML code for open span tag
2438 public static function start_span($class = '', array $attributes = null) {
2439 return self::start_tag('span', self::add_class($class, $attributes));
2443 * Ends a <span> tag. (Shortcut function.)
2445 * @return string HTML code for close span tag
2447 public static function end_span() {
2448 return self::end_tag('span');
2453 * Simple javascript output class
2455 * @copyright 2010 Petr Skoda
2456 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2457 * @since Moodle 2.0
2458 * @package core
2459 * @category output
2461 class js_writer {
2464 * Returns javascript code calling the function
2466 * @param string $function function name, can be complex like Y.Event.purgeElement
2467 * @param array $arguments parameters
2468 * @param int $delay execution delay in seconds
2469 * @return string JS code fragment
2471 public static function function_call($function, array $arguments = null, $delay=0) {
2472 if ($arguments) {
2473 $arguments = array_map('json_encode', convert_to_array($arguments));
2474 $arguments = implode(', ', $arguments);
2475 } else {
2476 $arguments = '';
2478 $js = "$function($arguments);";
2480 if ($delay) {
2481 $delay = $delay * 1000; // in miliseconds
2482 $js = "setTimeout(function() { $js }, $delay);";
2484 return $js . "\n";
2488 * Special function which adds Y as first argument of function call.
2490 * @param string $function The function to call
2491 * @param array $extraarguments Any arguments to pass to it
2492 * @return string Some JS code
2494 public static function function_call_with_Y($function, array $extraarguments = null) {
2495 if ($extraarguments) {
2496 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
2497 $arguments = 'Y, ' . implode(', ', $extraarguments);
2498 } else {
2499 $arguments = 'Y';
2501 return "$function($arguments);\n";
2505 * Returns JavaScript code to initialise a new object
2507 * @param string $var If it is null then no var is assigned the new object.
2508 * @param string $class The class to initialise an object for.
2509 * @param array $arguments An array of args to pass to the init method.
2510 * @param array $requirements Any modules required for this class.
2511 * @param int $delay The delay before initialisation. 0 = no delay.
2512 * @return string Some JS code
2514 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
2515 if (is_array($arguments)) {
2516 $arguments = array_map('json_encode', convert_to_array($arguments));
2517 $arguments = implode(', ', $arguments);
2520 if ($var === null) {
2521 $js = "new $class(Y, $arguments);";
2522 } else if (strpos($var, '.')!==false) {
2523 $js = "$var = new $class(Y, $arguments);";
2524 } else {
2525 $js = "var $var = new $class(Y, $arguments);";
2528 if ($delay) {
2529 $delay = $delay * 1000; // in miliseconds
2530 $js = "setTimeout(function() { $js }, $delay);";
2533 if (count($requirements) > 0) {
2534 $requirements = implode("', '", $requirements);
2535 $js = "Y.use('$requirements', function(Y){ $js });";
2537 return $js."\n";
2541 * Returns code setting value to variable
2543 * @param string $name
2544 * @param mixed $value json serialised value
2545 * @param bool $usevar add var definition, ignored for nested properties
2546 * @return string JS code fragment
2548 public static function set_variable($name, $value, $usevar = true) {
2549 $output = '';
2551 if ($usevar) {
2552 if (strpos($name, '.')) {
2553 $output .= '';
2554 } else {
2555 $output .= 'var ';
2559 $output .= "$name = ".json_encode($value).";";
2561 return $output;
2565 * Writes event handler attaching code
2567 * @param array|string $selector standard YUI selector for elements, may be
2568 * array or string, element id is in the form "#idvalue"
2569 * @param string $event A valid DOM event (click, mousedown, change etc.)
2570 * @param string $function The name of the function to call
2571 * @param array $arguments An optional array of argument parameters to pass to the function
2572 * @return string JS code fragment
2574 public static function event_handler($selector, $event, $function, array $arguments = null) {
2575 $selector = json_encode($selector);
2576 $output = "Y.on('$event', $function, $selector, null";
2577 if (!empty($arguments)) {
2578 $output .= ', ' . json_encode($arguments);
2580 return $output . ");\n";
2585 * Holds all the information required to render a <table> by {@link core_renderer::table()}
2587 * Example of usage:
2588 * $t = new html_table();
2589 * ... // set various properties of the object $t as described below
2590 * echo html_writer::table($t);
2592 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
2593 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2594 * @since Moodle 2.0
2595 * @package core
2596 * @category output
2598 class html_table {
2601 * @var string Value to use for the id attribute of the table
2603 public $id = null;
2606 * @var array Attributes of HTML attributes for the <table> element
2608 public $attributes = array();
2611 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
2612 * For more control over the rendering of the headers, an array of html_table_cell objects
2613 * can be passed instead of an array of strings.
2615 * Example of usage:
2616 * $t->head = array('Student', 'Grade');
2618 public $head;
2621 * @var array An array that can be used to make a heading span multiple columns.
2622 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
2623 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
2625 * Example of usage:
2626 * $t->headspan = array(2,1);
2628 public $headspan;
2631 * @var array An array of column alignments.
2632 * The value is used as CSS 'text-align' property. Therefore, possible
2633 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
2634 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
2636 * Examples of usage:
2637 * $t->align = array(null, 'right');
2638 * or
2639 * $t->align[1] = 'right';
2641 public $align;
2644 * @var array The value is used as CSS 'size' property.
2646 * Examples of usage:
2647 * $t->size = array('50%', '50%');
2648 * or
2649 * $t->size[1] = '120px';
2651 public $size;
2654 * @var array An array of wrapping information.
2655 * The only possible value is 'nowrap' that sets the
2656 * CSS property 'white-space' to the value 'nowrap' in the given column.
2658 * Example of usage:
2659 * $t->wrap = array(null, 'nowrap');
2661 public $wrap;
2664 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2665 * $head specified, the string 'hr' (for horizontal ruler) can be used
2666 * instead of an array of cells data resulting in a divider rendered.
2668 * Example of usage with array of arrays:
2669 * $row1 = array('Harry Potter', '76 %');
2670 * $row2 = array('Hermione Granger', '100 %');
2671 * $t->data = array($row1, $row2);
2673 * Example with array of html_table_row objects: (used for more fine-grained control)
2674 * $cell1 = new html_table_cell();
2675 * $cell1->text = 'Harry Potter';
2676 * $cell1->colspan = 2;
2677 * $row1 = new html_table_row();
2678 * $row1->cells[] = $cell1;
2679 * $cell2 = new html_table_cell();
2680 * $cell2->text = 'Hermione Granger';
2681 * $cell3 = new html_table_cell();
2682 * $cell3->text = '100 %';
2683 * $row2 = new html_table_row();
2684 * $row2->cells = array($cell2, $cell3);
2685 * $t->data = array($row1, $row2);
2687 public $data = [];
2690 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2691 * @var string Width of the table, percentage of the page preferred.
2693 public $width = null;
2696 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2697 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2699 public $tablealign = null;
2702 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2703 * @var int Padding on each cell, in pixels
2705 public $cellpadding = null;
2708 * @var int Spacing between cells, in pixels
2709 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2711 public $cellspacing = null;
2714 * @var array Array of classes to add to particular rows, space-separated string.
2715 * Class 'lastrow' is added automatically for the last row in the table.
2717 * Example of usage:
2718 * $t->rowclasses[9] = 'tenth'
2720 public $rowclasses;
2723 * @var array An array of classes to add to every cell in a particular column,
2724 * space-separated string. Class 'cell' is added automatically by the renderer.
2725 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2726 * respectively. Class 'lastcol' is added automatically for all last cells
2727 * in a row.
2729 * Example of usage:
2730 * $t->colclasses = array(null, 'grade');
2732 public $colclasses;
2735 * @var string Description of the contents for screen readers.
2737 public $summary;
2740 * @var string Caption for the table, typically a title.
2742 * Example of usage:
2743 * $t->caption = "TV Guide";
2745 public $caption;
2748 * @var bool Whether to hide the table's caption from sighted users.
2750 * Example of usage:
2751 * $t->caption = "TV Guide";
2752 * $t->captionhide = true;
2754 public $captionhide = false;
2757 * Constructor
2759 public function __construct() {
2760 $this->attributes['class'] = '';
2765 * Component representing a table row.
2767 * @copyright 2009 Nicolas Connault
2768 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2769 * @since Moodle 2.0
2770 * @package core
2771 * @category output
2773 class html_table_row {
2776 * @var string Value to use for the id attribute of the row.
2778 public $id = null;
2781 * @var array Array of html_table_cell objects
2783 public $cells = array();
2786 * @var string Value to use for the style attribute of the table row
2788 public $style = null;
2791 * @var array Attributes of additional HTML attributes for the <tr> element
2793 public $attributes = array();
2796 * Constructor
2797 * @param array $cells
2799 public function __construct(array $cells=null) {
2800 $this->attributes['class'] = '';
2801 $cells = (array)$cells;
2802 foreach ($cells as $cell) {
2803 if ($cell instanceof html_table_cell) {
2804 $this->cells[] = $cell;
2805 } else {
2806 $this->cells[] = new html_table_cell($cell);
2813 * Component representing a table cell.
2815 * @copyright 2009 Nicolas Connault
2816 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2817 * @since Moodle 2.0
2818 * @package core
2819 * @category output
2821 class html_table_cell {
2824 * @var string Value to use for the id attribute of the cell.
2826 public $id = null;
2829 * @var string The contents of the cell.
2831 public $text;
2834 * @var string Abbreviated version of the contents of the cell.
2836 public $abbr = null;
2839 * @var int Number of columns this cell should span.
2841 public $colspan = null;
2844 * @var int Number of rows this cell should span.
2846 public $rowspan = null;
2849 * @var string Defines a way to associate header cells and data cells in a table.
2851 public $scope = null;
2854 * @var bool Whether or not this cell is a header cell.
2856 public $header = null;
2859 * @var string Value to use for the style attribute of the table cell
2861 public $style = null;
2864 * @var array Attributes of additional HTML attributes for the <td> element
2866 public $attributes = array();
2869 * Constructs a table cell
2871 * @param string $text
2873 public function __construct($text = null) {
2874 $this->text = $text;
2875 $this->attributes['class'] = '';
2880 * Component representing a paging bar.
2882 * @copyright 2009 Nicolas Connault
2883 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2884 * @since Moodle 2.0
2885 * @package core
2886 * @category output
2888 class paging_bar implements renderable, templatable {
2891 * @var int The maximum number of pagelinks to display.
2893 public $maxdisplay = 18;
2896 * @var int The total number of entries to be pages through..
2898 public $totalcount;
2901 * @var int The page you are currently viewing.
2903 public $page;
2906 * @var int The number of entries that should be shown per page.
2908 public $perpage;
2911 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2912 * an equals sign and the page number.
2913 * If this is a moodle_url object then the pagevar param will be replaced by
2914 * the page no, for each page.
2916 public $baseurl;
2919 * @var string This is the variable name that you use for the pagenumber in your
2920 * code (ie. 'tablepage', 'blogpage', etc)
2922 public $pagevar;
2925 * @var string A HTML link representing the "previous" page.
2927 public $previouslink = null;
2930 * @var string A HTML link representing the "next" page.
2932 public $nextlink = null;
2935 * @var string A HTML link representing the first page.
2937 public $firstlink = null;
2940 * @var string A HTML link representing the last page.
2942 public $lastlink = null;
2945 * @var array An array of strings. One of them is just a string: the current page
2947 public $pagelinks = array();
2950 * Constructor paging_bar with only the required params.
2952 * @param int $totalcount The total number of entries available to be paged through
2953 * @param int $page The page you are currently viewing
2954 * @param int $perpage The number of entries that should be shown per page
2955 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2956 * @param string $pagevar name of page parameter that holds the page number
2958 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2959 $this->totalcount = $totalcount;
2960 $this->page = $page;
2961 $this->perpage = $perpage;
2962 $this->baseurl = $baseurl;
2963 $this->pagevar = $pagevar;
2967 * Prepares the paging bar for output.
2969 * This method validates the arguments set up for the paging bar and then
2970 * produces fragments of HTML to assist display later on.
2972 * @param renderer_base $output
2973 * @param moodle_page $page
2974 * @param string $target
2975 * @throws coding_exception
2977 public function prepare(renderer_base $output, moodle_page $page, $target) {
2978 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2979 throw new coding_exception('paging_bar requires a totalcount value.');
2981 if (!isset($this->page) || is_null($this->page)) {
2982 throw new coding_exception('paging_bar requires a page value.');
2984 if (empty($this->perpage)) {
2985 throw new coding_exception('paging_bar requires a perpage value.');
2987 if (empty($this->baseurl)) {
2988 throw new coding_exception('paging_bar requires a baseurl value.');
2991 if ($this->totalcount > $this->perpage) {
2992 $pagenum = $this->page - 1;
2994 if ($this->page > 0) {
2995 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2998 if ($this->perpage > 0) {
2999 $lastpage = ceil($this->totalcount / $this->perpage);
3000 } else {
3001 $lastpage = 1;
3004 if ($this->page > round(($this->maxdisplay/3)*2)) {
3005 $currpage = $this->page - round($this->maxdisplay/3);
3007 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
3008 } else {
3009 $currpage = 0;
3012 $displaycount = $displaypage = 0;
3014 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3015 $displaypage = $currpage + 1;
3017 if ($this->page == $currpage) {
3018 $this->pagelinks[] = html_writer::span($displaypage, 'current-page');
3019 } else {
3020 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
3021 $this->pagelinks[] = $pagelink;
3024 $displaycount++;
3025 $currpage++;
3028 if ($currpage < $lastpage) {
3029 $lastpageactual = $lastpage - 1;
3030 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
3033 $pagenum = $this->page + 1;
3035 if ($pagenum != $lastpage) {
3036 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
3042 * Export for template.
3044 * @param renderer_base $output The renderer.
3045 * @return stdClass
3047 public function export_for_template(renderer_base $output) {
3048 $data = new stdClass();
3049 $data->previous = null;
3050 $data->next = null;
3051 $data->first = null;
3052 $data->last = null;
3053 $data->label = get_string('page');
3054 $data->pages = [];
3055 $data->haspages = $this->totalcount > $this->perpage;
3057 if (!$data->haspages) {
3058 return $data;
3061 if ($this->page > 0) {
3062 $data->previous = [
3063 'page' => $this->page - 1,
3064 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page - 1]))->out(false)
3068 $currpage = 0;
3069 if ($this->page > round(($this->maxdisplay / 3) * 2)) {
3070 $currpage = $this->page - round($this->maxdisplay / 3);
3071 $data->first = [
3072 'page' => 1,
3073 'url' => (new moodle_url($this->baseurl, [$this->pagevar => 0]))->out(false)
3077 $lastpage = 1;
3078 if ($this->perpage > 0) {
3079 $lastpage = ceil($this->totalcount / $this->perpage);
3082 $displaycount = 0;
3083 $displaypage = 0;
3084 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3085 $displaypage = $currpage + 1;
3087 $iscurrent = $this->page == $currpage;
3088 $link = new moodle_url($this->baseurl, [$this->pagevar => $currpage]);
3090 $data->pages[] = [
3091 'page' => $displaypage,
3092 'active' => $iscurrent,
3093 'url' => $iscurrent ? null : $link->out(false)
3096 $displaycount++;
3097 $currpage++;
3100 if ($currpage < $lastpage) {
3101 $data->last = [
3102 'page' => $lastpage,
3103 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $lastpage - 1]))->out(false)
3107 if ($this->page + 1 != $lastpage) {
3108 $data->next = [
3109 'page' => $this->page + 1,
3110 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page + 1]))->out(false)
3114 return $data;
3119 * Component representing initials bar.
3121 * @copyright 2017 Ilya Tregubov
3122 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3123 * @since Moodle 3.3
3124 * @package core
3125 * @category output
3127 class initials_bar implements renderable, templatable {
3130 * @var string Currently selected letter.
3132 public $current;
3135 * @var string Class name to add to this initial bar.
3137 public $class;
3140 * @var string The name to put in front of this initial bar.
3142 public $title;
3145 * @var string URL parameter name for this initial.
3147 public $urlvar;
3150 * @var string URL object.
3152 public $url;
3155 * @var array An array of letters in the alphabet.
3157 public $alpha;
3160 * Constructor initials_bar with only the required params.
3162 * @param string $current the currently selected letter.
3163 * @param string $class class name to add to this initial bar.
3164 * @param string $title the name to put in front of this initial bar.
3165 * @param string $urlvar URL parameter name for this initial.
3166 * @param string $url URL object.
3167 * @param array $alpha of letters in the alphabet.
3169 public function __construct($current, $class, $title, $urlvar, $url, $alpha = null) {
3170 $this->current = $current;
3171 $this->class = $class;
3172 $this->title = $title;
3173 $this->urlvar = $urlvar;
3174 $this->url = $url;
3175 $this->alpha = $alpha;
3179 * Export for template.
3181 * @param renderer_base $output The renderer.
3182 * @return stdClass
3184 public function export_for_template(renderer_base $output) {
3185 $data = new stdClass();
3187 if ($this->alpha == null) {
3188 $this->alpha = explode(',', get_string('alphabet', 'langconfig'));
3191 if ($this->current == 'all') {
3192 $this->current = '';
3195 // We want to find a letter grouping size which suits the language so
3196 // find the largest group size which is less than 15 chars.
3197 // The choice of 15 chars is the largest number of chars that reasonably
3198 // fits on the smallest supported screen size. By always using a max number
3199 // of groups which is a factor of 2, we always get nice wrapping, and the
3200 // last row is always the shortest.
3201 $groupsize = count($this->alpha);
3202 $groups = 1;
3203 while ($groupsize > 15) {
3204 $groups *= 2;
3205 $groupsize = ceil(count($this->alpha) / $groups);
3208 $groupsizelimit = 0;
3209 $groupnumber = 0;
3210 foreach ($this->alpha as $letter) {
3211 if ($groupsizelimit++ > 0 && $groupsizelimit % $groupsize == 1) {
3212 $groupnumber++;
3214 $groupletter = new stdClass();
3215 $groupletter->name = $letter;
3216 $groupletter->url = $this->url->out(false, array($this->urlvar => $letter));
3217 if ($letter == $this->current) {
3218 $groupletter->selected = $this->current;
3220 $data->group[$groupnumber]->letter[] = $groupletter;
3223 $data->class = $this->class;
3224 $data->title = $this->title;
3225 $data->url = $this->url->out(false, array($this->urlvar => ''));
3226 $data->current = $this->current;
3227 $data->all = get_string('all');
3229 return $data;
3234 * This class represents how a block appears on a page.
3236 * During output, each block instance is asked to return a block_contents object,
3237 * those are then passed to the $OUTPUT->block function for display.
3239 * contents should probably be generated using a moodle_block_..._renderer.
3241 * Other block-like things that need to appear on the page, for example the
3242 * add new block UI, are also represented as block_contents objects.
3244 * @copyright 2009 Tim Hunt
3245 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3246 * @since Moodle 2.0
3247 * @package core
3248 * @category output
3250 class block_contents {
3252 /** Used when the block cannot be collapsed **/
3253 const NOT_HIDEABLE = 0;
3255 /** Used when the block can be collapsed but currently is not **/
3256 const VISIBLE = 1;
3258 /** Used when the block has been collapsed **/
3259 const HIDDEN = 2;
3262 * @var int Used to set $skipid.
3264 protected static $idcounter = 1;
3267 * @var int All the blocks (or things that look like blocks) printed on
3268 * a page are given a unique number that can be used to construct id="" attributes.
3269 * This is set automatically be the {@link prepare()} method.
3270 * Do not try to set it manually.
3272 public $skipid;
3275 * @var int If this is the contents of a real block, this should be set
3276 * to the block_instance.id. Otherwise this should be set to 0.
3278 public $blockinstanceid = 0;
3281 * @var int If this is a real block instance, and there is a corresponding
3282 * block_position.id for the block on this page, this should be set to that id.
3283 * Otherwise it should be 0.
3285 public $blockpositionid = 0;
3288 * @var array An array of attribute => value pairs that are put on the outer div of this
3289 * block. {@link $id} and {@link $classes} attributes should be set separately.
3291 public $attributes;
3294 * @var string The title of this block. If this came from user input, it should already
3295 * have had format_string() processing done on it. This will be output inside
3296 * <h2> tags. Please do not cause invalid XHTML.
3298 public $title = '';
3301 * @var string The label to use when the block does not, or will not have a visible title.
3302 * You should never set this as well as title... it will just be ignored.
3304 public $arialabel = '';
3307 * @var string HTML for the content
3309 public $content = '';
3312 * @var array An alternative to $content, it you want a list of things with optional icons.
3314 public $footer = '';
3317 * @var string Any small print that should appear under the block to explain
3318 * to the teacher about the block, for example 'This is a sticky block that was
3319 * added in the system context.'
3321 public $annotation = '';
3324 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
3325 * the user can toggle whether this block is visible.
3327 public $collapsible = self::NOT_HIDEABLE;
3330 * Set this to true if the block is dockable.
3331 * @var bool
3333 public $dockable = false;
3336 * @var array A (possibly empty) array of editing controls. Each element of
3337 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
3338 * $icon is the icon name. Fed to $OUTPUT->image_url.
3340 public $controls = array();
3344 * Create new instance of block content
3345 * @param array $attributes
3347 public function __construct(array $attributes = null) {
3348 $this->skipid = self::$idcounter;
3349 self::$idcounter += 1;
3351 if ($attributes) {
3352 // standard block
3353 $this->attributes = $attributes;
3354 } else {
3355 // simple "fake" blocks used in some modules and "Add new block" block
3356 $this->attributes = array('class'=>'block');
3361 * Add html class to block
3363 * @param string $class
3365 public function add_class($class) {
3366 $this->attributes['class'] .= ' '.$class;
3372 * This class represents a target for where a block can go when it is being moved.
3374 * This needs to be rendered as a form with the given hidden from fields, and
3375 * clicking anywhere in the form should submit it. The form action should be
3376 * $PAGE->url.
3378 * @copyright 2009 Tim Hunt
3379 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3380 * @since Moodle 2.0
3381 * @package core
3382 * @category output
3384 class block_move_target {
3387 * @var moodle_url Move url
3389 public $url;
3392 * Constructor
3393 * @param moodle_url $url
3395 public function __construct(moodle_url $url) {
3396 $this->url = $url;
3401 * Custom menu item
3403 * This class is used to represent one item within a custom menu that may or may
3404 * not have children.
3406 * @copyright 2010 Sam Hemelryk
3407 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3408 * @since Moodle 2.0
3409 * @package core
3410 * @category output
3412 class custom_menu_item implements renderable, templatable {
3415 * @var string The text to show for the item
3417 protected $text;
3420 * @var moodle_url The link to give the icon if it has no children
3422 protected $url;
3425 * @var string A title to apply to the item. By default the text
3427 protected $title;
3430 * @var int A sort order for the item, not necessary if you order things in
3431 * the CFG var.
3433 protected $sort;
3436 * @var custom_menu_item A reference to the parent for this item or NULL if
3437 * it is a top level item
3439 protected $parent;
3442 * @var array A array in which to store children this item has.
3444 protected $children = array();
3447 * @var int A reference to the sort var of the last child that was added
3449 protected $lastsort = 0;
3452 * Constructs the new custom menu item
3454 * @param string $text
3455 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
3456 * @param string $title A title to apply to this item [Optional]
3457 * @param int $sort A sort or to use if we need to sort differently [Optional]
3458 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
3459 * belongs to, only if the child has a parent. [Optional]
3461 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
3462 $this->text = $text;
3463 $this->url = $url;
3464 $this->title = $title;
3465 $this->sort = (int)$sort;
3466 $this->parent = $parent;
3470 * Adds a custom menu item as a child of this node given its properties.
3472 * @param string $text
3473 * @param moodle_url $url
3474 * @param string $title
3475 * @param int $sort
3476 * @return custom_menu_item
3478 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
3479 $key = count($this->children);
3480 if (empty($sort)) {
3481 $sort = $this->lastsort + 1;
3483 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
3484 $this->lastsort = (int)$sort;
3485 return $this->children[$key];
3489 * Removes a custom menu item that is a child or descendant to the current menu.
3491 * Returns true if child was found and removed.
3493 * @param custom_menu_item $menuitem
3494 * @return bool
3496 public function remove_child(custom_menu_item $menuitem) {
3497 $removed = false;
3498 if (($key = array_search($menuitem, $this->children)) !== false) {
3499 unset($this->children[$key]);
3500 $this->children = array_values($this->children);
3501 $removed = true;
3502 } else {
3503 foreach ($this->children as $child) {
3504 if ($removed = $child->remove_child($menuitem)) {
3505 break;
3509 return $removed;
3513 * Returns the text for this item
3514 * @return string
3516 public function get_text() {
3517 return $this->text;
3521 * Returns the url for this item
3522 * @return moodle_url
3524 public function get_url() {
3525 return $this->url;
3529 * Returns the title for this item
3530 * @return string
3532 public function get_title() {
3533 return $this->title;
3537 * Sorts and returns the children for this item
3538 * @return array
3540 public function get_children() {
3541 $this->sort();
3542 return $this->children;
3546 * Gets the sort order for this child
3547 * @return int
3549 public function get_sort_order() {
3550 return $this->sort;
3554 * Gets the parent this child belong to
3555 * @return custom_menu_item
3557 public function get_parent() {
3558 return $this->parent;
3562 * Sorts the children this item has
3564 public function sort() {
3565 usort($this->children, array('custom_menu','sort_custom_menu_items'));
3569 * Returns true if this item has any children
3570 * @return bool
3572 public function has_children() {
3573 return (count($this->children) > 0);
3577 * Sets the text for the node
3578 * @param string $text
3580 public function set_text($text) {
3581 $this->text = (string)$text;
3585 * Sets the title for the node
3586 * @param string $title
3588 public function set_title($title) {
3589 $this->title = (string)$title;
3593 * Sets the url for the node
3594 * @param moodle_url $url
3596 public function set_url(moodle_url $url) {
3597 $this->url = $url;
3601 * Export this data so it can be used as the context for a mustache template.
3603 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
3604 * @return array
3606 public function export_for_template(renderer_base $output) {
3607 global $CFG;
3609 require_once($CFG->libdir . '/externallib.php');
3611 $syscontext = context_system::instance();
3613 $context = new stdClass();
3614 $context->text = external_format_string($this->text, $syscontext->id);
3615 $context->url = $this->url ? $this->url->out() : null;
3616 $context->title = external_format_string($this->title, $syscontext->id);
3617 $context->sort = $this->sort;
3618 $context->children = array();
3619 if (preg_match("/^#+$/", $this->text)) {
3620 $context->divider = true;
3622 $context->haschildren = !empty($this->children) && (count($this->children) > 0);
3623 foreach ($this->children as $child) {
3624 $child = $child->export_for_template($output);
3625 array_push($context->children, $child);
3628 return $context;
3633 * Custom menu class
3635 * This class is used to operate a custom menu that can be rendered for the page.
3636 * The custom menu is built using $CFG->custommenuitems and is a structured collection
3637 * of custom_menu_item nodes that can be rendered by the core renderer.
3639 * To configure the custom menu:
3640 * Settings: Administration > Appearance > Themes > Theme settings
3642 * @copyright 2010 Sam Hemelryk
3643 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3644 * @since Moodle 2.0
3645 * @package core
3646 * @category output
3648 class custom_menu extends custom_menu_item {
3651 * @var string The language we should render for, null disables multilang support.
3653 protected $currentlanguage = null;
3656 * Creates the custom menu
3658 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
3659 * @param string $currentlanguage the current language code, null disables multilang support
3661 public function __construct($definition = '', $currentlanguage = null) {
3662 $this->currentlanguage = $currentlanguage;
3663 parent::__construct('root'); // create virtual root element of the menu
3664 if (!empty($definition)) {
3665 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
3670 * Overrides the children of this custom menu. Useful when getting children
3671 * from $CFG->custommenuitems
3673 * @param array $children
3675 public function override_children(array $children) {
3676 $this->children = array();
3677 foreach ($children as $child) {
3678 if ($child instanceof custom_menu_item) {
3679 $this->children[] = $child;
3685 * Converts a string into a structured array of custom_menu_items which can
3686 * then be added to a custom menu.
3688 * Structure:
3689 * text|url|title|langs
3690 * The number of hyphens at the start determines the depth of the item. The
3691 * languages are optional, comma separated list of languages the line is for.
3693 * Example structure:
3694 * First level first item|http://www.moodle.com/
3695 * -Second level first item|http://www.moodle.com/partners/
3696 * -Second level second item|http://www.moodle.com/hq/
3697 * --Third level first item|http://www.moodle.com/jobs/
3698 * -Second level third item|http://www.moodle.com/development/
3699 * First level second item|http://www.moodle.com/feedback/
3700 * First level third item
3701 * English only|http://moodle.com|English only item|en
3702 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
3705 * @static
3706 * @param string $text the menu items definition
3707 * @param string $language the language code, null disables multilang support
3708 * @return array
3710 public static function convert_text_to_menu_nodes($text, $language = null) {
3711 $root = new custom_menu();
3712 $lastitem = $root;
3713 $lastdepth = 0;
3714 $hiddenitems = array();
3715 $lines = explode("\n", $text);
3716 foreach ($lines as $linenumber => $line) {
3717 $line = trim($line);
3718 if (strlen($line) == 0) {
3719 continue;
3721 // Parse item settings.
3722 $itemtext = null;
3723 $itemurl = null;
3724 $itemtitle = null;
3725 $itemvisible = true;
3726 $settings = explode('|', $line);
3727 foreach ($settings as $i => $setting) {
3728 $setting = trim($setting);
3729 if (!empty($setting)) {
3730 switch ($i) {
3731 case 0:
3732 $itemtext = ltrim($setting, '-');
3733 $itemtitle = $itemtext;
3734 break;
3735 case 1:
3736 try {
3737 $itemurl = new moodle_url($setting);
3738 } catch (moodle_exception $exception) {
3739 // We're not actually worried about this, we don't want to mess up the display
3740 // just for a wrongly entered URL.
3741 $itemurl = null;
3743 break;
3744 case 2:
3745 $itemtitle = $setting;
3746 break;
3747 case 3:
3748 if (!empty($language)) {
3749 $itemlanguages = array_map('trim', explode(',', $setting));
3750 $itemvisible &= in_array($language, $itemlanguages);
3752 break;
3756 // Get depth of new item.
3757 preg_match('/^(\-*)/', $line, $match);
3758 $itemdepth = strlen($match[1]) + 1;
3759 // Find parent item for new item.
3760 while (($lastdepth - $itemdepth) >= 0) {
3761 $lastitem = $lastitem->get_parent();
3762 $lastdepth--;
3764 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1);
3765 $lastdepth++;
3766 if (!$itemvisible) {
3767 $hiddenitems[] = $lastitem;
3770 foreach ($hiddenitems as $item) {
3771 $item->parent->remove_child($item);
3773 return $root->get_children();
3777 * Sorts two custom menu items
3779 * This function is designed to be used with the usort method
3780 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
3782 * @static
3783 * @param custom_menu_item $itema
3784 * @param custom_menu_item $itemb
3785 * @return int
3787 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
3788 $itema = $itema->get_sort_order();
3789 $itemb = $itemb->get_sort_order();
3790 if ($itema == $itemb) {
3791 return 0;
3793 return ($itema > $itemb) ? +1 : -1;
3798 * Stores one tab
3800 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3801 * @package core
3803 class tabobject implements renderable, templatable {
3804 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
3805 var $id;
3806 /** @var moodle_url|string link */
3807 var $link;
3808 /** @var string text on the tab */
3809 var $text;
3810 /** @var string title under the link, by defaul equals to text */
3811 var $title;
3812 /** @var bool whether to display a link under the tab name when it's selected */
3813 var $linkedwhenselected = false;
3814 /** @var bool whether the tab is inactive */
3815 var $inactive = false;
3816 /** @var bool indicates that this tab's child is selected */
3817 var $activated = false;
3818 /** @var bool indicates that this tab is selected */
3819 var $selected = false;
3820 /** @var array stores children tabobjects */
3821 var $subtree = array();
3822 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
3823 var $level = 1;
3826 * Constructor
3828 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
3829 * @param string|moodle_url $link
3830 * @param string $text text on the tab
3831 * @param string $title title under the link, by defaul equals to text
3832 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
3834 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
3835 $this->id = $id;
3836 $this->link = $link;
3837 $this->text = $text;
3838 $this->title = $title ? $title : $text;
3839 $this->linkedwhenselected = $linkedwhenselected;
3843 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
3845 * @param string $selected the id of the selected tab (whatever row it's on),
3846 * if null marks all tabs as unselected
3847 * @return bool whether this tab is selected or contains selected tab in its subtree
3849 protected function set_selected($selected) {
3850 if ((string)$selected === (string)$this->id) {
3851 $this->selected = true;
3852 // This tab is selected. No need to travel through subtree.
3853 return true;
3855 foreach ($this->subtree as $subitem) {
3856 if ($subitem->set_selected($selected)) {
3857 // This tab has child that is selected. Mark it as activated. No need to check other children.
3858 $this->activated = true;
3859 return true;
3862 return false;
3866 * Travels through tree and finds a tab with specified id
3868 * @param string $id
3869 * @return tabtree|null
3871 public function find($id) {
3872 if ((string)$this->id === (string)$id) {
3873 return $this;
3875 foreach ($this->subtree as $tab) {
3876 if ($obj = $tab->find($id)) {
3877 return $obj;
3880 return null;
3884 * Allows to mark each tab's level in the tree before rendering.
3886 * @param int $level
3888 protected function set_level($level) {
3889 $this->level = $level;
3890 foreach ($this->subtree as $tab) {
3891 $tab->set_level($level + 1);
3896 * Export for template.
3898 * @param renderer_base $output Renderer.
3899 * @return object
3901 public function export_for_template(renderer_base $output) {
3902 if ($this->inactive || ($this->selected && !$this->linkedwhenselected) || $this->activated) {
3903 $link = null;
3904 } else {
3905 $link = $this->link;
3907 $active = $this->activated || $this->selected;
3909 return (object) [
3910 'id' => $this->id,
3911 'link' => is_object($link) ? $link->out(false) : $link,
3912 'text' => $this->text,
3913 'title' => $this->title,
3914 'inactive' => !$active && $this->inactive,
3915 'active' => $active,
3916 'level' => $this->level,
3923 * Renderable for the main page header.
3925 * @package core
3926 * @category output
3927 * @since 2.9
3928 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
3929 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3931 class context_header implements renderable {
3934 * @var string $heading Main heading.
3936 public $heading;
3938 * @var int $headinglevel Main heading 'h' tag level.
3940 public $headinglevel;
3942 * @var string|null $imagedata HTML code for the picture in the page header.
3944 public $imagedata;
3946 * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
3947 * array elements - title => alternate text for the image, or if no image is available the button text.
3948 * url => Link for the button to head to. Should be a moodle_url.
3949 * image => location to the image, or name of the image in /pix/t/{image name}.
3950 * linkattributes => additional attributes for the <a href> element.
3951 * page => page object. Don't include if the image is an external image.
3953 public $additionalbuttons;
3956 * Constructor.
3958 * @param string $heading Main heading data.
3959 * @param int $headinglevel Main heading 'h' tag level.
3960 * @param string|null $imagedata HTML code for the picture in the page header.
3961 * @param string $additionalbuttons Buttons for the header e.g. Messaging button for the user header.
3963 public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null) {
3965 $this->heading = $heading;
3966 $this->headinglevel = $headinglevel;
3967 $this->imagedata = $imagedata;
3968 $this->additionalbuttons = $additionalbuttons;
3969 // If we have buttons then format them.
3970 if (isset($this->additionalbuttons)) {
3971 $this->format_button_images();
3976 * Adds an array element for a formatted image.
3978 protected function format_button_images() {
3980 foreach ($this->additionalbuttons as $buttontype => $button) {
3981 $page = $button['page'];
3982 // If no image is provided then just use the title.
3983 if (!isset($button['image'])) {
3984 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['title'];
3985 } else {
3986 // Check to see if this is an internal Moodle icon.
3987 $internalimage = $page->theme->resolve_image_location('t/' . $button['image'], 'moodle');
3988 if ($internalimage) {
3989 $this->additionalbuttons[$buttontype]['formattedimage'] = 't/' . $button['image'];
3990 } else {
3991 // Treat as an external image.
3992 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['image'];
3996 if (isset($button['linkattributes']['class'])) {
3997 $class = $button['linkattributes']['class'] . ' btn';
3998 } else {
3999 $class = 'btn';
4001 // Add the bootstrap 'btn' class for formatting.
4002 $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
4003 array('class' => $class));
4009 * Stores tabs list
4011 * Example how to print a single line tabs:
4012 * $rows = array(
4013 * new tabobject(...),
4014 * new tabobject(...)
4015 * );
4016 * echo $OUTPUT->tabtree($rows, $selectedid);
4018 * Multiple row tabs may not look good on some devices but if you want to use them
4019 * you can specify ->subtree for the active tabobject.
4021 * @copyright 2013 Marina Glancy
4022 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4023 * @since Moodle 2.5
4024 * @package core
4025 * @category output
4027 class tabtree extends tabobject {
4029 * Constuctor
4031 * It is highly recommended to call constructor when list of tabs is already
4032 * populated, this way you ensure that selected and inactive tabs are located
4033 * and attribute level is set correctly.
4035 * @param array $tabs array of tabs, each of them may have it's own ->subtree
4036 * @param string|null $selected which tab to mark as selected, all parent tabs will
4037 * automatically be marked as activated
4038 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4039 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
4041 public function __construct($tabs, $selected = null, $inactive = null) {
4042 $this->subtree = $tabs;
4043 if ($selected !== null) {
4044 $this->set_selected($selected);
4046 if ($inactive !== null) {
4047 if (is_array($inactive)) {
4048 foreach ($inactive as $id) {
4049 if ($tab = $this->find($id)) {
4050 $tab->inactive = true;
4053 } else if ($tab = $this->find($inactive)) {
4054 $tab->inactive = true;
4057 $this->set_level(0);
4061 * Export for template.
4063 * @param renderer_base $output Renderer.
4064 * @return object
4066 public function export_for_template(renderer_base $output) {
4067 $tabs = [];
4068 $secondrow = false;
4070 foreach ($this->subtree as $tab) {
4071 $tabs[] = $tab->export_for_template($output);
4072 if (!empty($tab->subtree) && ($tab->level == 0 || $tab->selected || $tab->activated)) {
4073 $secondrow = new tabtree($tab->subtree);
4077 return (object) [
4078 'tabs' => $tabs,
4079 'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false
4085 * An action menu.
4087 * This action menu component takes a series of primary and secondary actions.
4088 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
4089 * down menu.
4091 * @package core
4092 * @category output
4093 * @copyright 2013 Sam Hemelryk
4094 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4096 class action_menu implements renderable, templatable {
4099 * Top right alignment.
4101 const TL = 1;
4104 * Top right alignment.
4106 const TR = 2;
4109 * Top right alignment.
4111 const BL = 3;
4114 * Top right alignment.
4116 const BR = 4;
4119 * The instance number. This is unique to this instance of the action menu.
4120 * @var int
4122 protected $instance = 0;
4125 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
4126 * @var array
4128 protected $primaryactions = array();
4131 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
4132 * @var array
4134 protected $secondaryactions = array();
4137 * An array of attributes added to the container of the action menu.
4138 * Initialised with defaults during construction.
4139 * @var array
4141 public $attributes = array();
4143 * An array of attributes added to the container of the primary actions.
4144 * Initialised with defaults during construction.
4145 * @var array
4147 public $attributesprimary = array();
4149 * An array of attributes added to the container of the secondary actions.
4150 * Initialised with defaults during construction.
4151 * @var array
4153 public $attributessecondary = array();
4156 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
4157 * @var array
4159 public $actiontext = null;
4162 * The string to use for the accessible label for the menu.
4163 * @var array
4165 public $actionlabel = null;
4168 * An icon to use for the toggling the secondary menu (dropdown).
4169 * @var actionicon
4171 public $actionicon;
4174 * Any text to use for the toggling the secondary menu (dropdown).
4175 * @var menutrigger
4177 public $menutrigger = '';
4180 * Any extra classes for toggling to the secondary menu.
4181 * @var triggerextraclasses
4183 public $triggerextraclasses = '';
4186 * Place the action menu before all other actions.
4187 * @var prioritise
4189 public $prioritise = false;
4192 * Constructs the action menu with the given items.
4194 * @param array $actions An array of actions.
4196 public function __construct(array $actions = array()) {
4197 static $initialised = 0;
4198 $this->instance = $initialised;
4199 $initialised++;
4201 $this->attributes = array(
4202 'id' => 'action-menu-'.$this->instance,
4203 'class' => 'moodle-actionmenu',
4204 'data-enhance' => 'moodle-core-actionmenu'
4206 $this->attributesprimary = array(
4207 'id' => 'action-menu-'.$this->instance.'-menubar',
4208 'class' => 'menubar',
4209 'role' => 'menubar'
4211 $this->attributessecondary = array(
4212 'id' => 'action-menu-'.$this->instance.'-menu',
4213 'class' => 'menu',
4214 'data-rel' => 'menu-content',
4215 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
4216 'role' => 'menu'
4218 $this->set_alignment(self::TR, self::BR);
4219 foreach ($actions as $action) {
4220 $this->add($action);
4225 * Sets the label for the menu trigger.
4227 * @param string $label The text
4228 * @return null
4230 public function set_action_label($label) {
4231 $this->actionlabel = $label;
4235 * Sets the menu trigger text.
4237 * @param string $trigger The text
4238 * @param string $extraclasses Extra classes to style the secondary menu toggle.
4239 * @return null
4241 public function set_menu_trigger($trigger, $extraclasses = '') {
4242 $this->menutrigger = $trigger;
4243 $this->triggerextraclasses = $extraclasses;
4247 * Return true if there is at least one visible link in the menu.
4249 * @return bool
4251 public function is_empty() {
4252 return !count($this->primaryactions) && !count($this->secondaryactions);
4256 * Initialises JS required fore the action menu.
4257 * The JS is only required once as it manages all action menu's on the page.
4259 * @param moodle_page $page
4261 public function initialise_js(moodle_page $page) {
4262 static $initialised = false;
4263 if (!$initialised) {
4264 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
4265 $initialised = true;
4270 * Adds an action to this action menu.
4272 * @param action_menu_link|pix_icon|string $action
4274 public function add($action) {
4275 if ($action instanceof action_link) {
4276 if ($action->primary) {
4277 $this->add_primary_action($action);
4278 } else {
4279 $this->add_secondary_action($action);
4281 } else if ($action instanceof pix_icon) {
4282 $this->add_primary_action($action);
4283 } else {
4284 $this->add_secondary_action($action);
4289 * Adds a primary action to the action menu.
4291 * @param action_menu_link|action_link|pix_icon|string $action
4293 public function add_primary_action($action) {
4294 if ($action instanceof action_link || $action instanceof pix_icon) {
4295 $action->attributes['role'] = 'menuitem';
4296 if ($action instanceof action_menu_link) {
4297 $action->actionmenu = $this;
4300 $this->primaryactions[] = $action;
4304 * Adds a secondary action to the action menu.
4306 * @param action_link|pix_icon|string $action
4308 public function add_secondary_action($action) {
4309 if ($action instanceof action_link || $action instanceof pix_icon) {
4310 $action->attributes['role'] = 'menuitem';
4311 if ($action instanceof action_menu_link) {
4312 $action->actionmenu = $this;
4315 $this->secondaryactions[] = $action;
4319 * Returns the primary actions ready to be rendered.
4321 * @param core_renderer $output The renderer to use for getting icons.
4322 * @return array
4324 public function get_primary_actions(core_renderer $output = null) {
4325 global $OUTPUT;
4326 if ($output === null) {
4327 $output = $OUTPUT;
4329 $pixicon = $this->actionicon;
4330 $linkclasses = array('toggle-display');
4332 $title = '';
4333 if (!empty($this->menutrigger)) {
4334 $pixicon = '<b class="caret"></b>';
4335 $linkclasses[] = 'textmenu';
4336 } else {
4337 $title = new lang_string('actionsmenu', 'moodle');
4338 $this->actionicon = new pix_icon(
4339 't/edit_menu',
4341 'moodle',
4342 array('class' => 'iconsmall actionmenu', 'title' => '')
4344 $pixicon = $this->actionicon;
4346 if ($pixicon instanceof renderable) {
4347 $pixicon = $output->render($pixicon);
4348 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
4349 $title = $pixicon->attributes['alt'];
4352 $string = '';
4353 if ($this->actiontext) {
4354 $string = $this->actiontext;
4356 $label = '';
4357 if ($this->actionlabel) {
4358 $label = $this->actionlabel;
4359 } else {
4360 $label = $title;
4362 $actions = $this->primaryactions;
4363 $attributes = array(
4364 'class' => implode(' ', $linkclasses),
4365 'title' => $title,
4366 'aria-label' => $label,
4367 'id' => 'action-menu-toggle-'.$this->instance,
4368 'role' => 'menuitem'
4370 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
4371 if ($this->prioritise) {
4372 array_unshift($actions, $link);
4373 } else {
4374 $actions[] = $link;
4376 return $actions;
4380 * Returns the secondary actions ready to be rendered.
4381 * @return array
4383 public function get_secondary_actions() {
4384 return $this->secondaryactions;
4388 * Sets the selector that should be used to find the owning node of this menu.
4389 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
4391 public function set_owner_selector($selector) {
4392 $this->attributes['data-owner'] = $selector;
4396 * Sets the alignment of the dialogue in relation to button used to toggle it.
4398 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4399 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4401 public function set_alignment($dialogue, $button) {
4402 if (isset($this->attributessecondary['data-align'])) {
4403 // We've already got one set, lets remove the old class so as to avoid troubles.
4404 $class = $this->attributessecondary['class'];
4405 $search = 'align-'.$this->attributessecondary['data-align'];
4406 $this->attributessecondary['class'] = str_replace($search, '', $class);
4408 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
4409 $this->attributessecondary['data-align'] = $align;
4410 $this->attributessecondary['class'] .= ' align-'.$align;
4414 * Returns a string to describe the alignment.
4416 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4417 * @return string
4419 protected function get_align_string($align) {
4420 switch ($align) {
4421 case self::TL :
4422 return 'tl';
4423 case self::TR :
4424 return 'tr';
4425 case self::BL :
4426 return 'bl';
4427 case self::BR :
4428 return 'br';
4429 default :
4430 return 'tl';
4435 * Sets a constraint for the dialogue.
4437 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
4438 * element the constraint identifies.
4440 * This is required whenever the action menu is displayed inside any CSS element with the .no-overflow class
4441 * (flexible_table and any of it's child classes are a likely candidate).
4443 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
4445 public function set_constraint($ancestorselector) {
4446 $this->attributessecondary['data-constraint'] = $ancestorselector;
4450 * If you call this method the action menu will be displayed but will not be enhanced.
4452 * By not displaying the menu enhanced all items will be displayed in a single row.
4454 * @deprecated since Moodle 3.2
4456 public function do_not_enhance() {
4457 debugging('The method action_menu::do_not_enhance() is deprecated, use a list of action_icon instead.', DEBUG_DEVELOPER);
4461 * Returns true if this action menu will be enhanced.
4463 * @return bool
4465 public function will_be_enhanced() {
4466 return isset($this->attributes['data-enhance']);
4470 * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
4472 * This property can be useful when the action menu is displayed within a parent element that is either floated
4473 * or relatively positioned.
4474 * In that situation the width of the menu is determined by the width of the parent element which may not be large
4475 * enough for the menu items without them wrapping.
4476 * This disables the wrapping so that the menu takes on the width of the longest item.
4478 * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
4480 public function set_nowrap_on_items($value = true) {
4481 $class = 'nowrap-items';
4482 if (!empty($this->attributes['class'])) {
4483 $pos = strpos($this->attributes['class'], $class);
4484 if ($value === true && $pos === false) {
4485 // The value is true and the class has not been set yet. Add it.
4486 $this->attributes['class'] .= ' '.$class;
4487 } else if ($value === false && $pos !== false) {
4488 // The value is false and the class has been set. Remove it.
4489 $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class));
4491 } else if ($value) {
4492 // The value is true and the class has not been set yet. Add it.
4493 $this->attributes['class'] = $class;
4498 * Export for template.
4500 * @param renderer_base $output The renderer.
4501 * @return stdClass
4503 public function export_for_template(renderer_base $output) {
4504 $data = new stdClass();
4505 $attributes = $this->attributes;
4506 $attributesprimary = $this->attributesprimary;
4507 $attributessecondary = $this->attributessecondary;
4509 $data->instance = $this->instance;
4511 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
4512 unset($attributes['class']);
4514 $data->attributes = array_map(function($key, $value) {
4515 return [ 'name' => $key, 'value' => $value ];
4516 }, array_keys($attributes), $attributes);
4518 $primary = new stdClass();
4519 $primary->title = '';
4520 $primary->prioritise = $this->prioritise;
4522 $primary->classes = isset($attributesprimary['class']) ? $attributesprimary['class'] : '';
4523 unset($attributesprimary['class']);
4524 $primary->attributes = array_map(function($key, $value) {
4525 return [ 'name' => $key, 'value' => $value ];
4526 }, array_keys($attributesprimary), $attributesprimary);
4528 $actionicon = $this->actionicon;
4529 if (!empty($this->menutrigger)) {
4530 $primary->menutrigger = $this->menutrigger;
4531 $primary->triggerextraclasses = $this->triggerextraclasses;
4532 if ($this->actionlabel) {
4533 $primary->title = $this->actionlabel;
4534 } else if ($this->actiontext) {
4535 $primary->title = $this->actiontext;
4536 } else {
4537 $primary->title = strip_tags($this->menutrigger);
4539 } else {
4540 $primary->title = get_string('actionsmenu');
4541 $actionicon = new pix_icon('t/edit_menu', '', 'moodle', ['class' => 'iconsmall actionmenu', 'title' => $primary->title]);
4544 if ($actionicon instanceof pix_icon) {
4545 $primary->icon = $actionicon->export_for_pix();
4546 if (!empty($actionicon->attributes['alt'])) {
4547 $primary->title = $actionicon->attributes['alt'];
4549 } else {
4550 $primary->iconraw = $actionicon ? $output->render($actionicon) : '';
4553 $primary->actiontext = $this->actiontext ? (string) $this->actiontext : '';
4554 $primary->items = array_map(function($item) use ($output) {
4555 $data = (object) [];
4556 if ($item instanceof action_menu_link) {
4557 $data->actionmenulink = $item->export_for_template($output);
4558 } else if ($item instanceof action_menu_filler) {
4559 $data->actionmenufiller = $item->export_for_template($output);
4560 } else if ($item instanceof action_link) {
4561 $data->actionlink = $item->export_for_template($output);
4562 } else if ($item instanceof pix_icon) {
4563 $data->pixicon = $item->export_for_template($output);
4564 } else {
4565 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4567 return $data;
4568 }, $this->primaryactions);
4570 $secondary = new stdClass();
4571 $secondary->classes = isset($attributessecondary['class']) ? $attributessecondary['class'] : '';
4572 unset($attributessecondary['class']);
4573 $secondary->attributes = array_map(function($key, $value) {
4574 return [ 'name' => $key, 'value' => $value ];
4575 }, array_keys($attributessecondary), $attributessecondary);
4576 $secondary->items = array_map(function($item) use ($output) {
4577 $data = (object) [];
4578 if ($item instanceof action_menu_link) {
4579 $data->actionmenulink = $item->export_for_template($output);
4580 } else if ($item instanceof action_menu_filler) {
4581 $data->actionmenufiller = $item->export_for_template($output);
4582 } else if ($item instanceof action_link) {
4583 $data->actionlink = $item->export_for_template($output);
4584 } else if ($item instanceof pix_icon) {
4585 $data->pixicon = $item->export_for_template($output);
4586 } else {
4587 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4589 return $data;
4590 }, $this->secondaryactions);
4592 $data->primary = $primary;
4593 $data->secondary = $secondary;
4595 return $data;
4601 * An action menu filler
4603 * @package core
4604 * @category output
4605 * @copyright 2013 Andrew Nicols
4606 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4608 class action_menu_filler extends action_link implements renderable {
4611 * True if this is a primary action. False if not.
4612 * @var bool
4614 public $primary = true;
4617 * Constructs the object.
4619 public function __construct() {
4624 * An action menu action
4626 * @package core
4627 * @category output
4628 * @copyright 2013 Sam Hemelryk
4629 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4631 class action_menu_link extends action_link implements renderable {
4634 * True if this is a primary action. False if not.
4635 * @var bool
4637 public $primary = true;
4640 * The action menu this link has been added to.
4641 * @var action_menu
4643 public $actionmenu = null;
4646 * Constructs the object.
4648 * @param moodle_url $url The URL for the action.
4649 * @param pix_icon $icon The icon to represent the action.
4650 * @param string $text The text to represent the action.
4651 * @param bool $primary Whether this is a primary action or not.
4652 * @param array $attributes Any attribtues associated with the action.
4654 public function __construct(moodle_url $url, pix_icon $icon = null, $text, $primary = true, array $attributes = array()) {
4655 parent::__construct($url, $text, null, $attributes, $icon);
4656 $this->primary = (bool)$primary;
4657 $this->add_class('menu-action');
4658 $this->attributes['role'] = 'menuitem';
4662 * Export for template.
4664 * @param renderer_base $output The renderer.
4665 * @return stdClass
4667 public function export_for_template(renderer_base $output) {
4668 static $instance = 1;
4670 $data = parent::export_for_template($output);
4671 $data->instance = $instance++;
4673 // Ignore what the parent did with the attributes, except for ID and class.
4674 $data->attributes = [];
4675 $attributes = $this->attributes;
4676 unset($attributes['id']);
4677 unset($attributes['class']);
4679 // Handle text being a renderable.
4680 if ($this->text instanceof renderable) {
4681 $data->text = $this->render($this->text);
4684 $data->showtext = (!$this->icon || $this->primary === false);
4686 $data->icon = null;
4687 if ($this->icon) {
4688 $icon = $this->icon;
4689 if ($this->primary || !$this->actionmenu->will_be_enhanced()) {
4690 $attributes['title'] = $data->text;
4692 $data->icon = $icon ? $icon->export_for_pix() : null;
4695 $data->disabled = !empty($attributes['disabled']);
4696 unset($attributes['disabled']);
4698 $data->attributes = array_map(function($key, $value) {
4699 return [
4700 'name' => $key,
4701 'value' => $value
4703 }, array_keys($attributes), $attributes);
4705 return $data;
4710 * A primary action menu action
4712 * @package core
4713 * @category output
4714 * @copyright 2013 Sam Hemelryk
4715 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4717 class action_menu_link_primary extends action_menu_link {
4719 * Constructs the object.
4721 * @param moodle_url $url
4722 * @param pix_icon $icon
4723 * @param string $text
4724 * @param array $attributes
4726 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
4727 parent::__construct($url, $icon, $text, true, $attributes);
4732 * A secondary action menu action
4734 * @package core
4735 * @category output
4736 * @copyright 2013 Sam Hemelryk
4737 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4739 class action_menu_link_secondary extends action_menu_link {
4741 * Constructs the object.
4743 * @param moodle_url $url
4744 * @param pix_icon $icon
4745 * @param string $text
4746 * @param array $attributes
4748 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
4749 parent::__construct($url, $icon, $text, false, $attributes);
4754 * Represents a set of preferences groups.
4756 * @package core
4757 * @category output
4758 * @copyright 2015 Frédéric Massart - FMCorz.net
4759 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4761 class preferences_groups implements renderable {
4764 * Array of preferences_group.
4765 * @var array
4767 public $groups;
4770 * Constructor.
4771 * @param array $groups of preferences_group
4773 public function __construct($groups) {
4774 $this->groups = $groups;
4780 * Represents a group of preferences page link.
4782 * @package core
4783 * @category output
4784 * @copyright 2015 Frédéric Massart - FMCorz.net
4785 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4787 class preferences_group implements renderable {
4790 * Title of the group.
4791 * @var string
4793 public $title;
4796 * Array of navigation_node.
4797 * @var array
4799 public $nodes;
4802 * Constructor.
4803 * @param string $title The title.
4804 * @param array $nodes of navigation_node.
4806 public function __construct($title, $nodes) {
4807 $this->title = $title;
4808 $this->nodes = $nodes;
4813 * Progress bar class.
4815 * Manages the display of a progress bar.
4817 * To use this class.
4818 * - construct
4819 * - call create (or use the 3rd param to the constructor)
4820 * - call update or update_full() or update() repeatedly
4822 * @copyright 2008 jamiesensei
4823 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4824 * @package core
4825 * @category output
4827 class progress_bar implements renderable, templatable {
4828 /** @var string html id */
4829 private $html_id;
4830 /** @var int total width */
4831 private $width;
4832 /** @var int last percentage printed */
4833 private $percent = 0;
4834 /** @var int time when last printed */
4835 private $lastupdate = 0;
4836 /** @var int when did we start printing this */
4837 private $time_start = 0;
4840 * Constructor
4842 * Prints JS code if $autostart true.
4844 * @param string $htmlid The container ID.
4845 * @param int $width The suggested width.
4846 * @param bool $autostart Whether to start the progress bar right away.
4848 public function __construct($htmlid = '', $width = 500, $autostart = false) {
4849 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
4850 debugging('progress_bar used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', DEBUG_DEVELOPER);
4853 if (!empty($htmlid)) {
4854 $this->html_id = $htmlid;
4855 } else {
4856 $this->html_id = 'pbar_'.uniqid();
4859 $this->width = $width;
4861 if ($autostart) {
4862 $this->create();
4867 * Create a new progress bar, this function will output html.
4869 * @return void Echo's output
4871 public function create() {
4872 global $OUTPUT;
4874 $this->time_start = microtime(true);
4875 if (CLI_SCRIPT) {
4876 return; // Temporary solution for cli scripts.
4879 flush();
4880 echo $OUTPUT->render($this);
4881 flush();
4885 * Update the progress bar.
4887 * @param int $percent From 1-100.
4888 * @param string $msg The message.
4889 * @return void Echo's output
4890 * @throws coding_exception
4892 private function _update($percent, $msg) {
4893 if (empty($this->time_start)) {
4894 throw new coding_exception('You must call create() (or use the $autostart ' .
4895 'argument to the constructor) before you try updating the progress bar.');
4898 if (CLI_SCRIPT) {
4899 return; // Temporary solution for cli scripts.
4902 $estimate = $this->estimate($percent);
4904 if ($estimate === null) {
4905 // Always do the first and last updates.
4906 } else if ($estimate == 0) {
4907 // Always do the last updates.
4908 } else if ($this->lastupdate + 20 < time()) {
4909 // We must update otherwise browser would time out.
4910 } else if (round($this->percent, 2) === round($percent, 2)) {
4911 // No significant change, no need to update anything.
4912 return;
4915 $estimatemsg = null;
4916 if (is_numeric($estimate)) {
4917 $estimatemsg = get_string('secondsleft', 'moodle', round($estimate, 2));
4920 $this->percent = round($percent, 2);
4921 $this->lastupdate = microtime(true);
4923 echo html_writer::script(js_writer::function_call('updateProgressBar',
4924 array($this->html_id, $this->percent, $msg, $estimatemsg)));
4925 flush();
4929 * Estimate how much time it is going to take.
4931 * @param int $pt From 1-100.
4932 * @return mixed Null (unknown), or int.
4934 private function estimate($pt) {
4935 if ($this->lastupdate == 0) {
4936 return null;
4938 if ($pt < 0.00001) {
4939 return null; // We do not know yet how long it will take.
4941 if ($pt > 99.99999) {
4942 return 0; // Nearly done, right?
4944 $consumed = microtime(true) - $this->time_start;
4945 if ($consumed < 0.001) {
4946 return null;
4949 return (100 - $pt) * ($consumed / $pt);
4953 * Update progress bar according percent.
4955 * @param int $percent From 1-100.
4956 * @param string $msg The message needed to be shown.
4958 public function update_full($percent, $msg) {
4959 $percent = max(min($percent, 100), 0);
4960 $this->_update($percent, $msg);
4964 * Update progress bar according the number of tasks.
4966 * @param int $cur Current task number.
4967 * @param int $total Total task number.
4968 * @param string $msg The message needed to be shown.
4970 public function update($cur, $total, $msg) {
4971 $percent = ($cur / $total) * 100;
4972 $this->update_full($percent, $msg);
4976 * Restart the progress bar.
4978 public function restart() {
4979 $this->percent = 0;
4980 $this->lastupdate = 0;
4981 $this->time_start = 0;
4985 * Export for template.
4987 * @param renderer_base $output The renderer.
4988 * @return array
4990 public function export_for_template(renderer_base $output) {
4991 return [
4992 'id' => $this->html_id,
4993 'width' => $this->width,