Merge branch 'MDL-57455_master-fix' of https://github.com/markn86/moodle
[moodle.git] / lib / outputcomponents.php
blobfac5c37ab8e8f5857b6ddc88c4684a575cf25e5a
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 $gravatardefault = str_replace($CFG->wwwroot, $CFG->httpswwwroot, $gravatardefault); // Replace by secure url.
436 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
437 } else {
438 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
442 return $defaulturl;
447 * Data structure representing a help icon.
449 * @copyright 2010 Petr Skoda (info@skodak.org)
450 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
451 * @since Moodle 2.0
452 * @package core
453 * @category output
455 class help_icon implements renderable, templatable {
458 * @var string lang pack identifier (without the "_help" suffix),
459 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
460 * must exist.
462 public $identifier;
465 * @var string Component name, the same as in get_string()
467 public $component;
470 * @var string Extra descriptive text next to the icon
472 public $linktext = null;
475 * Constructor
477 * @param string $identifier string for help page title,
478 * string with _help suffix is used for the actual help text.
479 * string with _link suffix is used to create a link to further info (if it exists)
480 * @param string $component
482 public function __construct($identifier, $component) {
483 $this->identifier = $identifier;
484 $this->component = $component;
488 * Verifies that both help strings exists, shows debug warnings if not
490 public function diag_strings() {
491 $sm = get_string_manager();
492 if (!$sm->string_exists($this->identifier, $this->component)) {
493 debugging("Help title string does not exist: [$this->identifier, $this->component]");
495 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
496 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
501 * Export this data so it can be used as the context for a mustache template.
503 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
504 * @return array
506 public function export_for_template(renderer_base $output) {
507 global $CFG;
509 $title = get_string($this->identifier, $this->component);
511 if (empty($this->linktext)) {
512 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
513 } else {
514 $alt = get_string('helpwiththis');
517 $data = get_formatted_help_string($this->identifier, $this->component, false);
519 $data->alt = $alt;
520 $data->icon = (new pix_icon('help', $alt, 'core', ['class' => 'iconhelp']))->export_for_template($output);
521 $data->linktext = $this->linktext;
522 $data->title = get_string('helpprefix2', '', trim($title, ". \t"));
523 $data->url = (new moodle_url($CFG->httpswwwroot . '/help.php', [
524 'component' => $this->component,
525 'identifier' => $this->identifier,
526 'lang' => current_language()
527 ]))->out(false);
529 $data->ltr = !right_to_left();
530 return $data;
536 * Data structure representing an icon font.
538 * @copyright 2016 Damyon Wiese
539 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
540 * @package core
541 * @category output
543 class pix_icon_font implements templatable {
546 * @var pix_icon $pixicon The original icon.
548 private $pixicon = null;
551 * @var string $key The mapped key.
553 private $key;
556 * @var bool $mapped The icon could not be mapped.
558 private $mapped;
561 * Constructor
563 * @param pix_icon $pixicon The original icon
565 public function __construct(pix_icon $pixicon) {
566 global $PAGE;
568 $this->pixicon = $pixicon;
569 $this->mapped = false;
570 $iconsystem = \core\output\icon_system::instance();
572 $this->key = $iconsystem->remap_icon_name($pixicon->pix, $pixicon->component);
573 if (!empty($this->key)) {
574 $this->mapped = true;
579 * Return true if this pix_icon was successfully mapped to an icon font.
581 * @return bool
583 public function is_mapped() {
584 return $this->mapped;
588 * Export this data so it can be used as the context for a mustache template.
590 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
591 * @return array
593 public function export_for_template(renderer_base $output) {
595 $pixdata = $this->pixicon->export_for_template($output);
597 $title = isset($this->pixicon->attributes['title']) ? $this->pixicon->attributes['title'] : '';
598 $alt = isset($this->pixicon->attributes['alt']) ? $this->pixicon->attributes['alt'] : '';
599 if (empty($title)) {
600 $title = $alt;
602 $data = array(
603 'extraclasses' => $pixdata['extraclasses'],
604 'title' => $title,
605 'alt' => $alt,
606 'key' => $this->key
609 return $data;
614 * Data structure representing an icon subtype.
616 * @copyright 2016 Damyon Wiese
617 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
618 * @package core
619 * @category output
621 class pix_icon_fontawesome extends pix_icon_font {
626 * Data structure representing an icon.
628 * @copyright 2010 Petr Skoda
629 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
630 * @since Moodle 2.0
631 * @package core
632 * @category output
634 class pix_icon implements renderable, templatable {
637 * @var string The icon name
639 var $pix;
642 * @var string The component the icon belongs to.
644 var $component;
647 * @var array An array of attributes to use on the icon
649 var $attributes = array();
652 * Constructor
654 * @param string $pix short icon name
655 * @param string $alt The alt text to use for the icon
656 * @param string $component component name
657 * @param array $attributes html attributes
659 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
660 global $PAGE;
662 $this->pix = $pix;
663 $this->component = $component;
664 $this->attributes = (array)$attributes;
666 if (empty($this->attributes['class'])) {
667 $this->attributes['class'] = '';
670 // Set an additional class for big icons so that they can be styled properly.
671 if (substr($pix, 0, 2) === 'b/') {
672 $this->attributes['class'] .= ' iconsize-big';
675 // If the alt is empty, don't place it in the attributes, otherwise it will override parent alt text.
676 if (!is_null($alt)) {
677 $this->attributes['alt'] = $alt;
679 // If there is no title, set it to the attribute.
680 if (!isset($this->attributes['title'])) {
681 $this->attributes['title'] = $this->attributes['alt'];
683 } else {
684 unset($this->attributes['alt']);
687 if (empty($this->attributes['title'])) {
688 // Remove the title attribute if empty, we probably want to use the parent node's title
689 // and some browsers might overwrite it with an empty title.
690 unset($this->attributes['title']);
695 * Export this data so it can be used as the context for a mustache template.
697 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
698 * @return array
700 public function export_for_template(renderer_base $output) {
701 $attributes = $this->attributes;
702 $extraclasses = '';
704 foreach ($attributes as $key => $item) {
705 if ($key == 'class') {
706 $extraclasses = $item;
707 unset($attributes[$key]);
708 break;
712 $attributes['src'] = $output->image_url($this->pix, $this->component)->out(false);
713 $templatecontext = array();
714 foreach ($attributes as $name => $value) {
715 $templatecontext[] = array('name' => $name, 'value' => $value);
717 $title = isset($attributes['title']) ? $attributes['title'] : '';
718 if (empty($title)) {
719 $title = isset($attributes['alt']) ? $attributes['alt'] : '';
721 $data = array(
722 'attributes' => $templatecontext,
723 'extraclasses' => $extraclasses
726 return $data;
730 * Much simpler version of export that will produce the data required to render this pix with the
731 * pix helper in a mustache tag.
733 * @return array
735 public function export_for_pix() {
736 $title = isset($this->attributes['title']) ? $this->attributes['title'] : '';
737 if (empty($title)) {
738 $title = isset($this->attributes['alt']) ? $this->attributes['alt'] : '';
740 return [
741 'key' => $this->pix,
742 'component' => $this->component,
743 'title' => $title
749 * Data structure representing an activity icon.
751 * The difference is that activity icons will always render with the standard icon system (no font icons).
753 * @copyright 2017 Damyon Wiese
754 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
755 * @package core
757 class image_icon extends pix_icon {
761 * Data structure representing an emoticon image
763 * @copyright 2010 David Mudrak
764 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
765 * @since Moodle 2.0
766 * @package core
767 * @category output
769 class pix_emoticon extends pix_icon implements renderable {
772 * Constructor
773 * @param string $pix short icon name
774 * @param string $alt alternative text
775 * @param string $component emoticon image provider
776 * @param array $attributes explicit HTML attributes
778 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
779 if (empty($attributes['class'])) {
780 $attributes['class'] = 'emoticon';
782 parent::__construct($pix, $alt, $component, $attributes);
787 * Data structure representing a simple form with only one button.
789 * @copyright 2009 Petr Skoda
790 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
791 * @since Moodle 2.0
792 * @package core
793 * @category output
795 class single_button implements renderable {
798 * @var moodle_url Target url
800 public $url;
803 * @var string Button label
805 public $label;
808 * @var string Form submit method post or get
810 public $method = 'post';
813 * @var string Wrapping div class
815 public $class = 'singlebutton';
818 * @var bool True if button is primary button. Used for styling.
820 public $primary = false;
823 * @var bool True if button disabled, false if normal
825 public $disabled = false;
828 * @var string Button tooltip
830 public $tooltip = null;
833 * @var string Form id
835 public $formid;
838 * @var array List of attached actions
840 public $actions = array();
843 * @var array $params URL Params
845 public $params;
848 * @var string Action id
850 public $actionid;
853 * Constructor
854 * @param moodle_url $url
855 * @param string $label button text
856 * @param string $method get or post submit method
858 public function __construct(moodle_url $url, $label, $method='post', $primary=false) {
859 $this->url = clone($url);
860 $this->label = $label;
861 $this->method = $method;
862 $this->primary = $primary;
866 * Shortcut for adding a JS confirm dialog when the button is clicked.
867 * The message must be a yes/no question.
869 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
871 public function add_confirm_action($confirmmessage) {
872 $this->add_action(new confirm_action($confirmmessage));
876 * Add action to the button.
877 * @param component_action $action
879 public function add_action(component_action $action) {
880 $this->actions[] = $action;
884 * Export data.
886 * @param renderer_base $output Renderer.
887 * @return stdClass
889 public function export_for_template(renderer_base $output) {
890 $url = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
892 $data = new stdClass();
893 $data->id = html_writer::random_id('single_button');
894 $data->formid = $this->formid;
895 $data->method = $this->method;
896 $data->url = $url === '' ? '#' : $url;
897 $data->label = $this->label;
898 $data->classes = $this->class;
899 $data->disabled = $this->disabled;
900 $data->tooltip = $this->tooltip;
901 $data->primary = $this->primary;
903 // Form parameters.
904 $params = $this->url->params();
905 if ($this->method === 'post') {
906 $params['sesskey'] = sesskey();
908 $data->params = array_map(function($key) use ($params) {
909 return ['name' => $key, 'value' => $params[$key]];
910 }, array_keys($params));
912 // Button actions.
913 $actions = $this->actions;
914 $data->actions = array_map(function($action) use ($output) {
915 return $action->export_for_template($output);
916 }, $actions);
917 $data->hasactions = !empty($data->actions);
919 return $data;
925 * Simple form with just one select field that gets submitted automatically.
927 * If JS not enabled small go button is printed too.
929 * @copyright 2009 Petr Skoda
930 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
931 * @since Moodle 2.0
932 * @package core
933 * @category output
935 class single_select implements renderable, templatable {
938 * @var moodle_url Target url - includes hidden fields
940 var $url;
943 * @var string Name of the select element.
945 var $name;
948 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
949 * it is also possible to specify optgroup as complex label array ex.:
950 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
951 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
953 var $options;
956 * @var string Selected option
958 var $selected;
961 * @var array Nothing selected
963 var $nothing;
966 * @var array Extra select field attributes
968 var $attributes = array();
971 * @var string Button label
973 var $label = '';
976 * @var array Button label's attributes
978 var $labelattributes = array();
981 * @var string Form submit method post or get
983 var $method = 'get';
986 * @var string Wrapping div class
988 var $class = 'singleselect';
991 * @var bool True if button disabled, false if normal
993 var $disabled = false;
996 * @var string Button tooltip
998 var $tooltip = null;
1001 * @var string Form id
1003 var $formid = null;
1006 * @var array List of attached actions
1008 var $helpicon = null;
1011 * Constructor
1012 * @param moodle_url $url form action target, includes hidden fields
1013 * @param string $name name of selection field - the changing parameter in url
1014 * @param array $options list of options
1015 * @param string $selected selected element
1016 * @param array $nothing
1017 * @param string $formid
1019 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1020 $this->url = $url;
1021 $this->name = $name;
1022 $this->options = $options;
1023 $this->selected = $selected;
1024 $this->nothing = $nothing;
1025 $this->formid = $formid;
1029 * Shortcut for adding a JS confirm dialog when the button is clicked.
1030 * The message must be a yes/no question.
1032 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
1034 public function add_confirm_action($confirmmessage) {
1035 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
1039 * Add action to the button.
1041 * @param component_action $action
1043 public function add_action(component_action $action) {
1044 $this->actions[] = $action;
1048 * Adds help icon.
1050 * @deprecated since Moodle 2.0
1052 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1053 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1057 * Adds help icon.
1059 * @param string $identifier The keyword that defines a help page
1060 * @param string $component
1062 public function set_help_icon($identifier, $component = 'moodle') {
1063 $this->helpicon = new help_icon($identifier, $component);
1067 * Sets select's label
1069 * @param string $label
1070 * @param array $attributes (optional)
1072 public function set_label($label, $attributes = array()) {
1073 $this->label = $label;
1074 $this->labelattributes = $attributes;
1079 * Export data.
1081 * @param renderer_base $output Renderer.
1082 * @return stdClass
1084 public function export_for_template(renderer_base $output) {
1085 $attributes = $this->attributes;
1087 $data = new stdClass();
1088 $data->name = $this->name;
1089 $data->method = $this->method;
1090 $data->action = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
1091 $data->classes = $this->class;
1092 $data->label = $this->label;
1093 $data->disabled = $this->disabled;
1094 $data->title = $this->tooltip;
1095 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('single_select_f');
1096 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('single_select');
1097 unset($attributes['id']);
1099 // Form parameters.
1100 $params = $this->url->params();
1101 if ($this->method === 'post') {
1102 $params['sesskey'] = sesskey();
1104 $data->params = array_map(function($key) use ($params) {
1105 return ['name' => $key, 'value' => $params[$key]];
1106 }, array_keys($params));
1108 // Select options.
1109 $hasnothing = false;
1110 if (is_string($this->nothing) && $this->nothing !== '') {
1111 $nothing = ['' => $this->nothing];
1112 $hasnothing = true;
1113 } else if (is_array($this->nothing)) {
1114 $nothingvalue = reset($this->nothing);
1115 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1116 $nothing = [key($this->nothing) => get_string('choosedots')];
1117 } else {
1118 $nothing = $this->nothing;
1120 $hasnothing = true;
1122 if ($hasnothing) {
1123 $options = $nothing + $this->options;
1124 } else {
1125 $options = $this->options;
1128 foreach ($options as $value => $name) {
1129 if (is_array($options[$value])) {
1130 foreach ($options[$value] as $optgroupname => $optgroupvalues) {
1131 $sublist = [];
1132 foreach ($optgroupvalues as $optvalue => $optname) {
1133 $sublist[] = [
1134 'value' => $optvalue,
1135 'name' => $optname,
1136 'selected' => strval($this->selected) === strval($optvalue),
1139 $data->options[] = [
1140 'name' => $optgroupname,
1141 'optgroup' => true,
1142 'options' => $sublist
1145 } else {
1146 $data->options[] = [
1147 'value' => $value,
1148 'name' => $options[$value],
1149 'selected' => strval($this->selected) === strval($value),
1150 'optgroup' => false
1155 // Label attributes.
1156 $data->labelattributes = [];
1157 foreach ($this->labelattributes as $key => $value) {
1158 $data->labelattributes = ['name' => $key, 'value' => $value];
1161 // Help icon.
1162 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1164 return $data;
1169 * Simple URL selection widget description.
1171 * @copyright 2009 Petr Skoda
1172 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1173 * @since Moodle 2.0
1174 * @package core
1175 * @category output
1177 class url_select implements renderable, templatable {
1179 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
1180 * it is also possible to specify optgroup as complex label array ex.:
1181 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1182 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1184 var $urls;
1187 * @var string Selected option
1189 var $selected;
1192 * @var array Nothing selected
1194 var $nothing;
1197 * @var array Extra select field attributes
1199 var $attributes = array();
1202 * @var string Button label
1204 var $label = '';
1207 * @var array Button label's attributes
1209 var $labelattributes = array();
1212 * @var string Wrapping div class
1214 var $class = 'urlselect';
1217 * @var bool True if button disabled, false if normal
1219 var $disabled = false;
1222 * @var string Button tooltip
1224 var $tooltip = null;
1227 * @var string Form id
1229 var $formid = null;
1232 * @var array List of attached actions
1234 var $helpicon = null;
1237 * @var string If set, makes button visible with given name for button
1239 var $showbutton = null;
1242 * Constructor
1243 * @param array $urls list of options
1244 * @param string $selected selected element
1245 * @param array $nothing
1246 * @param string $formid
1247 * @param string $showbutton Set to text of button if it should be visible
1248 * or null if it should be hidden (hidden version always has text 'go')
1250 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
1251 $this->urls = $urls;
1252 $this->selected = $selected;
1253 $this->nothing = $nothing;
1254 $this->formid = $formid;
1255 $this->showbutton = $showbutton;
1259 * Adds help icon.
1261 * @deprecated since Moodle 2.0
1263 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1264 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1268 * Adds help icon.
1270 * @param string $identifier The keyword that defines a help page
1271 * @param string $component
1273 public function set_help_icon($identifier, $component = 'moodle') {
1274 $this->helpicon = new help_icon($identifier, $component);
1278 * Sets select's label
1280 * @param string $label
1281 * @param array $attributes (optional)
1283 public function set_label($label, $attributes = array()) {
1284 $this->label = $label;
1285 $this->labelattributes = $attributes;
1289 * Clean a URL.
1291 * @param string $value The URL.
1292 * @return The cleaned URL.
1294 protected function clean_url($value) {
1295 global $CFG;
1297 if (empty($value)) {
1298 // Nothing.
1300 } else if (strpos($value, $CFG->wwwroot . '/') === 0) {
1301 $value = str_replace($CFG->wwwroot, '', $value);
1303 } else if (strpos($value, '/') !== 0) {
1304 debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER);
1307 return $value;
1311 * Flatten the options for Mustache.
1313 * This also cleans the URLs.
1315 * @param array $options The options.
1316 * @param array $nothing The nothing option.
1317 * @return array
1319 protected function flatten_options($options, $nothing) {
1320 $flattened = [];
1322 foreach ($options as $value => $option) {
1323 if (is_array($option)) {
1324 foreach ($option as $groupname => $optoptions) {
1325 if (!isset($flattened[$groupname])) {
1326 $flattened[$groupname] = [
1327 'name' => $groupname,
1328 'isgroup' => true,
1329 'options' => []
1332 foreach ($optoptions as $optvalue => $optoption) {
1333 $cleanedvalue = $this->clean_url($optvalue);
1334 $flattened[$groupname]['options'][$cleanedvalue] = [
1335 'name' => $optoption,
1336 'value' => $cleanedvalue,
1337 'selected' => $this->selected == $optvalue,
1342 } else {
1343 $cleanedvalue = $this->clean_url($value);
1344 $flattened[$cleanedvalue] = [
1345 'name' => $option,
1346 'value' => $cleanedvalue,
1347 'selected' => $this->selected == $value,
1352 if (!empty($nothing)) {
1353 $value = key($nothing);
1354 $name = reset($nothing);
1355 $flattened = [
1356 $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value]
1357 ] + $flattened;
1360 // Make non-associative array.
1361 foreach ($flattened as $key => $value) {
1362 if (!empty($value['options'])) {
1363 $flattened[$key]['options'] = array_values($value['options']);
1366 $flattened = array_values($flattened);
1368 return $flattened;
1372 * Export for template.
1374 * @param renderer_base $output Renderer.
1375 * @return stdClass
1377 public function export_for_template(renderer_base $output) {
1378 $attributes = $this->attributes;
1380 $data = new stdClass();
1381 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('url_select_f');
1382 $data->classes = $this->class;
1383 $data->label = $this->label;
1384 $data->disabled = $this->disabled;
1385 $data->title = $this->tooltip;
1386 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('url_select');
1387 $data->sesskey = sesskey();
1388 $data->action = (new moodle_url('/course/jumpto.php'))->out(false);
1390 // Remove attributes passed as property directly.
1391 unset($attributes['class']);
1392 unset($attributes['id']);
1393 unset($attributes['name']);
1394 unset($attributes['title']);
1396 $data->showbutton = $this->showbutton;
1398 // Select options.
1399 $nothing = false;
1400 if (is_string($this->nothing) && $this->nothing !== '') {
1401 $nothing = ['' => $this->nothing];
1402 } else if (is_array($this->nothing)) {
1403 $nothingvalue = reset($this->nothing);
1404 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1405 $nothing = [key($this->nothing) => get_string('choosedots')];
1406 } else {
1407 $nothing = $this->nothing;
1410 $data->options = $this->flatten_options($this->urls, $nothing);
1412 // Label attributes.
1413 $data->labelattributes = [];
1414 foreach ($this->labelattributes as $key => $value) {
1415 $data->labelattributes[] = ['name' => $key, 'value' => $value];
1418 // Help icon.
1419 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1421 // Finally all the remaining attributes.
1422 $data->attributes = [];
1423 foreach ($this->attributes as $key => $value) {
1424 $data->attributes = ['name' => $key, 'value' => $value];
1427 return $data;
1432 * Data structure describing html link with special action attached.
1434 * @copyright 2010 Petr Skoda
1435 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1436 * @since Moodle 2.0
1437 * @package core
1438 * @category output
1440 class action_link implements renderable {
1443 * @var moodle_url Href url
1445 public $url;
1448 * @var string Link text HTML fragment
1450 public $text;
1453 * @var array HTML attributes
1455 public $attributes;
1458 * @var array List of actions attached to link
1460 public $actions;
1463 * @var pix_icon Optional pix icon to render with the link
1465 public $icon;
1468 * Constructor
1469 * @param moodle_url $url
1470 * @param string $text HTML fragment
1471 * @param component_action $action
1472 * @param array $attributes associative array of html link attributes + disabled
1473 * @param pix_icon $icon optional pix_icon to render with the link text
1475 public function __construct(moodle_url $url,
1476 $text,
1477 component_action $action=null,
1478 array $attributes=null,
1479 pix_icon $icon=null) {
1480 $this->url = clone($url);
1481 $this->text = $text;
1482 $this->attributes = (array)$attributes;
1483 if ($action) {
1484 $this->add_action($action);
1486 $this->icon = $icon;
1490 * Add action to the link.
1492 * @param component_action $action
1494 public function add_action(component_action $action) {
1495 $this->actions[] = $action;
1499 * Adds a CSS class to this action link object
1500 * @param string $class
1502 public function add_class($class) {
1503 if (empty($this->attributes['class'])) {
1504 $this->attributes['class'] = $class;
1505 } else {
1506 $this->attributes['class'] .= ' ' . $class;
1511 * Returns true if the specified class has been added to this link.
1512 * @param string $class
1513 * @return bool
1515 public function has_class($class) {
1516 return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
1520 * Return the rendered HTML for the icon. Useful for rendering action links in a template.
1521 * @return string
1523 public function get_icon_html() {
1524 global $OUTPUT;
1525 if (!$this->icon) {
1526 return '';
1528 return $OUTPUT->render($this->icon);
1532 * Export for template.
1534 * @param renderer_base $output The renderer.
1535 * @return stdClass
1537 public function export_for_template(renderer_base $output) {
1538 $data = new stdClass();
1539 $attributes = $this->attributes;
1541 if (empty($attributes['id'])) {
1542 $attributes['id'] = html_writer::random_id('action_link');
1544 $data->id = $attributes['id'];
1545 unset($attributes['id']);
1547 $data->disabled = !empty($attributes['disabled']);
1548 unset($attributes['disabled']);
1550 $data->text = $this->text instanceof renderable ? $output->render($this->text) : (string) $this->text;
1551 $data->url = $this->url ? $this->url->out(false) : '';
1552 $data->icon = $this->icon ? $this->icon->export_for_pix() : null;
1553 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
1554 unset($attributes['class']);
1556 $data->attributes = array_map(function($key, $value) {
1557 return [
1558 'name' => $key,
1559 'value' => $value
1561 }, array_keys($attributes), $attributes);
1563 $data->actions = array_map(function($action) use ($output) {
1564 return $action->export_for_template($output);
1565 }, !empty($this->actions) ? $this->actions : []);
1566 $data->hasactions = !empty($this->actions);
1568 return $data;
1573 * Simple html output class
1575 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1576 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1577 * @since Moodle 2.0
1578 * @package core
1579 * @category output
1581 class html_writer {
1584 * Outputs a tag with attributes and contents
1586 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1587 * @param string $contents What goes between the opening and closing tags
1588 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1589 * @return string HTML fragment
1591 public static function tag($tagname, $contents, array $attributes = null) {
1592 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1596 * Outputs an opening tag with attributes
1598 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1599 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1600 * @return string HTML fragment
1602 public static function start_tag($tagname, array $attributes = null) {
1603 return '<' . $tagname . self::attributes($attributes) . '>';
1607 * Outputs a closing tag
1609 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1610 * @return string HTML fragment
1612 public static function end_tag($tagname) {
1613 return '</' . $tagname . '>';
1617 * Outputs an empty tag with attributes
1619 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1620 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1621 * @return string HTML fragment
1623 public static function empty_tag($tagname, array $attributes = null) {
1624 return '<' . $tagname . self::attributes($attributes) . ' />';
1628 * Outputs a tag, but only if the contents are not empty
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 nonempty_tag($tagname, $contents, array $attributes = null) {
1636 if ($contents === '' || is_null($contents)) {
1637 return '';
1639 return self::tag($tagname, $contents, $attributes);
1643 * Outputs a HTML attribute and value
1645 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1646 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1647 * @return string HTML fragment
1649 public static function attribute($name, $value) {
1650 if ($value instanceof moodle_url) {
1651 return ' ' . $name . '="' . $value->out() . '"';
1654 // special case, we do not want these in output
1655 if ($value === null) {
1656 return '';
1659 // no sloppy trimming here!
1660 return ' ' . $name . '="' . s($value) . '"';
1664 * Outputs a list of HTML attributes and values
1666 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1667 * The values will be escaped with {@link s()}
1668 * @return string HTML fragment
1670 public static function attributes(array $attributes = null) {
1671 $attributes = (array)$attributes;
1672 $output = '';
1673 foreach ($attributes as $name => $value) {
1674 $output .= self::attribute($name, $value);
1676 return $output;
1680 * Generates a simple image tag with attributes.
1682 * @param string $src The source of image
1683 * @param string $alt The alternate text for image
1684 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1685 * @return string HTML fragment
1687 public static function img($src, $alt, array $attributes = null) {
1688 $attributes = (array)$attributes;
1689 $attributes['src'] = $src;
1690 $attributes['alt'] = $alt;
1692 return self::empty_tag('img', $attributes);
1696 * Generates random html element id.
1698 * @staticvar int $counter
1699 * @staticvar type $uniq
1700 * @param string $base A string fragment that will be included in the random ID.
1701 * @return string A unique ID
1703 public static function random_id($base='random') {
1704 static $counter = 0;
1705 static $uniq;
1707 if (!isset($uniq)) {
1708 $uniq = uniqid();
1711 $counter++;
1712 return $base.$uniq.$counter;
1716 * Generates a simple html link
1718 * @param string|moodle_url $url The URL
1719 * @param string $text The text
1720 * @param array $attributes HTML attributes
1721 * @return string HTML fragment
1723 public static function link($url, $text, array $attributes = null) {
1724 $attributes = (array)$attributes;
1725 $attributes['href'] = $url;
1726 return self::tag('a', $text, $attributes);
1730 * Generates a simple checkbox with optional label
1732 * @param string $name The name of the checkbox
1733 * @param string $value The value of the checkbox
1734 * @param bool $checked Whether the checkbox is checked
1735 * @param string $label The label for the checkbox
1736 * @param array $attributes Any attributes to apply to the checkbox
1737 * @return string html fragment
1739 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1740 $attributes = (array)$attributes;
1741 $output = '';
1743 if ($label !== '' and !is_null($label)) {
1744 if (empty($attributes['id'])) {
1745 $attributes['id'] = self::random_id('checkbox_');
1748 $attributes['type'] = 'checkbox';
1749 $attributes['value'] = $value;
1750 $attributes['name'] = $name;
1751 $attributes['checked'] = $checked ? 'checked' : null;
1753 $output .= self::empty_tag('input', $attributes);
1755 if ($label !== '' and !is_null($label)) {
1756 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1759 return $output;
1763 * Generates a simple select yes/no form field
1765 * @param string $name name of select element
1766 * @param bool $selected
1767 * @param array $attributes - html select element attributes
1768 * @return string HTML fragment
1770 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1771 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1772 return self::select($options, $name, $selected, null, $attributes);
1776 * Generates a simple select form field
1778 * @param array $options associative array value=>label ex.:
1779 * array(1=>'One, 2=>Two)
1780 * it is also possible to specify optgroup as complex label array ex.:
1781 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1782 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1783 * @param string $name name of select element
1784 * @param string|array $selected value or array of values depending on multiple attribute
1785 * @param array|bool $nothing add nothing selected option, or false of not added
1786 * @param array $attributes html select element attributes
1787 * @return string HTML fragment
1789 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1790 $attributes = (array)$attributes;
1791 if (is_array($nothing)) {
1792 foreach ($nothing as $k=>$v) {
1793 if ($v === 'choose' or $v === 'choosedots') {
1794 $nothing[$k] = get_string('choosedots');
1797 $options = $nothing + $options; // keep keys, do not override
1799 } else if (is_string($nothing) and $nothing !== '') {
1800 // BC
1801 $options = array(''=>$nothing) + $options;
1804 // we may accept more values if multiple attribute specified
1805 $selected = (array)$selected;
1806 foreach ($selected as $k=>$v) {
1807 $selected[$k] = (string)$v;
1810 if (!isset($attributes['id'])) {
1811 $id = 'menu'.$name;
1812 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1813 $id = str_replace('[', '', $id);
1814 $id = str_replace(']', '', $id);
1815 $attributes['id'] = $id;
1818 if (!isset($attributes['class'])) {
1819 $class = 'menu'.$name;
1820 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1821 $class = str_replace('[', '', $class);
1822 $class = str_replace(']', '', $class);
1823 $attributes['class'] = $class;
1825 $attributes['class'] = 'select custom-select ' . $attributes['class']; // Add 'select' selector always.
1827 $attributes['name'] = $name;
1829 if (!empty($attributes['disabled'])) {
1830 $attributes['disabled'] = 'disabled';
1831 } else {
1832 unset($attributes['disabled']);
1835 $output = '';
1836 foreach ($options as $value=>$label) {
1837 if (is_array($label)) {
1838 // ignore key, it just has to be unique
1839 $output .= self::select_optgroup(key($label), current($label), $selected);
1840 } else {
1841 $output .= self::select_option($label, $value, $selected);
1844 return self::tag('select', $output, $attributes);
1848 * Returns HTML to display a select box option.
1850 * @param string $label The label to display as the option.
1851 * @param string|int $value The value the option represents
1852 * @param array $selected An array of selected options
1853 * @return string HTML fragment
1855 private static function select_option($label, $value, array $selected) {
1856 $attributes = array();
1857 $value = (string)$value;
1858 if (in_array($value, $selected, true)) {
1859 $attributes['selected'] = 'selected';
1861 $attributes['value'] = $value;
1862 return self::tag('option', $label, $attributes);
1866 * Returns HTML to display a select box option group.
1868 * @param string $groupname The label to use for the group
1869 * @param array $options The options in the group
1870 * @param array $selected An array of selected values.
1871 * @return string HTML fragment.
1873 private static function select_optgroup($groupname, $options, array $selected) {
1874 if (empty($options)) {
1875 return '';
1877 $attributes = array('label'=>$groupname);
1878 $output = '';
1879 foreach ($options as $value=>$label) {
1880 $output .= self::select_option($label, $value, $selected);
1882 return self::tag('optgroup', $output, $attributes);
1886 * This is a shortcut for making an hour selector menu.
1888 * @param string $type The type of selector (years, months, days, hours, minutes)
1889 * @param string $name fieldname
1890 * @param int $currenttime A default timestamp in GMT
1891 * @param int $step minute spacing
1892 * @param array $attributes - html select element attributes
1893 * @return HTML fragment
1895 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1896 global $OUTPUT;
1898 if (!$currenttime) {
1899 $currenttime = time();
1901 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1902 $currentdate = $calendartype->timestamp_to_date_array($currenttime);
1903 $userdatetype = $type;
1904 $timeunits = array();
1906 switch ($type) {
1907 case 'years':
1908 $timeunits = $calendartype->get_years();
1909 $userdatetype = 'year';
1910 break;
1911 case 'months':
1912 $timeunits = $calendartype->get_months();
1913 $userdatetype = 'month';
1914 $currentdate['month'] = (int)$currentdate['mon'];
1915 break;
1916 case 'days':
1917 $timeunits = $calendartype->get_days();
1918 $userdatetype = 'mday';
1919 break;
1920 case 'hours':
1921 for ($i=0; $i<=23; $i++) {
1922 $timeunits[$i] = sprintf("%02d",$i);
1924 break;
1925 case 'minutes':
1926 if ($step != 1) {
1927 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1930 for ($i=0; $i<=59; $i+=$step) {
1931 $timeunits[$i] = sprintf("%02d",$i);
1933 break;
1934 default:
1935 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1938 $attributes = (array) $attributes;
1939 $data = (object) [
1940 'name' => $name,
1941 'id' => !empty($attributes['id']) ? $attributes['id'] : self::random_id('ts_'),
1942 'label' => get_string(substr($type, 0, -1), 'form'),
1943 'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) {
1944 return [
1945 'name' => $timeunits[$value],
1946 'value' => $value,
1947 'selected' => $currentdate[$userdatetype] == $value
1949 }, array_keys($timeunits)),
1952 unset($attributes['id']);
1953 unset($attributes['name']);
1954 $data->attributes = array_map(function($name) use ($attributes) {
1955 return [
1956 'name' => $name,
1957 'value' => $attributes[$name]
1959 }, array_keys($attributes));
1961 return $OUTPUT->render_from_template('core/select_time', $data);
1965 * Shortcut for quick making of lists
1967 * Note: 'list' is a reserved keyword ;-)
1969 * @param array $items
1970 * @param array $attributes
1971 * @param string $tag ul or ol
1972 * @return string
1974 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1975 $output = html_writer::start_tag($tag, $attributes)."\n";
1976 foreach ($items as $item) {
1977 $output .= html_writer::tag('li', $item)."\n";
1979 $output .= html_writer::end_tag($tag);
1980 return $output;
1984 * Returns hidden input fields created from url parameters.
1986 * @param moodle_url $url
1987 * @param array $exclude list of excluded parameters
1988 * @return string HTML fragment
1990 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1991 $exclude = (array)$exclude;
1992 $params = $url->params();
1993 foreach ($exclude as $key) {
1994 unset($params[$key]);
1997 $output = '';
1998 foreach ($params as $key => $value) {
1999 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
2000 $output .= self::empty_tag('input', $attributes)."\n";
2002 return $output;
2006 * Generate a script tag containing the the specified code.
2008 * @param string $jscode the JavaScript code
2009 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
2010 * @return string HTML, the code wrapped in <script> tags.
2012 public static function script($jscode, $url=null) {
2013 if ($jscode) {
2014 $attributes = array('type'=>'text/javascript');
2015 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
2017 } else if ($url) {
2018 $attributes = array('type'=>'text/javascript', 'src'=>$url);
2019 return self::tag('script', '', $attributes) . "\n";
2021 } else {
2022 return '';
2027 * Renders HTML table
2029 * This method may modify the passed instance by adding some default properties if they are not set yet.
2030 * If this is not what you want, you should make a full clone of your data before passing them to this
2031 * method. In most cases this is not an issue at all so we do not clone by default for performance
2032 * and memory consumption reasons.
2034 * @param html_table $table data to be rendered
2035 * @return string HTML code
2037 public static function table(html_table $table) {
2038 // prepare table data and populate missing properties with reasonable defaults
2039 if (!empty($table->align)) {
2040 foreach ($table->align as $key => $aa) {
2041 if ($aa) {
2042 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
2043 } else {
2044 $table->align[$key] = null;
2048 if (!empty($table->size)) {
2049 foreach ($table->size as $key => $ss) {
2050 if ($ss) {
2051 $table->size[$key] = 'width:'. $ss .';';
2052 } else {
2053 $table->size[$key] = null;
2057 if (!empty($table->wrap)) {
2058 foreach ($table->wrap as $key => $ww) {
2059 if ($ww) {
2060 $table->wrap[$key] = 'white-space:nowrap;';
2061 } else {
2062 $table->wrap[$key] = '';
2066 if (!empty($table->head)) {
2067 foreach ($table->head as $key => $val) {
2068 if (!isset($table->align[$key])) {
2069 $table->align[$key] = null;
2071 if (!isset($table->size[$key])) {
2072 $table->size[$key] = null;
2074 if (!isset($table->wrap[$key])) {
2075 $table->wrap[$key] = null;
2080 if (empty($table->attributes['class'])) {
2081 $table->attributes['class'] = 'generaltable';
2083 if (!empty($table->tablealign)) {
2084 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
2087 // explicitly assigned properties override those defined via $table->attributes
2088 $table->attributes['class'] = trim($table->attributes['class']);
2089 $attributes = array_merge($table->attributes, array(
2090 'id' => $table->id,
2091 'width' => $table->width,
2092 'summary' => $table->summary,
2093 'cellpadding' => $table->cellpadding,
2094 'cellspacing' => $table->cellspacing,
2096 $output = html_writer::start_tag('table', $attributes) . "\n";
2098 $countcols = 0;
2100 // Output a caption if present.
2101 if (!empty($table->caption)) {
2102 $captionattributes = array();
2103 if ($table->captionhide) {
2104 $captionattributes['class'] = 'accesshide';
2106 $output .= html_writer::tag(
2107 'caption',
2108 $table->caption,
2109 $captionattributes
2113 if (!empty($table->head)) {
2114 $countcols = count($table->head);
2116 $output .= html_writer::start_tag('thead', array()) . "\n";
2117 $output .= html_writer::start_tag('tr', array()) . "\n";
2118 $keys = array_keys($table->head);
2119 $lastkey = end($keys);
2121 foreach ($table->head as $key => $heading) {
2122 // Convert plain string headings into html_table_cell objects
2123 if (!($heading instanceof html_table_cell)) {
2124 $headingtext = $heading;
2125 $heading = new html_table_cell();
2126 $heading->text = $headingtext;
2127 $heading->header = true;
2130 if ($heading->header !== false) {
2131 $heading->header = true;
2134 if ($heading->header && empty($heading->scope)) {
2135 $heading->scope = 'col';
2138 $heading->attributes['class'] .= ' header c' . $key;
2139 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
2140 $heading->colspan = $table->headspan[$key];
2141 $countcols += $table->headspan[$key] - 1;
2144 if ($key == $lastkey) {
2145 $heading->attributes['class'] .= ' lastcol';
2147 if (isset($table->colclasses[$key])) {
2148 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
2150 $heading->attributes['class'] = trim($heading->attributes['class']);
2151 $attributes = array_merge($heading->attributes, array(
2152 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
2153 'scope' => $heading->scope,
2154 'colspan' => $heading->colspan,
2157 $tagtype = 'td';
2158 if ($heading->header === true) {
2159 $tagtype = 'th';
2161 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
2163 $output .= html_writer::end_tag('tr') . "\n";
2164 $output .= html_writer::end_tag('thead') . "\n";
2166 if (empty($table->data)) {
2167 // For valid XHTML strict every table must contain either a valid tr
2168 // or a valid tbody... both of which must contain a valid td
2169 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
2170 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
2171 $output .= html_writer::end_tag('tbody');
2175 if (!empty($table->data)) {
2176 $keys = array_keys($table->data);
2177 $lastrowkey = end($keys);
2178 $output .= html_writer::start_tag('tbody', array());
2180 foreach ($table->data as $key => $row) {
2181 if (($row === 'hr') && ($countcols)) {
2182 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
2183 } else {
2184 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
2185 if (!($row instanceof html_table_row)) {
2186 $newrow = new html_table_row();
2188 foreach ($row as $cell) {
2189 if (!($cell instanceof html_table_cell)) {
2190 $cell = new html_table_cell($cell);
2192 $newrow->cells[] = $cell;
2194 $row = $newrow;
2197 if (isset($table->rowclasses[$key])) {
2198 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
2201 if ($key == $lastrowkey) {
2202 $row->attributes['class'] .= ' lastrow';
2205 // Explicitly assigned properties should override those defined in the attributes.
2206 $row->attributes['class'] = trim($row->attributes['class']);
2207 $trattributes = array_merge($row->attributes, array(
2208 'id' => $row->id,
2209 'style' => $row->style,
2211 $output .= html_writer::start_tag('tr', $trattributes) . "\n";
2212 $keys2 = array_keys($row->cells);
2213 $lastkey = end($keys2);
2215 $gotlastkey = false; //flag for sanity checking
2216 foreach ($row->cells as $key => $cell) {
2217 if ($gotlastkey) {
2218 //This should never happen. Why do we have a cell after the last cell?
2219 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
2222 if (!($cell instanceof html_table_cell)) {
2223 $mycell = new html_table_cell();
2224 $mycell->text = $cell;
2225 $cell = $mycell;
2228 if (($cell->header === true) && empty($cell->scope)) {
2229 $cell->scope = 'row';
2232 if (isset($table->colclasses[$key])) {
2233 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
2236 $cell->attributes['class'] .= ' cell c' . $key;
2237 if ($key == $lastkey) {
2238 $cell->attributes['class'] .= ' lastcol';
2239 $gotlastkey = true;
2241 $tdstyle = '';
2242 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
2243 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
2244 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
2245 $cell->attributes['class'] = trim($cell->attributes['class']);
2246 $tdattributes = array_merge($cell->attributes, array(
2247 'style' => $tdstyle . $cell->style,
2248 'colspan' => $cell->colspan,
2249 'rowspan' => $cell->rowspan,
2250 'id' => $cell->id,
2251 'abbr' => $cell->abbr,
2252 'scope' => $cell->scope,
2254 $tagtype = 'td';
2255 if ($cell->header === true) {
2256 $tagtype = 'th';
2258 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
2261 $output .= html_writer::end_tag('tr') . "\n";
2263 $output .= html_writer::end_tag('tbody') . "\n";
2265 $output .= html_writer::end_tag('table') . "\n";
2267 return $output;
2271 * Renders form element label
2273 * By default, the label is suffixed with a label separator defined in the
2274 * current language pack (colon by default in the English lang pack).
2275 * Adding the colon can be explicitly disabled if needed. Label separators
2276 * are put outside the label tag itself so they are not read by
2277 * screenreaders (accessibility).
2279 * Parameter $for explicitly associates the label with a form control. When
2280 * set, the value of this attribute must be the same as the value of
2281 * the id attribute of the form control in the same document. When null,
2282 * the label being defined is associated with the control inside the label
2283 * element.
2285 * @param string $text content of the label tag
2286 * @param string|null $for id of the element this label is associated with, null for no association
2287 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
2288 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
2289 * @return string HTML of the label element
2291 public static function label($text, $for, $colonize = true, array $attributes=array()) {
2292 if (!is_null($for)) {
2293 $attributes = array_merge($attributes, array('for' => $for));
2295 $text = trim($text);
2296 $label = self::tag('label', $text, $attributes);
2298 // TODO MDL-12192 $colonize disabled for now yet
2299 // if (!empty($text) and $colonize) {
2300 // // the $text may end with the colon already, though it is bad string definition style
2301 // $colon = get_string('labelsep', 'langconfig');
2302 // if (!empty($colon)) {
2303 // $trimmed = trim($colon);
2304 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
2305 // //debugging('The label text should not end with colon or other label separator,
2306 // // please fix the string definition.', DEBUG_DEVELOPER);
2307 // } else {
2308 // $label .= $colon;
2309 // }
2310 // }
2311 // }
2313 return $label;
2317 * Combines a class parameter with other attributes. Aids in code reduction
2318 * because the class parameter is very frequently used.
2320 * If the class attribute is specified both in the attributes and in the
2321 * class parameter, the two values are combined with a space between.
2323 * @param string $class Optional CSS class (or classes as space-separated list)
2324 * @param array $attributes Optional other attributes as array
2325 * @return array Attributes (or null if still none)
2327 private static function add_class($class = '', array $attributes = null) {
2328 if ($class !== '') {
2329 $classattribute = array('class' => $class);
2330 if ($attributes) {
2331 if (array_key_exists('class', $attributes)) {
2332 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
2333 } else {
2334 $attributes = $classattribute + $attributes;
2336 } else {
2337 $attributes = $classattribute;
2340 return $attributes;
2344 * Creates a <div> tag. (Shortcut function.)
2346 * @param string $content HTML content of tag
2347 * @param string $class Optional CSS class (or classes as space-separated list)
2348 * @param array $attributes Optional other attributes as array
2349 * @return string HTML code for div
2351 public static function div($content, $class = '', array $attributes = null) {
2352 return self::tag('div', $content, self::add_class($class, $attributes));
2356 * Starts a <div> tag. (Shortcut function.)
2358 * @param string $class Optional CSS class (or classes as space-separated list)
2359 * @param array $attributes Optional other attributes as array
2360 * @return string HTML code for open div tag
2362 public static function start_div($class = '', array $attributes = null) {
2363 return self::start_tag('div', self::add_class($class, $attributes));
2367 * Ends a <div> tag. (Shortcut function.)
2369 * @return string HTML code for close div tag
2371 public static function end_div() {
2372 return self::end_tag('div');
2376 * Creates a <span> tag. (Shortcut function.)
2378 * @param string $content HTML content of tag
2379 * @param string $class Optional CSS class (or classes as space-separated list)
2380 * @param array $attributes Optional other attributes as array
2381 * @return string HTML code for span
2383 public static function span($content, $class = '', array $attributes = null) {
2384 return self::tag('span', $content, self::add_class($class, $attributes));
2388 * Starts a <span> tag. (Shortcut function.)
2390 * @param string $class Optional CSS class (or classes as space-separated list)
2391 * @param array $attributes Optional other attributes as array
2392 * @return string HTML code for open span tag
2394 public static function start_span($class = '', array $attributes = null) {
2395 return self::start_tag('span', self::add_class($class, $attributes));
2399 * Ends a <span> tag. (Shortcut function.)
2401 * @return string HTML code for close span tag
2403 public static function end_span() {
2404 return self::end_tag('span');
2409 * Simple javascript output class
2411 * @copyright 2010 Petr Skoda
2412 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2413 * @since Moodle 2.0
2414 * @package core
2415 * @category output
2417 class js_writer {
2420 * Returns javascript code calling the function
2422 * @param string $function function name, can be complex like Y.Event.purgeElement
2423 * @param array $arguments parameters
2424 * @param int $delay execution delay in seconds
2425 * @return string JS code fragment
2427 public static function function_call($function, array $arguments = null, $delay=0) {
2428 if ($arguments) {
2429 $arguments = array_map('json_encode', convert_to_array($arguments));
2430 $arguments = implode(', ', $arguments);
2431 } else {
2432 $arguments = '';
2434 $js = "$function($arguments);";
2436 if ($delay) {
2437 $delay = $delay * 1000; // in miliseconds
2438 $js = "setTimeout(function() { $js }, $delay);";
2440 return $js . "\n";
2444 * Special function which adds Y as first argument of function call.
2446 * @param string $function The function to call
2447 * @param array $extraarguments Any arguments to pass to it
2448 * @return string Some JS code
2450 public static function function_call_with_Y($function, array $extraarguments = null) {
2451 if ($extraarguments) {
2452 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
2453 $arguments = 'Y, ' . implode(', ', $extraarguments);
2454 } else {
2455 $arguments = 'Y';
2457 return "$function($arguments);\n";
2461 * Returns JavaScript code to initialise a new object
2463 * @param string $var If it is null then no var is assigned the new object.
2464 * @param string $class The class to initialise an object for.
2465 * @param array $arguments An array of args to pass to the init method.
2466 * @param array $requirements Any modules required for this class.
2467 * @param int $delay The delay before initialisation. 0 = no delay.
2468 * @return string Some JS code
2470 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
2471 if (is_array($arguments)) {
2472 $arguments = array_map('json_encode', convert_to_array($arguments));
2473 $arguments = implode(', ', $arguments);
2476 if ($var === null) {
2477 $js = "new $class(Y, $arguments);";
2478 } else if (strpos($var, '.')!==false) {
2479 $js = "$var = new $class(Y, $arguments);";
2480 } else {
2481 $js = "var $var = new $class(Y, $arguments);";
2484 if ($delay) {
2485 $delay = $delay * 1000; // in miliseconds
2486 $js = "setTimeout(function() { $js }, $delay);";
2489 if (count($requirements) > 0) {
2490 $requirements = implode("', '", $requirements);
2491 $js = "Y.use('$requirements', function(Y){ $js });";
2493 return $js."\n";
2497 * Returns code setting value to variable
2499 * @param string $name
2500 * @param mixed $value json serialised value
2501 * @param bool $usevar add var definition, ignored for nested properties
2502 * @return string JS code fragment
2504 public static function set_variable($name, $value, $usevar = true) {
2505 $output = '';
2507 if ($usevar) {
2508 if (strpos($name, '.')) {
2509 $output .= '';
2510 } else {
2511 $output .= 'var ';
2515 $output .= "$name = ".json_encode($value).";";
2517 return $output;
2521 * Writes event handler attaching code
2523 * @param array|string $selector standard YUI selector for elements, may be
2524 * array or string, element id is in the form "#idvalue"
2525 * @param string $event A valid DOM event (click, mousedown, change etc.)
2526 * @param string $function The name of the function to call
2527 * @param array $arguments An optional array of argument parameters to pass to the function
2528 * @return string JS code fragment
2530 public static function event_handler($selector, $event, $function, array $arguments = null) {
2531 $selector = json_encode($selector);
2532 $output = "Y.on('$event', $function, $selector, null";
2533 if (!empty($arguments)) {
2534 $output .= ', ' . json_encode($arguments);
2536 return $output . ");\n";
2541 * Holds all the information required to render a <table> by {@link core_renderer::table()}
2543 * Example of usage:
2544 * $t = new html_table();
2545 * ... // set various properties of the object $t as described below
2546 * echo html_writer::table($t);
2548 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
2549 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2550 * @since Moodle 2.0
2551 * @package core
2552 * @category output
2554 class html_table {
2557 * @var string Value to use for the id attribute of the table
2559 public $id = null;
2562 * @var array Attributes of HTML attributes for the <table> element
2564 public $attributes = array();
2567 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
2568 * For more control over the rendering of the headers, an array of html_table_cell objects
2569 * can be passed instead of an array of strings.
2571 * Example of usage:
2572 * $t->head = array('Student', 'Grade');
2574 public $head;
2577 * @var array An array that can be used to make a heading span multiple columns.
2578 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
2579 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
2581 * Example of usage:
2582 * $t->headspan = array(2,1);
2584 public $headspan;
2587 * @var array An array of column alignments.
2588 * The value is used as CSS 'text-align' property. Therefore, possible
2589 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
2590 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
2592 * Examples of usage:
2593 * $t->align = array(null, 'right');
2594 * or
2595 * $t->align[1] = 'right';
2597 public $align;
2600 * @var array The value is used as CSS 'size' property.
2602 * Examples of usage:
2603 * $t->size = array('50%', '50%');
2604 * or
2605 * $t->size[1] = '120px';
2607 public $size;
2610 * @var array An array of wrapping information.
2611 * The only possible value is 'nowrap' that sets the
2612 * CSS property 'white-space' to the value 'nowrap' in the given column.
2614 * Example of usage:
2615 * $t->wrap = array(null, 'nowrap');
2617 public $wrap;
2620 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2621 * $head specified, the string 'hr' (for horizontal ruler) can be used
2622 * instead of an array of cells data resulting in a divider rendered.
2624 * Example of usage with array of arrays:
2625 * $row1 = array('Harry Potter', '76 %');
2626 * $row2 = array('Hermione Granger', '100 %');
2627 * $t->data = array($row1, $row2);
2629 * Example with array of html_table_row objects: (used for more fine-grained control)
2630 * $cell1 = new html_table_cell();
2631 * $cell1->text = 'Harry Potter';
2632 * $cell1->colspan = 2;
2633 * $row1 = new html_table_row();
2634 * $row1->cells[] = $cell1;
2635 * $cell2 = new html_table_cell();
2636 * $cell2->text = 'Hermione Granger';
2637 * $cell3 = new html_table_cell();
2638 * $cell3->text = '100 %';
2639 * $row2 = new html_table_row();
2640 * $row2->cells = array($cell2, $cell3);
2641 * $t->data = array($row1, $row2);
2643 public $data = [];
2646 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2647 * @var string Width of the table, percentage of the page preferred.
2649 public $width = null;
2652 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2653 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2655 public $tablealign = null;
2658 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2659 * @var int Padding on each cell, in pixels
2661 public $cellpadding = null;
2664 * @var int Spacing between cells, in pixels
2665 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2667 public $cellspacing = null;
2670 * @var array Array of classes to add to particular rows, space-separated string.
2671 * Class 'lastrow' is added automatically for the last row in the table.
2673 * Example of usage:
2674 * $t->rowclasses[9] = 'tenth'
2676 public $rowclasses;
2679 * @var array An array of classes to add to every cell in a particular column,
2680 * space-separated string. Class 'cell' is added automatically by the renderer.
2681 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2682 * respectively. Class 'lastcol' is added automatically for all last cells
2683 * in a row.
2685 * Example of usage:
2686 * $t->colclasses = array(null, 'grade');
2688 public $colclasses;
2691 * @var string Description of the contents for screen readers.
2693 public $summary;
2696 * @var string Caption for the table, typically a title.
2698 * Example of usage:
2699 * $t->caption = "TV Guide";
2701 public $caption;
2704 * @var bool Whether to hide the table's caption from sighted users.
2706 * Example of usage:
2707 * $t->caption = "TV Guide";
2708 * $t->captionhide = true;
2710 public $captionhide = false;
2713 * Constructor
2715 public function __construct() {
2716 $this->attributes['class'] = '';
2721 * Component representing a table row.
2723 * @copyright 2009 Nicolas Connault
2724 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2725 * @since Moodle 2.0
2726 * @package core
2727 * @category output
2729 class html_table_row {
2732 * @var string Value to use for the id attribute of the row.
2734 public $id = null;
2737 * @var array Array of html_table_cell objects
2739 public $cells = array();
2742 * @var string Value to use for the style attribute of the table row
2744 public $style = null;
2747 * @var array Attributes of additional HTML attributes for the <tr> element
2749 public $attributes = array();
2752 * Constructor
2753 * @param array $cells
2755 public function __construct(array $cells=null) {
2756 $this->attributes['class'] = '';
2757 $cells = (array)$cells;
2758 foreach ($cells as $cell) {
2759 if ($cell instanceof html_table_cell) {
2760 $this->cells[] = $cell;
2761 } else {
2762 $this->cells[] = new html_table_cell($cell);
2769 * Component representing a table cell.
2771 * @copyright 2009 Nicolas Connault
2772 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2773 * @since Moodle 2.0
2774 * @package core
2775 * @category output
2777 class html_table_cell {
2780 * @var string Value to use for the id attribute of the cell.
2782 public $id = null;
2785 * @var string The contents of the cell.
2787 public $text;
2790 * @var string Abbreviated version of the contents of the cell.
2792 public $abbr = null;
2795 * @var int Number of columns this cell should span.
2797 public $colspan = null;
2800 * @var int Number of rows this cell should span.
2802 public $rowspan = null;
2805 * @var string Defines a way to associate header cells and data cells in a table.
2807 public $scope = null;
2810 * @var bool Whether or not this cell is a header cell.
2812 public $header = null;
2815 * @var string Value to use for the style attribute of the table cell
2817 public $style = null;
2820 * @var array Attributes of additional HTML attributes for the <td> element
2822 public $attributes = array();
2825 * Constructs a table cell
2827 * @param string $text
2829 public function __construct($text = null) {
2830 $this->text = $text;
2831 $this->attributes['class'] = '';
2836 * Component representing a paging bar.
2838 * @copyright 2009 Nicolas Connault
2839 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2840 * @since Moodle 2.0
2841 * @package core
2842 * @category output
2844 class paging_bar implements renderable, templatable {
2847 * @var int The maximum number of pagelinks to display.
2849 public $maxdisplay = 18;
2852 * @var int The total number of entries to be pages through..
2854 public $totalcount;
2857 * @var int The page you are currently viewing.
2859 public $page;
2862 * @var int The number of entries that should be shown per page.
2864 public $perpage;
2867 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2868 * an equals sign and the page number.
2869 * If this is a moodle_url object then the pagevar param will be replaced by
2870 * the page no, for each page.
2872 public $baseurl;
2875 * @var string This is the variable name that you use for the pagenumber in your
2876 * code (ie. 'tablepage', 'blogpage', etc)
2878 public $pagevar;
2881 * @var string A HTML link representing the "previous" page.
2883 public $previouslink = null;
2886 * @var string A HTML link representing the "next" page.
2888 public $nextlink = null;
2891 * @var string A HTML link representing the first page.
2893 public $firstlink = null;
2896 * @var string A HTML link representing the last page.
2898 public $lastlink = null;
2901 * @var array An array of strings. One of them is just a string: the current page
2903 public $pagelinks = array();
2906 * Constructor paging_bar with only the required params.
2908 * @param int $totalcount The total number of entries available to be paged through
2909 * @param int $page The page you are currently viewing
2910 * @param int $perpage The number of entries that should be shown per page
2911 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2912 * @param string $pagevar name of page parameter that holds the page number
2914 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2915 $this->totalcount = $totalcount;
2916 $this->page = $page;
2917 $this->perpage = $perpage;
2918 $this->baseurl = $baseurl;
2919 $this->pagevar = $pagevar;
2923 * Prepares the paging bar for output.
2925 * This method validates the arguments set up for the paging bar and then
2926 * produces fragments of HTML to assist display later on.
2928 * @param renderer_base $output
2929 * @param moodle_page $page
2930 * @param string $target
2931 * @throws coding_exception
2933 public function prepare(renderer_base $output, moodle_page $page, $target) {
2934 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2935 throw new coding_exception('paging_bar requires a totalcount value.');
2937 if (!isset($this->page) || is_null($this->page)) {
2938 throw new coding_exception('paging_bar requires a page value.');
2940 if (empty($this->perpage)) {
2941 throw new coding_exception('paging_bar requires a perpage value.');
2943 if (empty($this->baseurl)) {
2944 throw new coding_exception('paging_bar requires a baseurl value.');
2947 if ($this->totalcount > $this->perpage) {
2948 $pagenum = $this->page - 1;
2950 if ($this->page > 0) {
2951 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2954 if ($this->perpage > 0) {
2955 $lastpage = ceil($this->totalcount / $this->perpage);
2956 } else {
2957 $lastpage = 1;
2960 if ($this->page > round(($this->maxdisplay/3)*2)) {
2961 $currpage = $this->page - round($this->maxdisplay/3);
2963 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2964 } else {
2965 $currpage = 0;
2968 $displaycount = $displaypage = 0;
2970 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2971 $displaypage = $currpage + 1;
2973 if ($this->page == $currpage) {
2974 $this->pagelinks[] = html_writer::span($displaypage, 'current-page');
2975 } else {
2976 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2977 $this->pagelinks[] = $pagelink;
2980 $displaycount++;
2981 $currpage++;
2984 if ($currpage < $lastpage) {
2985 $lastpageactual = $lastpage - 1;
2986 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2989 $pagenum = $this->page + 1;
2991 if ($pagenum != $lastpage) {
2992 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2998 * Export for template.
3000 * @param renderer_base $output The renderer.
3001 * @return stdClass
3003 public function export_for_template(renderer_base $output) {
3004 $data = new stdClass();
3005 $data->previous = null;
3006 $data->next = null;
3007 $data->first = null;
3008 $data->last = null;
3009 $data->label = get_string('page');
3010 $data->pages = [];
3011 $data->haspages = $this->totalcount > $this->perpage;
3013 if (!$data->haspages) {
3014 return $data;
3017 if ($this->page > 0) {
3018 $data->previous = [
3019 'page' => $this->page - 1,
3020 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page - 1]))->out(false)
3024 $currpage = 0;
3025 if ($this->page > round(($this->maxdisplay / 3) * 2)) {
3026 $currpage = $this->page - round($this->maxdisplay / 3);
3027 $data->first = [
3028 'page' => 1,
3029 'url' => (new moodle_url($this->baseurl, [$this->pagevar => 0]))->out(false)
3033 $lastpage = 1;
3034 if ($this->perpage > 0) {
3035 $lastpage = ceil($this->totalcount / $this->perpage);
3038 $displaycount = 0;
3039 $displaypage = 0;
3040 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3041 $displaypage = $currpage + 1;
3043 $iscurrent = $this->page == $currpage;
3044 $link = new moodle_url($this->baseurl, [$this->pagevar => $currpage]);
3046 $data->pages[] = [
3047 'page' => $displaypage,
3048 'active' => $iscurrent,
3049 'url' => $iscurrent ? null : $link->out(false)
3052 $displaycount++;
3053 $currpage++;
3056 if ($currpage < $lastpage) {
3057 $data->last = [
3058 'page' => $lastpage,
3059 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $lastpage - 1]))->out(false)
3063 if ($this->page + 1 != $lastpage) {
3064 $data->next = [
3065 'page' => $this->page + 1,
3066 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page + 1]))->out(false)
3070 return $data;
3075 * Component representing initials bar.
3077 * @copyright 2017 Ilya Tregubov
3078 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3079 * @since Moodle 3.3
3080 * @package core
3081 * @category output
3083 class initials_bar implements renderable, templatable {
3086 * @var string Currently selected letter.
3088 public $current;
3091 * @var string Class name to add to this initial bar.
3093 public $class;
3096 * @var string The name to put in front of this initial bar.
3098 public $title;
3101 * @var string URL parameter name for this initial.
3103 public $urlvar;
3106 * @var string URL object.
3108 public $url;
3111 * @var array An array of letters in the alphabet.
3113 public $alpha;
3116 * Constructor initials_bar with only the required params.
3118 * @param string $current the currently selected letter.
3119 * @param string $class class name to add to this initial bar.
3120 * @param string $title the name to put in front of this initial bar.
3121 * @param string $urlvar URL parameter name for this initial.
3122 * @param string $url URL object.
3123 * @param array $alpha of letters in the alphabet.
3125 public function __construct($current, $class, $title, $urlvar, $url, $alpha = null) {
3126 $this->current = $current;
3127 $this->class = $class;
3128 $this->title = $title;
3129 $this->urlvar = $urlvar;
3130 $this->url = $url;
3131 $this->alpha = $alpha;
3135 * Export for template.
3137 * @param renderer_base $output The renderer.
3138 * @return stdClass
3140 public function export_for_template(renderer_base $output) {
3141 $data = new stdClass();
3143 if ($this->alpha == null) {
3144 $this->alpha = explode(',', get_string('alphabet', 'langconfig'));
3147 if ($this->current == 'all') {
3148 $this->current = '';
3151 // We want to find a letter grouping size which suits the language so
3152 // find the largest group size which is less than 15 chars.
3153 // The choice of 15 chars is the largest number of chars that reasonably
3154 // fits on the smallest supported screen size. By always using a max number
3155 // of groups which is a factor of 2, we always get nice wrapping, and the
3156 // last row is always the shortest.
3157 $groupsize = count($this->alpha);
3158 $groups = 1;
3159 while ($groupsize > 15) {
3160 $groups *= 2;
3161 $groupsize = ceil(count($this->alpha) / $groups);
3164 $groupsizelimit = 0;
3165 $groupnumber = 0;
3166 foreach ($this->alpha as $letter) {
3167 if ($groupsizelimit++ > 0 && $groupsizelimit % $groupsize == 1) {
3168 $groupnumber++;
3170 $groupletter = new stdClass();
3171 $groupletter->name = $letter;
3172 $groupletter->url = $this->url->out(false, array($this->urlvar => $letter));
3173 if ($letter == $this->current) {
3174 $groupletter->selected = $this->current;
3176 $data->group[$groupnumber]->letter[] = $groupletter;
3179 $data->class = $this->class;
3180 $data->title = $this->title;
3181 $data->url = $this->url->out(false, array($this->urlvar => ''));
3182 $data->current = $this->current;
3183 $data->all = get_string('all');
3185 return $data;
3190 * This class represents how a block appears on a page.
3192 * During output, each block instance is asked to return a block_contents object,
3193 * those are then passed to the $OUTPUT->block function for display.
3195 * contents should probably be generated using a moodle_block_..._renderer.
3197 * Other block-like things that need to appear on the page, for example the
3198 * add new block UI, are also represented as block_contents objects.
3200 * @copyright 2009 Tim Hunt
3201 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3202 * @since Moodle 2.0
3203 * @package core
3204 * @category output
3206 class block_contents {
3208 /** Used when the block cannot be collapsed **/
3209 const NOT_HIDEABLE = 0;
3211 /** Used when the block can be collapsed but currently is not **/
3212 const VISIBLE = 1;
3214 /** Used when the block has been collapsed **/
3215 const HIDDEN = 2;
3218 * @var int Used to set $skipid.
3220 protected static $idcounter = 1;
3223 * @var int All the blocks (or things that look like blocks) printed on
3224 * a page are given a unique number that can be used to construct id="" attributes.
3225 * This is set automatically be the {@link prepare()} method.
3226 * Do not try to set it manually.
3228 public $skipid;
3231 * @var int If this is the contents of a real block, this should be set
3232 * to the block_instance.id. Otherwise this should be set to 0.
3234 public $blockinstanceid = 0;
3237 * @var int If this is a real block instance, and there is a corresponding
3238 * block_position.id for the block on this page, this should be set to that id.
3239 * Otherwise it should be 0.
3241 public $blockpositionid = 0;
3244 * @var array An array of attribute => value pairs that are put on the outer div of this
3245 * block. {@link $id} and {@link $classes} attributes should be set separately.
3247 public $attributes;
3250 * @var string The title of this block. If this came from user input, it should already
3251 * have had format_string() processing done on it. This will be output inside
3252 * <h2> tags. Please do not cause invalid XHTML.
3254 public $title = '';
3257 * @var string The label to use when the block does not, or will not have a visible title.
3258 * You should never set this as well as title... it will just be ignored.
3260 public $arialabel = '';
3263 * @var string HTML for the content
3265 public $content = '';
3268 * @var array An alternative to $content, it you want a list of things with optional icons.
3270 public $footer = '';
3273 * @var string Any small print that should appear under the block to explain
3274 * to the teacher about the block, for example 'This is a sticky block that was
3275 * added in the system context.'
3277 public $annotation = '';
3280 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
3281 * the user can toggle whether this block is visible.
3283 public $collapsible = self::NOT_HIDEABLE;
3286 * Set this to true if the block is dockable.
3287 * @var bool
3289 public $dockable = false;
3292 * @var array A (possibly empty) array of editing controls. Each element of
3293 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
3294 * $icon is the icon name. Fed to $OUTPUT->image_url.
3296 public $controls = array();
3300 * Create new instance of block content
3301 * @param array $attributes
3303 public function __construct(array $attributes = null) {
3304 $this->skipid = self::$idcounter;
3305 self::$idcounter += 1;
3307 if ($attributes) {
3308 // standard block
3309 $this->attributes = $attributes;
3310 } else {
3311 // simple "fake" blocks used in some modules and "Add new block" block
3312 $this->attributes = array('class'=>'block');
3317 * Add html class to block
3319 * @param string $class
3321 public function add_class($class) {
3322 $this->attributes['class'] .= ' '.$class;
3328 * This class represents a target for where a block can go when it is being moved.
3330 * This needs to be rendered as a form with the given hidden from fields, and
3331 * clicking anywhere in the form should submit it. The form action should be
3332 * $PAGE->url.
3334 * @copyright 2009 Tim Hunt
3335 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3336 * @since Moodle 2.0
3337 * @package core
3338 * @category output
3340 class block_move_target {
3343 * @var moodle_url Move url
3345 public $url;
3348 * Constructor
3349 * @param moodle_url $url
3351 public function __construct(moodle_url $url) {
3352 $this->url = $url;
3357 * Custom menu item
3359 * This class is used to represent one item within a custom menu that may or may
3360 * not have children.
3362 * @copyright 2010 Sam Hemelryk
3363 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3364 * @since Moodle 2.0
3365 * @package core
3366 * @category output
3368 class custom_menu_item implements renderable, templatable {
3371 * @var string The text to show for the item
3373 protected $text;
3376 * @var moodle_url The link to give the icon if it has no children
3378 protected $url;
3381 * @var string A title to apply to the item. By default the text
3383 protected $title;
3386 * @var int A sort order for the item, not necessary if you order things in
3387 * the CFG var.
3389 protected $sort;
3392 * @var custom_menu_item A reference to the parent for this item or NULL if
3393 * it is a top level item
3395 protected $parent;
3398 * @var array A array in which to store children this item has.
3400 protected $children = array();
3403 * @var int A reference to the sort var of the last child that was added
3405 protected $lastsort = 0;
3408 * Constructs the new custom menu item
3410 * @param string $text
3411 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
3412 * @param string $title A title to apply to this item [Optional]
3413 * @param int $sort A sort or to use if we need to sort differently [Optional]
3414 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
3415 * belongs to, only if the child has a parent. [Optional]
3417 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
3418 $this->text = $text;
3419 $this->url = $url;
3420 $this->title = $title;
3421 $this->sort = (int)$sort;
3422 $this->parent = $parent;
3426 * Adds a custom menu item as a child of this node given its properties.
3428 * @param string $text
3429 * @param moodle_url $url
3430 * @param string $title
3431 * @param int $sort
3432 * @return custom_menu_item
3434 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
3435 $key = count($this->children);
3436 if (empty($sort)) {
3437 $sort = $this->lastsort + 1;
3439 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
3440 $this->lastsort = (int)$sort;
3441 return $this->children[$key];
3445 * Removes a custom menu item that is a child or descendant to the current menu.
3447 * Returns true if child was found and removed.
3449 * @param custom_menu_item $menuitem
3450 * @return bool
3452 public function remove_child(custom_menu_item $menuitem) {
3453 $removed = false;
3454 if (($key = array_search($menuitem, $this->children)) !== false) {
3455 unset($this->children[$key]);
3456 $this->children = array_values($this->children);
3457 $removed = true;
3458 } else {
3459 foreach ($this->children as $child) {
3460 if ($removed = $child->remove_child($menuitem)) {
3461 break;
3465 return $removed;
3469 * Returns the text for this item
3470 * @return string
3472 public function get_text() {
3473 return $this->text;
3477 * Returns the url for this item
3478 * @return moodle_url
3480 public function get_url() {
3481 return $this->url;
3485 * Returns the title for this item
3486 * @return string
3488 public function get_title() {
3489 return $this->title;
3493 * Sorts and returns the children for this item
3494 * @return array
3496 public function get_children() {
3497 $this->sort();
3498 return $this->children;
3502 * Gets the sort order for this child
3503 * @return int
3505 public function get_sort_order() {
3506 return $this->sort;
3510 * Gets the parent this child belong to
3511 * @return custom_menu_item
3513 public function get_parent() {
3514 return $this->parent;
3518 * Sorts the children this item has
3520 public function sort() {
3521 usort($this->children, array('custom_menu','sort_custom_menu_items'));
3525 * Returns true if this item has any children
3526 * @return bool
3528 public function has_children() {
3529 return (count($this->children) > 0);
3533 * Sets the text for the node
3534 * @param string $text
3536 public function set_text($text) {
3537 $this->text = (string)$text;
3541 * Sets the title for the node
3542 * @param string $title
3544 public function set_title($title) {
3545 $this->title = (string)$title;
3549 * Sets the url for the node
3550 * @param moodle_url $url
3552 public function set_url(moodle_url $url) {
3553 $this->url = $url;
3557 * Export this data so it can be used as the context for a mustache template.
3559 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
3560 * @return array
3562 public function export_for_template(renderer_base $output) {
3563 global $CFG;
3565 require_once($CFG->libdir . '/externallib.php');
3567 $syscontext = context_system::instance();
3569 $context = new stdClass();
3570 $context->text = external_format_string($this->text, $syscontext->id);
3571 $context->url = $this->url ? $this->url->out() : null;
3572 $context->title = external_format_string($this->title, $syscontext->id);
3573 $context->sort = $this->sort;
3574 $context->children = array();
3575 if (preg_match("/^#+$/", $this->text)) {
3576 $context->divider = true;
3578 $context->haschildren = !empty($this->children) && (count($this->children) > 0);
3579 foreach ($this->children as $child) {
3580 $child = $child->export_for_template($output);
3581 array_push($context->children, $child);
3584 return $context;
3589 * Custom menu class
3591 * This class is used to operate a custom menu that can be rendered for the page.
3592 * The custom menu is built using $CFG->custommenuitems and is a structured collection
3593 * of custom_menu_item nodes that can be rendered by the core renderer.
3595 * To configure the custom menu:
3596 * Settings: Administration > Appearance > Themes > Theme settings
3598 * @copyright 2010 Sam Hemelryk
3599 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3600 * @since Moodle 2.0
3601 * @package core
3602 * @category output
3604 class custom_menu extends custom_menu_item {
3607 * @var string The language we should render for, null disables multilang support.
3609 protected $currentlanguage = null;
3612 * Creates the custom menu
3614 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
3615 * @param string $currentlanguage the current language code, null disables multilang support
3617 public function __construct($definition = '', $currentlanguage = null) {
3618 $this->currentlanguage = $currentlanguage;
3619 parent::__construct('root'); // create virtual root element of the menu
3620 if (!empty($definition)) {
3621 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
3626 * Overrides the children of this custom menu. Useful when getting children
3627 * from $CFG->custommenuitems
3629 * @param array $children
3631 public function override_children(array $children) {
3632 $this->children = array();
3633 foreach ($children as $child) {
3634 if ($child instanceof custom_menu_item) {
3635 $this->children[] = $child;
3641 * Converts a string into a structured array of custom_menu_items which can
3642 * then be added to a custom menu.
3644 * Structure:
3645 * text|url|title|langs
3646 * The number of hyphens at the start determines the depth of the item. The
3647 * languages are optional, comma separated list of languages the line is for.
3649 * Example structure:
3650 * First level first item|http://www.moodle.com/
3651 * -Second level first item|http://www.moodle.com/partners/
3652 * -Second level second item|http://www.moodle.com/hq/
3653 * --Third level first item|http://www.moodle.com/jobs/
3654 * -Second level third item|http://www.moodle.com/development/
3655 * First level second item|http://www.moodle.com/feedback/
3656 * First level third item
3657 * English only|http://moodle.com|English only item|en
3658 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
3661 * @static
3662 * @param string $text the menu items definition
3663 * @param string $language the language code, null disables multilang support
3664 * @return array
3666 public static function convert_text_to_menu_nodes($text, $language = null) {
3667 $root = new custom_menu();
3668 $lastitem = $root;
3669 $lastdepth = 0;
3670 $hiddenitems = array();
3671 $lines = explode("\n", $text);
3672 foreach ($lines as $linenumber => $line) {
3673 $line = trim($line);
3674 if (strlen($line) == 0) {
3675 continue;
3677 // Parse item settings.
3678 $itemtext = null;
3679 $itemurl = null;
3680 $itemtitle = null;
3681 $itemvisible = true;
3682 $settings = explode('|', $line);
3683 foreach ($settings as $i => $setting) {
3684 $setting = trim($setting);
3685 if (!empty($setting)) {
3686 switch ($i) {
3687 case 0:
3688 $itemtext = ltrim($setting, '-');
3689 $itemtitle = $itemtext;
3690 break;
3691 case 1:
3692 try {
3693 $itemurl = new moodle_url($setting);
3694 } catch (moodle_exception $exception) {
3695 // We're not actually worried about this, we don't want to mess up the display
3696 // just for a wrongly entered URL.
3697 $itemurl = null;
3699 break;
3700 case 2:
3701 $itemtitle = $setting;
3702 break;
3703 case 3:
3704 if (!empty($language)) {
3705 $itemlanguages = array_map('trim', explode(',', $setting));
3706 $itemvisible &= in_array($language, $itemlanguages);
3708 break;
3712 // Get depth of new item.
3713 preg_match('/^(\-*)/', $line, $match);
3714 $itemdepth = strlen($match[1]) + 1;
3715 // Find parent item for new item.
3716 while (($lastdepth - $itemdepth) >= 0) {
3717 $lastitem = $lastitem->get_parent();
3718 $lastdepth--;
3720 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1);
3721 $lastdepth++;
3722 if (!$itemvisible) {
3723 $hiddenitems[] = $lastitem;
3726 foreach ($hiddenitems as $item) {
3727 $item->parent->remove_child($item);
3729 return $root->get_children();
3733 * Sorts two custom menu items
3735 * This function is designed to be used with the usort method
3736 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
3738 * @static
3739 * @param custom_menu_item $itema
3740 * @param custom_menu_item $itemb
3741 * @return int
3743 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
3744 $itema = $itema->get_sort_order();
3745 $itemb = $itemb->get_sort_order();
3746 if ($itema == $itemb) {
3747 return 0;
3749 return ($itema > $itemb) ? +1 : -1;
3754 * Stores one tab
3756 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3757 * @package core
3759 class tabobject implements renderable, templatable {
3760 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
3761 var $id;
3762 /** @var moodle_url|string link */
3763 var $link;
3764 /** @var string text on the tab */
3765 var $text;
3766 /** @var string title under the link, by defaul equals to text */
3767 var $title;
3768 /** @var bool whether to display a link under the tab name when it's selected */
3769 var $linkedwhenselected = false;
3770 /** @var bool whether the tab is inactive */
3771 var $inactive = false;
3772 /** @var bool indicates that this tab's child is selected */
3773 var $activated = false;
3774 /** @var bool indicates that this tab is selected */
3775 var $selected = false;
3776 /** @var array stores children tabobjects */
3777 var $subtree = array();
3778 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
3779 var $level = 1;
3782 * Constructor
3784 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
3785 * @param string|moodle_url $link
3786 * @param string $text text on the tab
3787 * @param string $title title under the link, by defaul equals to text
3788 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
3790 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
3791 $this->id = $id;
3792 $this->link = $link;
3793 $this->text = $text;
3794 $this->title = $title ? $title : $text;
3795 $this->linkedwhenselected = $linkedwhenselected;
3799 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
3801 * @param string $selected the id of the selected tab (whatever row it's on),
3802 * if null marks all tabs as unselected
3803 * @return bool whether this tab is selected or contains selected tab in its subtree
3805 protected function set_selected($selected) {
3806 if ((string)$selected === (string)$this->id) {
3807 $this->selected = true;
3808 // This tab is selected. No need to travel through subtree.
3809 return true;
3811 foreach ($this->subtree as $subitem) {
3812 if ($subitem->set_selected($selected)) {
3813 // This tab has child that is selected. Mark it as activated. No need to check other children.
3814 $this->activated = true;
3815 return true;
3818 return false;
3822 * Travels through tree and finds a tab with specified id
3824 * @param string $id
3825 * @return tabtree|null
3827 public function find($id) {
3828 if ((string)$this->id === (string)$id) {
3829 return $this;
3831 foreach ($this->subtree as $tab) {
3832 if ($obj = $tab->find($id)) {
3833 return $obj;
3836 return null;
3840 * Allows to mark each tab's level in the tree before rendering.
3842 * @param int $level
3844 protected function set_level($level) {
3845 $this->level = $level;
3846 foreach ($this->subtree as $tab) {
3847 $tab->set_level($level + 1);
3852 * Export for template.
3854 * @param renderer_base $output Renderer.
3855 * @return object
3857 public function export_for_template(renderer_base $output) {
3858 if ($this->inactive || ($this->selected && !$this->linkedwhenselected) || $this->activated) {
3859 $link = null;
3860 } else {
3861 $link = $this->link;
3863 $active = $this->activated || $this->selected;
3865 return (object) [
3866 'id' => $this->id,
3867 'link' => is_object($link) ? $link->out(false) : $link,
3868 'text' => $this->text,
3869 'title' => $this->title,
3870 'inactive' => !$active && $this->inactive,
3871 'active' => $active,
3872 'level' => $this->level,
3879 * Renderable for the main page header.
3881 * @package core
3882 * @category output
3883 * @since 2.9
3884 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
3885 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3887 class context_header implements renderable {
3890 * @var string $heading Main heading.
3892 public $heading;
3894 * @var int $headinglevel Main heading 'h' tag level.
3896 public $headinglevel;
3898 * @var string|null $imagedata HTML code for the picture in the page header.
3900 public $imagedata;
3902 * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
3903 * array elements - title => alternate text for the image, or if no image is available the button text.
3904 * url => Link for the button to head to. Should be a moodle_url.
3905 * image => location to the image, or name of the image in /pix/t/{image name}.
3906 * linkattributes => additional attributes for the <a href> element.
3907 * page => page object. Don't include if the image is an external image.
3909 public $additionalbuttons;
3912 * Constructor.
3914 * @param string $heading Main heading data.
3915 * @param int $headinglevel Main heading 'h' tag level.
3916 * @param string|null $imagedata HTML code for the picture in the page header.
3917 * @param string $additionalbuttons Buttons for the header e.g. Messaging button for the user header.
3919 public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null) {
3921 $this->heading = $heading;
3922 $this->headinglevel = $headinglevel;
3923 $this->imagedata = $imagedata;
3924 $this->additionalbuttons = $additionalbuttons;
3925 // If we have buttons then format them.
3926 if (isset($this->additionalbuttons)) {
3927 $this->format_button_images();
3932 * Adds an array element for a formatted image.
3934 protected function format_button_images() {
3936 foreach ($this->additionalbuttons as $buttontype => $button) {
3937 $page = $button['page'];
3938 // If no image is provided then just use the title.
3939 if (!isset($button['image'])) {
3940 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['title'];
3941 } else {
3942 // Check to see if this is an internal Moodle icon.
3943 $internalimage = $page->theme->resolve_image_location('t/' . $button['image'], 'moodle');
3944 if ($internalimage) {
3945 $this->additionalbuttons[$buttontype]['formattedimage'] = 't/' . $button['image'];
3946 } else {
3947 // Treat as an external image.
3948 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['image'];
3952 if (isset($button['linkattributes']['class'])) {
3953 $class = $button['linkattributes']['class'] . ' btn';
3954 } else {
3955 $class = 'btn';
3957 // Add the bootstrap 'btn' class for formatting.
3958 $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
3959 array('class' => $class));
3965 * Stores tabs list
3967 * Example how to print a single line tabs:
3968 * $rows = array(
3969 * new tabobject(...),
3970 * new tabobject(...)
3971 * );
3972 * echo $OUTPUT->tabtree($rows, $selectedid);
3974 * Multiple row tabs may not look good on some devices but if you want to use them
3975 * you can specify ->subtree for the active tabobject.
3977 * @copyright 2013 Marina Glancy
3978 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3979 * @since Moodle 2.5
3980 * @package core
3981 * @category output
3983 class tabtree extends tabobject {
3985 * Constuctor
3987 * It is highly recommended to call constructor when list of tabs is already
3988 * populated, this way you ensure that selected and inactive tabs are located
3989 * and attribute level is set correctly.
3991 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3992 * @param string|null $selected which tab to mark as selected, all parent tabs will
3993 * automatically be marked as activated
3994 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3995 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3997 public function __construct($tabs, $selected = null, $inactive = null) {
3998 $this->subtree = $tabs;
3999 if ($selected !== null) {
4000 $this->set_selected($selected);
4002 if ($inactive !== null) {
4003 if (is_array($inactive)) {
4004 foreach ($inactive as $id) {
4005 if ($tab = $this->find($id)) {
4006 $tab->inactive = true;
4009 } else if ($tab = $this->find($inactive)) {
4010 $tab->inactive = true;
4013 $this->set_level(0);
4017 * Export for template.
4019 * @param renderer_base $output Renderer.
4020 * @return object
4022 public function export_for_template(renderer_base $output) {
4023 $tabs = [];
4024 $secondrow = false;
4026 foreach ($this->subtree as $tab) {
4027 $tabs[] = $tab->export_for_template($output);
4028 if (!empty($tab->subtree) && ($tab->level == 0 || $tab->selected || $tab->activated)) {
4029 $secondrow = new tabtree($tab->subtree);
4033 return (object) [
4034 'tabs' => $tabs,
4035 'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false
4041 * An action menu.
4043 * This action menu component takes a series of primary and secondary actions.
4044 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
4045 * down menu.
4047 * @package core
4048 * @category output
4049 * @copyright 2013 Sam Hemelryk
4050 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4052 class action_menu implements renderable, templatable {
4055 * Top right alignment.
4057 const TL = 1;
4060 * Top right alignment.
4062 const TR = 2;
4065 * Top right alignment.
4067 const BL = 3;
4070 * Top right alignment.
4072 const BR = 4;
4075 * The instance number. This is unique to this instance of the action menu.
4076 * @var int
4078 protected $instance = 0;
4081 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
4082 * @var array
4084 protected $primaryactions = array();
4087 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
4088 * @var array
4090 protected $secondaryactions = array();
4093 * An array of attributes added to the container of the action menu.
4094 * Initialised with defaults during construction.
4095 * @var array
4097 public $attributes = array();
4099 * An array of attributes added to the container of the primary actions.
4100 * Initialised with defaults during construction.
4101 * @var array
4103 public $attributesprimary = array();
4105 * An array of attributes added to the container of the secondary actions.
4106 * Initialised with defaults during construction.
4107 * @var array
4109 public $attributessecondary = array();
4112 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
4113 * @var array
4115 public $actiontext = null;
4118 * An icon to use for the toggling the secondary menu (dropdown).
4119 * @var actionicon
4121 public $actionicon;
4124 * Any text to use for the toggling the secondary menu (dropdown).
4125 * @var menutrigger
4127 public $menutrigger = '';
4130 * Place the action menu before all other actions.
4131 * @var prioritise
4133 public $prioritise = false;
4136 * Constructs the action menu with the given items.
4138 * @param array $actions An array of actions.
4140 public function __construct(array $actions = array()) {
4141 static $initialised = 0;
4142 $this->instance = $initialised;
4143 $initialised++;
4145 $this->attributes = array(
4146 'id' => 'action-menu-'.$this->instance,
4147 'class' => 'moodle-actionmenu',
4148 'data-enhance' => 'moodle-core-actionmenu'
4150 $this->attributesprimary = array(
4151 'id' => 'action-menu-'.$this->instance.'-menubar',
4152 'class' => 'menubar',
4153 'role' => 'menubar'
4155 $this->attributessecondary = array(
4156 'id' => 'action-menu-'.$this->instance.'-menu',
4157 'class' => 'menu',
4158 'data-rel' => 'menu-content',
4159 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
4160 'role' => 'menu'
4162 $this->set_alignment(self::TR, self::BR);
4163 foreach ($actions as $action) {
4164 $this->add($action);
4168 public function set_menu_trigger($trigger) {
4169 $this->menutrigger = $trigger;
4173 * Return true if there is at least one visible link in the menu.
4175 * @return bool
4177 public function is_empty() {
4178 return !count($this->primaryactions) && !count($this->secondaryactions);
4182 * Initialises JS required fore the action menu.
4183 * The JS is only required once as it manages all action menu's on the page.
4185 * @param moodle_page $page
4187 public function initialise_js(moodle_page $page) {
4188 static $initialised = false;
4189 if (!$initialised) {
4190 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
4191 $initialised = true;
4196 * Adds an action to this action menu.
4198 * @param action_menu_link|pix_icon|string $action
4200 public function add($action) {
4201 if ($action instanceof action_link) {
4202 if ($action->primary) {
4203 $this->add_primary_action($action);
4204 } else {
4205 $this->add_secondary_action($action);
4207 } else if ($action instanceof pix_icon) {
4208 $this->add_primary_action($action);
4209 } else {
4210 $this->add_secondary_action($action);
4215 * Adds a primary action to the action menu.
4217 * @param action_menu_link|action_link|pix_icon|string $action
4219 public function add_primary_action($action) {
4220 if ($action instanceof action_link || $action instanceof pix_icon) {
4221 $action->attributes['role'] = 'menuitem';
4222 if ($action instanceof action_menu_link) {
4223 $action->actionmenu = $this;
4226 $this->primaryactions[] = $action;
4230 * Adds a secondary action to the action menu.
4232 * @param action_link|pix_icon|string $action
4234 public function add_secondary_action($action) {
4235 if ($action instanceof action_link || $action instanceof pix_icon) {
4236 $action->attributes['role'] = 'menuitem';
4237 if ($action instanceof action_menu_link) {
4238 $action->actionmenu = $this;
4241 $this->secondaryactions[] = $action;
4245 * Returns the primary actions ready to be rendered.
4247 * @param core_renderer $output The renderer to use for getting icons.
4248 * @return array
4250 public function get_primary_actions(core_renderer $output = null) {
4251 global $OUTPUT;
4252 if ($output === null) {
4253 $output = $OUTPUT;
4255 $pixicon = $this->actionicon;
4256 $linkclasses = array('toggle-display');
4258 $title = '';
4259 if (!empty($this->menutrigger)) {
4260 $pixicon = '<b class="caret"></b>';
4261 $linkclasses[] = 'textmenu';
4262 } else {
4263 $title = new lang_string('actions', 'moodle');
4264 $this->actionicon = new pix_icon(
4265 't/edit_menu',
4267 'moodle',
4268 array('class' => 'iconsmall actionmenu', 'title' => '')
4270 $pixicon = $this->actionicon;
4272 if ($pixicon instanceof renderable) {
4273 $pixicon = $output->render($pixicon);
4274 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
4275 $title = $pixicon->attributes['alt'];
4278 $string = '';
4279 if ($this->actiontext) {
4280 $string = $this->actiontext;
4282 $actions = $this->primaryactions;
4283 $attributes = array(
4284 'class' => implode(' ', $linkclasses),
4285 'title' => $title,
4286 'id' => 'action-menu-toggle-'.$this->instance,
4287 'role' => 'menuitem'
4289 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
4290 if ($this->prioritise) {
4291 array_unshift($actions, $link);
4292 } else {
4293 $actions[] = $link;
4295 return $actions;
4299 * Returns the secondary actions ready to be rendered.
4300 * @return array
4302 public function get_secondary_actions() {
4303 return $this->secondaryactions;
4307 * Sets the selector that should be used to find the owning node of this menu.
4308 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
4310 public function set_owner_selector($selector) {
4311 $this->attributes['data-owner'] = $selector;
4315 * Sets the alignment of the dialogue in relation to button used to toggle it.
4317 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4318 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4320 public function set_alignment($dialogue, $button) {
4321 if (isset($this->attributessecondary['data-align'])) {
4322 // We've already got one set, lets remove the old class so as to avoid troubles.
4323 $class = $this->attributessecondary['class'];
4324 $search = 'align-'.$this->attributessecondary['data-align'];
4325 $this->attributessecondary['class'] = str_replace($search, '', $class);
4327 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
4328 $this->attributessecondary['data-align'] = $align;
4329 $this->attributessecondary['class'] .= ' align-'.$align;
4333 * Returns a string to describe the alignment.
4335 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4336 * @return string
4338 protected function get_align_string($align) {
4339 switch ($align) {
4340 case self::TL :
4341 return 'tl';
4342 case self::TR :
4343 return 'tr';
4344 case self::BL :
4345 return 'bl';
4346 case self::BR :
4347 return 'br';
4348 default :
4349 return 'tl';
4354 * Sets a constraint for the dialogue.
4356 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
4357 * element the constraint identifies.
4359 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
4361 public function set_constraint($ancestorselector) {
4362 $this->attributessecondary['data-constraint'] = $ancestorselector;
4366 * If you call this method the action menu will be displayed but will not be enhanced.
4368 * By not displaying the menu enhanced all items will be displayed in a single row.
4370 * @deprecated since Moodle 3.2
4372 public function do_not_enhance() {
4373 debugging('The method action_menu::do_not_enhance() is deprecated, use a list of action_icon instead.', DEBUG_DEVELOPER);
4377 * Returns true if this action menu will be enhanced.
4379 * @return bool
4381 public function will_be_enhanced() {
4382 return isset($this->attributes['data-enhance']);
4386 * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
4388 * This property can be useful when the action menu is displayed within a parent element that is either floated
4389 * or relatively positioned.
4390 * In that situation the width of the menu is determined by the width of the parent element which may not be large
4391 * enough for the menu items without them wrapping.
4392 * This disables the wrapping so that the menu takes on the width of the longest item.
4394 * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
4396 public function set_nowrap_on_items($value = true) {
4397 $class = 'nowrap-items';
4398 if (!empty($this->attributes['class'])) {
4399 $pos = strpos($this->attributes['class'], $class);
4400 if ($value === true && $pos === false) {
4401 // The value is true and the class has not been set yet. Add it.
4402 $this->attributes['class'] .= ' '.$class;
4403 } else if ($value === false && $pos !== false) {
4404 // The value is false and the class has been set. Remove it.
4405 $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class));
4407 } else if ($value) {
4408 // The value is true and the class has not been set yet. Add it.
4409 $this->attributes['class'] = $class;
4414 * Export for template.
4416 * @param renderer_base $output The renderer.
4417 * @return stdClass
4419 public function export_for_template(renderer_base $output) {
4420 $data = new stdClass();
4421 $attributes = $this->attributes;
4422 $attributesprimary = $this->attributesprimary;
4423 $attributessecondary = $this->attributessecondary;
4425 $data->instance = $this->instance;
4427 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
4428 unset($attributes['class']);
4430 $data->attributes = array_map(function($key, $value) {
4431 return [ 'name' => $key, 'value' => $value ];
4432 }, array_keys($attributes), $attributes);
4434 $primary = new stdClass();
4435 $primary->title = '';
4436 $primary->prioritise = $this->prioritise;
4438 $primary->classes = isset($attributesprimary['class']) ? $attributesprimary['class'] : '';
4439 unset($attributesprimary['class']);
4440 $primary->attributes = array_map(function($key, $value) {
4441 return [ 'name' => $key, 'value' => $value ];
4442 }, array_keys($attributesprimary), $attributesprimary);
4444 $actionicon = $this->actionicon;
4445 if (!empty($this->menutrigger)) {
4446 $primary->menutrigger = $this->menutrigger;
4447 } else {
4448 $primary->title = get_string('actions');
4449 $actionicon = new pix_icon('t/edit_menu', '', 'moodle', ['class' => 'iconsmall actionmenu', 'title' => '']);
4452 if ($actionicon instanceof pix_icon) {
4453 $primary->icon = $actionicon->export_for_pix();
4454 $primary->title = !empty($actionicon->attributes['alt']) ? $this->actionicon->attributes['alt'] : '';
4455 } else {
4456 $primary->iconraw = $actionicon ? $output->render($actionicon) : '';
4459 $primary->actiontext = $this->actiontext ? (string) $this->actiontext : '';
4460 $primary->items = array_map(function($item) use ($output) {
4461 $data = (object) [];
4462 if ($item instanceof action_menu_link) {
4463 $data->actionmenulink = $item->export_for_template($output);
4464 } else if ($item instanceof action_menu_filler) {
4465 $data->actionmenufiller = $item->export_for_template($output);
4466 } else if ($item instanceof action_link) {
4467 $data->actionlink = $item->export_for_template($output);
4468 } else if ($item instanceof pix_icon) {
4469 $data->pixicon = $item->export_for_template($output);
4470 } else {
4471 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4473 return $data;
4474 }, $this->primaryactions);
4476 $secondary = new stdClass();
4477 $secondary->classes = isset($attributessecondary['class']) ? $attributessecondary['class'] : '';
4478 unset($attributessecondary['class']);
4479 $secondary->attributes = array_map(function($key, $value) {
4480 return [ 'name' => $key, 'value' => $value ];
4481 }, array_keys($attributessecondary), $attributessecondary);
4482 $secondary->items = array_map(function($item) use ($output) {
4483 $data = (object) [];
4484 if ($item instanceof action_menu_link) {
4485 $data->actionmenulink = $item->export_for_template($output);
4486 } else if ($item instanceof action_menu_filler) {
4487 $data->actionmenufiller = $item->export_for_template($output);
4488 } else if ($item instanceof action_link) {
4489 $data->actionlink = $item->export_for_template($output);
4490 } else if ($item instanceof pix_icon) {
4491 $data->pixicon = $item->export_for_template($output);
4492 } else {
4493 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4495 return $data;
4496 }, $this->secondaryactions);
4498 $data->primary = $primary;
4499 $data->secondary = $secondary;
4501 return $data;
4507 * An action menu filler
4509 * @package core
4510 * @category output
4511 * @copyright 2013 Andrew Nicols
4512 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4514 class action_menu_filler extends action_link implements renderable {
4517 * True if this is a primary action. False if not.
4518 * @var bool
4520 public $primary = true;
4523 * Constructs the object.
4525 public function __construct() {
4530 * An action menu action
4532 * @package core
4533 * @category output
4534 * @copyright 2013 Sam Hemelryk
4535 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4537 class action_menu_link extends action_link implements renderable {
4540 * True if this is a primary action. False if not.
4541 * @var bool
4543 public $primary = true;
4546 * The action menu this link has been added to.
4547 * @var action_menu
4549 public $actionmenu = null;
4552 * Constructs the object.
4554 * @param moodle_url $url The URL for the action.
4555 * @param pix_icon $icon The icon to represent the action.
4556 * @param string $text The text to represent the action.
4557 * @param bool $primary Whether this is a primary action or not.
4558 * @param array $attributes Any attribtues associated with the action.
4560 public function __construct(moodle_url $url, pix_icon $icon = null, $text, $primary = true, array $attributes = array()) {
4561 parent::__construct($url, $text, null, $attributes, $icon);
4562 $this->primary = (bool)$primary;
4563 $this->add_class('menu-action');
4564 $this->attributes['role'] = 'menuitem';
4568 * Export for template.
4570 * @param renderer_base $output The renderer.
4571 * @return stdClass
4573 public function export_for_template(renderer_base $output) {
4574 static $instance = 1;
4576 $data = parent::export_for_template($output);
4577 $data->instance = $instance++;
4579 // Ignore what the parent did with the attributes, except for ID and class.
4580 $data->attributes = [];
4581 $attributes = $this->attributes;
4582 unset($attributes['id']);
4583 unset($attributes['class']);
4585 // Handle text being a renderable.
4586 if ($this->text instanceof renderable) {
4587 $data->text = $this->render($this->text);
4590 $data->showtext = (!$this->icon || $this->primary === false);
4592 $data->icon = null;
4593 if ($this->icon) {
4594 $icon = $this->icon;
4595 if ($this->primary || !$this->actionmenu->will_be_enhanced()) {
4596 $attributes['title'] = $data->text;
4598 $data->icon = $icon ? $icon->export_for_pix() : null;
4601 $data->disabled = !empty($attributes['disabled']);
4602 unset($attributes['disabled']);
4604 $data->attributes = array_map(function($key, $value) {
4605 return [
4606 'name' => $key,
4607 'value' => $value
4609 }, array_keys($attributes), $attributes);
4611 return $data;
4616 * A primary action menu action
4618 * @package core
4619 * @category output
4620 * @copyright 2013 Sam Hemelryk
4621 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4623 class action_menu_link_primary extends action_menu_link {
4625 * Constructs the object.
4627 * @param moodle_url $url
4628 * @param pix_icon $icon
4629 * @param string $text
4630 * @param array $attributes
4632 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
4633 parent::__construct($url, $icon, $text, true, $attributes);
4638 * A secondary action menu action
4640 * @package core
4641 * @category output
4642 * @copyright 2013 Sam Hemelryk
4643 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4645 class action_menu_link_secondary extends action_menu_link {
4647 * Constructs the object.
4649 * @param moodle_url $url
4650 * @param pix_icon $icon
4651 * @param string $text
4652 * @param array $attributes
4654 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
4655 parent::__construct($url, $icon, $text, false, $attributes);
4660 * Represents a set of preferences groups.
4662 * @package core
4663 * @category output
4664 * @copyright 2015 Frédéric Massart - FMCorz.net
4665 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4667 class preferences_groups implements renderable {
4670 * Array of preferences_group.
4671 * @var array
4673 public $groups;
4676 * Constructor.
4677 * @param array $groups of preferences_group
4679 public function __construct($groups) {
4680 $this->groups = $groups;
4686 * Represents a group of preferences page link.
4688 * @package core
4689 * @category output
4690 * @copyright 2015 Frédéric Massart - FMCorz.net
4691 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4693 class preferences_group implements renderable {
4696 * Title of the group.
4697 * @var string
4699 public $title;
4702 * Array of navigation_node.
4703 * @var array
4705 public $nodes;
4708 * Constructor.
4709 * @param string $title The title.
4710 * @param array $nodes of navigation_node.
4712 public function __construct($title, $nodes) {
4713 $this->title = $title;
4714 $this->nodes = $nodes;
4719 * Progress bar class.
4721 * Manages the display of a progress bar.
4723 * To use this class.
4724 * - construct
4725 * - call create (or use the 3rd param to the constructor)
4726 * - call update or update_full() or update() repeatedly
4728 * @copyright 2008 jamiesensei
4729 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4730 * @package core
4731 * @category output
4733 class progress_bar implements renderable, templatable {
4734 /** @var string html id */
4735 private $html_id;
4736 /** @var int total width */
4737 private $width;
4738 /** @var int last percentage printed */
4739 private $percent = 0;
4740 /** @var int time when last printed */
4741 private $lastupdate = 0;
4742 /** @var int when did we start printing this */
4743 private $time_start = 0;
4746 * Constructor
4748 * Prints JS code if $autostart true.
4750 * @param string $htmlid The container ID.
4751 * @param int $width The suggested width.
4752 * @param bool $autostart Whether to start the progress bar right away.
4754 public function __construct($htmlid = '', $width = 500, $autostart = false) {
4755 if (!defined('NO_OUTPUT_BUFFERING') || !NO_OUTPUT_BUFFERING) {
4756 debugging('progress_bar used without setting NO_OUTPUT_BUFFERING.', DEBUG_DEVELOPER);
4759 if (!empty($htmlid)) {
4760 $this->html_id = $htmlid;
4761 } else {
4762 $this->html_id = 'pbar_'.uniqid();
4765 $this->width = $width;
4767 if ($autostart) {
4768 $this->create();
4773 * Create a new progress bar, this function will output html.
4775 * @return void Echo's output
4777 public function create() {
4778 global $OUTPUT;
4780 $this->time_start = microtime(true);
4781 if (CLI_SCRIPT) {
4782 return; // Temporary solution for cli scripts.
4785 flush();
4786 echo $OUTPUT->render($this);
4787 flush();
4791 * Update the progress bar.
4793 * @param int $percent From 1-100.
4794 * @param string $msg The message.
4795 * @return void Echo's output
4796 * @throws coding_exception
4798 private function _update($percent, $msg) {
4799 if (empty($this->time_start)) {
4800 throw new coding_exception('You must call create() (or use the $autostart ' .
4801 'argument to the constructor) before you try updating the progress bar.');
4804 if (CLI_SCRIPT) {
4805 return; // Temporary solution for cli scripts.
4808 $estimate = $this->estimate($percent);
4810 if ($estimate === null) {
4811 // Always do the first and last updates.
4812 } else if ($estimate == 0) {
4813 // Always do the last updates.
4814 } else if ($this->lastupdate + 20 < time()) {
4815 // We must update otherwise browser would time out.
4816 } else if (round($this->percent, 2) === round($percent, 2)) {
4817 // No significant change, no need to update anything.
4818 return;
4821 $estimatemsg = null;
4822 if (is_numeric($estimate)) {
4823 $estimatemsg = get_string('secondsleft', 'moodle', round($estimate, 2));
4826 $this->percent = round($percent, 2);
4827 $this->lastupdate = microtime(true);
4829 echo html_writer::script(js_writer::function_call('updateProgressBar',
4830 array($this->html_id, $this->percent, $msg, $estimatemsg)));
4831 flush();
4835 * Estimate how much time it is going to take.
4837 * @param int $pt From 1-100.
4838 * @return mixed Null (unknown), or int.
4840 private function estimate($pt) {
4841 if ($this->lastupdate == 0) {
4842 return null;
4844 if ($pt < 0.00001) {
4845 return null; // We do not know yet how long it will take.
4847 if ($pt > 99.99999) {
4848 return 0; // Nearly done, right?
4850 $consumed = microtime(true) - $this->time_start;
4851 if ($consumed < 0.001) {
4852 return null;
4855 return (100 - $pt) * ($consumed / $pt);
4859 * Update progress bar according percent.
4861 * @param int $percent From 1-100.
4862 * @param string $msg The message needed to be shown.
4864 public function update_full($percent, $msg) {
4865 $percent = max(min($percent, 100), 0);
4866 $this->_update($percent, $msg);
4870 * Update progress bar according the number of tasks.
4872 * @param int $cur Current task number.
4873 * @param int $total Total task number.
4874 * @param string $msg The message needed to be shown.
4876 public function update($cur, $total, $msg) {
4877 $percent = ($cur / $total) * 100;
4878 $this->update_full($percent, $msg);
4882 * Restart the progress bar.
4884 public function restart() {
4885 $this->percent = 0;
4886 $this->lastupdate = 0;
4887 $this->time_start = 0;
4891 * Export for template.
4893 * @param renderer_base $output The renderer.
4894 * @return array
4896 public function export_for_template(renderer_base $output) {
4897 return [
4898 'id' => $this->html_id,
4899 'width' => $this->width,