Merge branch 'MDL-66614_36' of https://github.com/timhunt/moodle into MOODLE_36_STABLE
[moodle.git] / lib / outputcomponents.php
blobcb79c92fcc6ff2dddf029a58285b080dc5b0f7a8
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 * @var bool Include user authentication token.
212 public $includetoken = false;
215 * User picture constructor.
217 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
218 * It is recommended to add also contextid of the user for performance reasons.
220 public function __construct(stdClass $user) {
221 global $DB;
223 if (empty($user->id)) {
224 throw new coding_exception('User id is required when printing user avatar image.');
227 // only touch the DB if we are missing data and complain loudly...
228 $needrec = false;
229 foreach (self::$fields as $field) {
230 if (!array_key_exists($field, $user)) {
231 $needrec = true;
232 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
233 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
234 break;
238 if ($needrec) {
239 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
240 } else {
241 $this->user = clone($user);
246 * Returns a list of required user fields, useful when fetching required user info from db.
248 * In some cases we have to fetch the user data together with some other information,
249 * the idalias is useful there because the id would otherwise override the main
250 * id of the result record. Please note it has to be converted back to id before rendering.
252 * @param string $tableprefix name of database table prefix in query
253 * @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)
254 * @param string $idalias alias of id field
255 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
256 * @return string
258 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
259 if (!$tableprefix and !$extrafields and !$idalias) {
260 return implode(',', self::$fields);
262 if ($tableprefix) {
263 $tableprefix .= '.';
265 foreach (self::$fields as $field) {
266 if ($field === 'id' and $idalias and $idalias !== 'id') {
267 $fields[$field] = "$tableprefix$field AS $idalias";
268 } else {
269 if ($fieldprefix and $field !== 'id') {
270 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
271 } else {
272 $fields[$field] = "$tableprefix$field";
276 // add extra fields if not already there
277 if ($extrafields) {
278 foreach ($extrafields as $e) {
279 if ($e === 'id' or isset($fields[$e])) {
280 continue;
282 if ($fieldprefix) {
283 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
284 } else {
285 $fields[$e] = "$tableprefix$e";
289 return implode(',', $fields);
293 * Extract the aliased user fields from a given record
295 * Given a record that was previously obtained using {@link self::fields()} with aliases,
296 * this method extracts user related unaliased fields.
298 * @param stdClass $record containing user picture fields
299 * @param array $extrafields extra fields included in the $record
300 * @param string $idalias alias of the id field
301 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
302 * @return stdClass object with unaliased user fields
304 public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
306 if (empty($idalias)) {
307 $idalias = 'id';
310 $return = new stdClass();
312 foreach (self::$fields as $field) {
313 if ($field === 'id') {
314 if (property_exists($record, $idalias)) {
315 $return->id = $record->{$idalias};
317 } else {
318 if (property_exists($record, $fieldprefix.$field)) {
319 $return->{$field} = $record->{$fieldprefix.$field};
323 // add extra fields if not already there
324 if ($extrafields) {
325 foreach ($extrafields as $e) {
326 if ($e === 'id' or property_exists($return, $e)) {
327 continue;
329 $return->{$e} = $record->{$fieldprefix.$e};
333 return $return;
337 * Works out the URL for the users picture.
339 * This method is recommended as it avoids costly redirects of user pictures
340 * if requests are made for non-existent files etc.
342 * @param moodle_page $page
343 * @param renderer_base $renderer
344 * @return moodle_url
346 public function get_url(moodle_page $page, renderer_base $renderer = null) {
347 global $CFG;
349 if (is_null($renderer)) {
350 $renderer = $page->get_renderer('core');
353 // Sort out the filename and size. Size is only required for the gravatar
354 // implementation presently.
355 if (empty($this->size)) {
356 $filename = 'f2';
357 $size = 35;
358 } else if ($this->size === true or $this->size == 1) {
359 $filename = 'f1';
360 $size = 100;
361 } else if ($this->size > 100) {
362 $filename = 'f3';
363 $size = (int)$this->size;
364 } else if ($this->size >= 50) {
365 $filename = 'f1';
366 $size = (int)$this->size;
367 } else {
368 $filename = 'f2';
369 $size = (int)$this->size;
372 $defaulturl = $renderer->image_url('u/'.$filename); // default image
374 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
375 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
376 // Protect images if login required and not logged in;
377 // also if login is required for profile images and is not logged in or guest
378 // do not use require_login() because it is expensive and not suitable here anyway.
379 return $defaulturl;
382 // First try to detect deleted users - but do not read from database for performance reasons!
383 if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
384 // All deleted users should have email replaced by md5 hash,
385 // all active users are expected to have valid email.
386 return $defaulturl;
389 // Did the user upload a picture?
390 if ($this->user->picture > 0) {
391 if (!empty($this->user->contextid)) {
392 $contextid = $this->user->contextid;
393 } else {
394 $context = context_user::instance($this->user->id, IGNORE_MISSING);
395 if (!$context) {
396 // This must be an incorrectly deleted user, all other users have context.
397 return $defaulturl;
399 $contextid = $context->id;
402 $path = '/';
403 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
404 // We append the theme name to the file path if we have it so that
405 // in the circumstance that the profile picture is not available
406 // when the user actually requests it they still get the profile
407 // picture for the correct theme.
408 $path .= $page->theme->name.'/';
410 // Set the image URL to the URL for the uploaded file and return.
411 $url = moodle_url::make_pluginfile_url(
412 $contextid, 'user', 'icon', null, $path, $filename, false, $this->includetoken);
413 $url->param('rev', $this->user->picture);
414 return $url;
417 if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
418 // Normalise the size variable to acceptable bounds
419 if ($size < 1 || $size > 512) {
420 $size = 35;
422 // Hash the users email address
423 $md5 = md5(strtolower(trim($this->user->email)));
424 // Build a gravatar URL with what we know.
426 // Find the best default image URL we can (MDL-35669)
427 if (empty($CFG->gravatardefaulturl)) {
428 $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
429 if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
430 $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
431 } else {
432 $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
434 } else {
435 $gravatardefault = $CFG->gravatardefaulturl;
438 // If the currently requested page is https then we'll return an
439 // https gravatar page.
440 if (is_https()) {
441 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
442 } else {
443 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
447 return $defaulturl;
452 * Data structure representing a help icon.
454 * @copyright 2010 Petr Skoda (info@skodak.org)
455 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
456 * @since Moodle 2.0
457 * @package core
458 * @category output
460 class help_icon implements renderable, templatable {
463 * @var string lang pack identifier (without the "_help" suffix),
464 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
465 * must exist.
467 public $identifier;
470 * @var string Component name, the same as in get_string()
472 public $component;
475 * @var string Extra descriptive text next to the icon
477 public $linktext = null;
480 * Constructor
482 * @param string $identifier string for help page title,
483 * string with _help suffix is used for the actual help text.
484 * string with _link suffix is used to create a link to further info (if it exists)
485 * @param string $component
487 public function __construct($identifier, $component) {
488 $this->identifier = $identifier;
489 $this->component = $component;
493 * Verifies that both help strings exists, shows debug warnings if not
495 public function diag_strings() {
496 $sm = get_string_manager();
497 if (!$sm->string_exists($this->identifier, $this->component)) {
498 debugging("Help title string does not exist: [$this->identifier, $this->component]");
500 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
501 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
506 * Export this data so it can be used as the context for a mustache template.
508 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
509 * @return array
511 public function export_for_template(renderer_base $output) {
512 global $CFG;
514 $title = get_string($this->identifier, $this->component);
516 if (empty($this->linktext)) {
517 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
518 } else {
519 $alt = get_string('helpwiththis');
522 $data = get_formatted_help_string($this->identifier, $this->component, false);
524 $data->alt = $alt;
525 $data->icon = (new pix_icon('help', $alt, 'core', ['class' => 'iconhelp']))->export_for_template($output);
526 $data->linktext = $this->linktext;
527 $data->title = get_string('helpprefix2', '', trim($title, ". \t"));
529 $options = [
530 'component' => $this->component,
531 'identifier' => $this->identifier,
532 'lang' => current_language()
535 // Debugging feature lets you display string identifier and component.
536 if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
537 $options['strings'] = 1;
540 $data->url = (new moodle_url('/help.php', $options))->out(false);
541 $data->ltr = !right_to_left();
542 return $data;
548 * Data structure representing an icon font.
550 * @copyright 2016 Damyon Wiese
551 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
552 * @package core
553 * @category output
555 class pix_icon_font implements templatable {
558 * @var pix_icon $pixicon The original icon.
560 private $pixicon = null;
563 * @var string $key The mapped key.
565 private $key;
568 * @var bool $mapped The icon could not be mapped.
570 private $mapped;
573 * Constructor
575 * @param pix_icon $pixicon The original icon
577 public function __construct(pix_icon $pixicon) {
578 global $PAGE;
580 $this->pixicon = $pixicon;
581 $this->mapped = false;
582 $iconsystem = \core\output\icon_system::instance();
584 $this->key = $iconsystem->remap_icon_name($pixicon->pix, $pixicon->component);
585 if (!empty($this->key)) {
586 $this->mapped = true;
591 * Return true if this pix_icon was successfully mapped to an icon font.
593 * @return bool
595 public function is_mapped() {
596 return $this->mapped;
600 * Export this data so it can be used as the context for a mustache template.
602 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
603 * @return array
605 public function export_for_template(renderer_base $output) {
607 $pixdata = $this->pixicon->export_for_template($output);
609 $title = isset($this->pixicon->attributes['title']) ? $this->pixicon->attributes['title'] : '';
610 $alt = isset($this->pixicon->attributes['alt']) ? $this->pixicon->attributes['alt'] : '';
611 if (empty($title)) {
612 $title = $alt;
614 $data = array(
615 'extraclasses' => $pixdata['extraclasses'],
616 'title' => $title,
617 'alt' => $alt,
618 'key' => $this->key
621 return $data;
626 * Data structure representing an icon subtype.
628 * @copyright 2016 Damyon Wiese
629 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
630 * @package core
631 * @category output
633 class pix_icon_fontawesome extends pix_icon_font {
638 * Data structure representing an icon.
640 * @copyright 2010 Petr Skoda
641 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
642 * @since Moodle 2.0
643 * @package core
644 * @category output
646 class pix_icon implements renderable, templatable {
649 * @var string The icon name
651 var $pix;
654 * @var string The component the icon belongs to.
656 var $component;
659 * @var array An array of attributes to use on the icon
661 var $attributes = array();
664 * Constructor
666 * @param string $pix short icon name
667 * @param string $alt The alt text to use for the icon
668 * @param string $component component name
669 * @param array $attributes html attributes
671 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
672 global $PAGE;
674 $this->pix = $pix;
675 $this->component = $component;
676 $this->attributes = (array)$attributes;
678 if (empty($this->attributes['class'])) {
679 $this->attributes['class'] = '';
682 // Set an additional class for big icons so that they can be styled properly.
683 if (substr($pix, 0, 2) === 'b/') {
684 $this->attributes['class'] .= ' iconsize-big';
687 // If the alt is empty, don't place it in the attributes, otherwise it will override parent alt text.
688 if (!is_null($alt)) {
689 $this->attributes['alt'] = $alt;
691 // If there is no title, set it to the attribute.
692 if (!isset($this->attributes['title'])) {
693 $this->attributes['title'] = $this->attributes['alt'];
695 } else {
696 unset($this->attributes['alt']);
699 if (empty($this->attributes['title'])) {
700 // Remove the title attribute if empty, we probably want to use the parent node's title
701 // and some browsers might overwrite it with an empty title.
702 unset($this->attributes['title']);
705 // Hide icons from screen readers that have no alt.
706 if (empty($this->attributes['alt'])) {
707 $this->attributes['aria-hidden'] = 'true';
712 * Export this data so it can be used as the context for a mustache template.
714 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
715 * @return array
717 public function export_for_template(renderer_base $output) {
718 $attributes = $this->attributes;
719 $extraclasses = '';
721 foreach ($attributes as $key => $item) {
722 if ($key == 'class') {
723 $extraclasses = $item;
724 unset($attributes[$key]);
725 break;
729 $attributes['src'] = $output->image_url($this->pix, $this->component)->out(false);
730 $templatecontext = array();
731 foreach ($attributes as $name => $value) {
732 $templatecontext[] = array('name' => $name, 'value' => $value);
734 $title = isset($attributes['title']) ? $attributes['title'] : '';
735 if (empty($title)) {
736 $title = isset($attributes['alt']) ? $attributes['alt'] : '';
738 $data = array(
739 'attributes' => $templatecontext,
740 'extraclasses' => $extraclasses
743 return $data;
747 * Much simpler version of export that will produce the data required to render this pix with the
748 * pix helper in a mustache tag.
750 * @return array
752 public function export_for_pix() {
753 $title = isset($this->attributes['title']) ? $this->attributes['title'] : '';
754 if (empty($title)) {
755 $title = isset($this->attributes['alt']) ? $this->attributes['alt'] : '';
757 return [
758 'key' => $this->pix,
759 'component' => $this->component,
760 'title' => $title
766 * Data structure representing an activity icon.
768 * The difference is that activity icons will always render with the standard icon system (no font icons).
770 * @copyright 2017 Damyon Wiese
771 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
772 * @package core
774 class image_icon extends pix_icon {
778 * Data structure representing an emoticon image
780 * @copyright 2010 David Mudrak
781 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
782 * @since Moodle 2.0
783 * @package core
784 * @category output
786 class pix_emoticon extends pix_icon implements renderable {
789 * Constructor
790 * @param string $pix short icon name
791 * @param string $alt alternative text
792 * @param string $component emoticon image provider
793 * @param array $attributes explicit HTML attributes
795 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
796 if (empty($attributes['class'])) {
797 $attributes['class'] = 'emoticon';
799 parent::__construct($pix, $alt, $component, $attributes);
804 * Data structure representing a simple form with only one button.
806 * @copyright 2009 Petr Skoda
807 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
808 * @since Moodle 2.0
809 * @package core
810 * @category output
812 class single_button implements renderable {
815 * @var moodle_url Target url
817 public $url;
820 * @var string Button label
822 public $label;
825 * @var string Form submit method post or get
827 public $method = 'post';
830 * @var string Wrapping div class
832 public $class = 'singlebutton';
835 * @var bool True if button is primary button. Used for styling.
837 public $primary = false;
840 * @var bool True if button disabled, false if normal
842 public $disabled = false;
845 * @var string Button tooltip
847 public $tooltip = null;
850 * @var string Form id
852 public $formid;
855 * @var array List of attached actions
857 public $actions = array();
860 * @var array $params URL Params
862 public $params;
865 * @var string Action id
867 public $actionid;
870 * Constructor
871 * @param moodle_url $url
872 * @param string $label button text
873 * @param string $method get or post submit method
875 public function __construct(moodle_url $url, $label, $method='post', $primary=false) {
876 $this->url = clone($url);
877 $this->label = $label;
878 $this->method = $method;
879 $this->primary = $primary;
883 * Shortcut for adding a JS confirm dialog when the button is clicked.
884 * The message must be a yes/no question.
886 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
888 public function add_confirm_action($confirmmessage) {
889 $this->add_action(new confirm_action($confirmmessage));
893 * Add action to the button.
894 * @param component_action $action
896 public function add_action(component_action $action) {
897 $this->actions[] = $action;
901 * Export data.
903 * @param renderer_base $output Renderer.
904 * @return stdClass
906 public function export_for_template(renderer_base $output) {
907 $url = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
909 $data = new stdClass();
910 $data->id = html_writer::random_id('single_button');
911 $data->formid = $this->formid;
912 $data->method = $this->method;
913 $data->url = $url === '' ? '#' : $url;
914 $data->label = $this->label;
915 $data->classes = $this->class;
916 $data->disabled = $this->disabled;
917 $data->tooltip = $this->tooltip;
918 $data->primary = $this->primary;
920 // Form parameters.
921 $params = $this->url->params();
922 if ($this->method === 'post') {
923 $params['sesskey'] = sesskey();
925 $data->params = array_map(function($key) use ($params) {
926 return ['name' => $key, 'value' => $params[$key]];
927 }, array_keys($params));
929 // Button actions.
930 $actions = $this->actions;
931 $data->actions = array_map(function($action) use ($output) {
932 return $action->export_for_template($output);
933 }, $actions);
934 $data->hasactions = !empty($data->actions);
936 return $data;
942 * Simple form with just one select field that gets submitted automatically.
944 * If JS not enabled small go button is printed too.
946 * @copyright 2009 Petr Skoda
947 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
948 * @since Moodle 2.0
949 * @package core
950 * @category output
952 class single_select implements renderable, templatable {
955 * @var moodle_url Target url - includes hidden fields
957 var $url;
960 * @var string Name of the select element.
962 var $name;
965 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
966 * it is also possible to specify optgroup as complex label array ex.:
967 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
968 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
970 var $options;
973 * @var string Selected option
975 var $selected;
978 * @var array Nothing selected
980 var $nothing;
983 * @var array Extra select field attributes
985 var $attributes = array();
988 * @var string Button label
990 var $label = '';
993 * @var array Button label's attributes
995 var $labelattributes = array();
998 * @var string Form submit method post or get
1000 var $method = 'get';
1003 * @var string Wrapping div class
1005 var $class = 'singleselect';
1008 * @var bool True if button disabled, false if normal
1010 var $disabled = false;
1013 * @var string Button tooltip
1015 var $tooltip = null;
1018 * @var string Form id
1020 var $formid = null;
1023 * @var help_icon The help icon for this element.
1025 var $helpicon = null;
1028 * Constructor
1029 * @param moodle_url $url form action target, includes hidden fields
1030 * @param string $name name of selection field - the changing parameter in url
1031 * @param array $options list of options
1032 * @param string $selected selected element
1033 * @param array $nothing
1034 * @param string $formid
1036 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1037 $this->url = $url;
1038 $this->name = $name;
1039 $this->options = $options;
1040 $this->selected = $selected;
1041 $this->nothing = $nothing;
1042 $this->formid = $formid;
1046 * Shortcut for adding a JS confirm dialog when the button is clicked.
1047 * The message must be a yes/no question.
1049 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
1051 public function add_confirm_action($confirmmessage) {
1052 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
1056 * Add action to the button.
1058 * @param component_action $action
1060 public function add_action(component_action $action) {
1061 $this->actions[] = $action;
1065 * Adds help icon.
1067 * @deprecated since Moodle 2.0
1069 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1070 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1074 * Adds help icon.
1076 * @param string $identifier The keyword that defines a help page
1077 * @param string $component
1079 public function set_help_icon($identifier, $component = 'moodle') {
1080 $this->helpicon = new help_icon($identifier, $component);
1084 * Sets select's label
1086 * @param string $label
1087 * @param array $attributes (optional)
1089 public function set_label($label, $attributes = array()) {
1090 $this->label = $label;
1091 $this->labelattributes = $attributes;
1096 * Export data.
1098 * @param renderer_base $output Renderer.
1099 * @return stdClass
1101 public function export_for_template(renderer_base $output) {
1102 $attributes = $this->attributes;
1104 $data = new stdClass();
1105 $data->name = $this->name;
1106 $data->method = $this->method;
1107 $data->action = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
1108 $data->classes = $this->class;
1109 $data->label = $this->label;
1110 $data->disabled = $this->disabled;
1111 $data->title = $this->tooltip;
1112 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('single_select_f');
1113 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('single_select');
1115 // Select element attributes.
1116 // Unset attributes that are already predefined in the template.
1117 unset($attributes['id']);
1118 unset($attributes['class']);
1119 unset($attributes['name']);
1120 unset($attributes['title']);
1121 unset($attributes['disabled']);
1123 // Map the attributes.
1124 $data->attributes = array_map(function($key) use ($attributes) {
1125 return ['name' => $key, 'value' => $attributes[$key]];
1126 }, array_keys($attributes));
1128 // Form parameters.
1129 $params = $this->url->params();
1130 if ($this->method === 'post') {
1131 $params['sesskey'] = sesskey();
1133 $data->params = array_map(function($key) use ($params) {
1134 return ['name' => $key, 'value' => $params[$key]];
1135 }, array_keys($params));
1137 // Select options.
1138 $hasnothing = false;
1139 if (is_string($this->nothing) && $this->nothing !== '') {
1140 $nothing = ['' => $this->nothing];
1141 $hasnothing = true;
1142 $nothingkey = '';
1143 } else if (is_array($this->nothing)) {
1144 $nothingvalue = reset($this->nothing);
1145 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1146 $nothing = [key($this->nothing) => get_string('choosedots')];
1147 } else {
1148 $nothing = $this->nothing;
1150 $hasnothing = true;
1151 $nothingkey = key($this->nothing);
1153 if ($hasnothing) {
1154 $options = $nothing + $this->options;
1155 } else {
1156 $options = $this->options;
1159 foreach ($options as $value => $name) {
1160 if (is_array($options[$value])) {
1161 foreach ($options[$value] as $optgroupname => $optgroupvalues) {
1162 $sublist = [];
1163 foreach ($optgroupvalues as $optvalue => $optname) {
1164 $option = [
1165 'value' => $optvalue,
1166 'name' => $optname,
1167 'selected' => strval($this->selected) === strval($optvalue),
1170 if ($hasnothing && $nothingkey === $optvalue) {
1171 $option['ignore'] = 'data-ignore';
1174 $sublist[] = $option;
1176 $data->options[] = [
1177 'name' => $optgroupname,
1178 'optgroup' => true,
1179 'options' => $sublist
1182 } else {
1183 $option = [
1184 'value' => $value,
1185 'name' => $options[$value],
1186 'selected' => strval($this->selected) === strval($value),
1187 'optgroup' => false
1190 if ($hasnothing && $nothingkey === $value) {
1191 $option['ignore'] = 'data-ignore';
1194 $data->options[] = $option;
1198 // Label attributes.
1199 $data->labelattributes = [];
1200 // Unset label attributes that are already in the template.
1201 unset($this->labelattributes['for']);
1202 // Map the label attributes.
1203 foreach ($this->labelattributes as $key => $value) {
1204 $data->labelattributes[] = ['name' => $key, 'value' => $value];
1207 // Help icon.
1208 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1210 return $data;
1215 * Simple URL selection widget description.
1217 * @copyright 2009 Petr Skoda
1218 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1219 * @since Moodle 2.0
1220 * @package core
1221 * @category output
1223 class url_select implements renderable, templatable {
1225 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
1226 * it is also possible to specify optgroup as complex label array ex.:
1227 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1228 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1230 var $urls;
1233 * @var string Selected option
1235 var $selected;
1238 * @var array Nothing selected
1240 var $nothing;
1243 * @var array Extra select field attributes
1245 var $attributes = array();
1248 * @var string Button label
1250 var $label = '';
1253 * @var array Button label's attributes
1255 var $labelattributes = array();
1258 * @var string Wrapping div class
1260 var $class = 'urlselect';
1263 * @var bool True if button disabled, false if normal
1265 var $disabled = false;
1268 * @var string Button tooltip
1270 var $tooltip = null;
1273 * @var string Form id
1275 var $formid = null;
1278 * @var help_icon The help icon for this element.
1280 var $helpicon = null;
1283 * @var string If set, makes button visible with given name for button
1285 var $showbutton = null;
1288 * Constructor
1289 * @param array $urls list of options
1290 * @param string $selected selected element
1291 * @param array $nothing
1292 * @param string $formid
1293 * @param string $showbutton Set to text of button if it should be visible
1294 * or null if it should be hidden (hidden version always has text 'go')
1296 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
1297 $this->urls = $urls;
1298 $this->selected = $selected;
1299 $this->nothing = $nothing;
1300 $this->formid = $formid;
1301 $this->showbutton = $showbutton;
1305 * Adds help icon.
1307 * @deprecated since Moodle 2.0
1309 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1310 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1314 * Adds help icon.
1316 * @param string $identifier The keyword that defines a help page
1317 * @param string $component
1319 public function set_help_icon($identifier, $component = 'moodle') {
1320 $this->helpicon = new help_icon($identifier, $component);
1324 * Sets select's label
1326 * @param string $label
1327 * @param array $attributes (optional)
1329 public function set_label($label, $attributes = array()) {
1330 $this->label = $label;
1331 $this->labelattributes = $attributes;
1335 * Clean a URL.
1337 * @param string $value The URL.
1338 * @return The cleaned URL.
1340 protected function clean_url($value) {
1341 global $CFG;
1343 if (empty($value)) {
1344 // Nothing.
1346 } else if (strpos($value, $CFG->wwwroot . '/') === 0) {
1347 $value = str_replace($CFG->wwwroot, '', $value);
1349 } else if (strpos($value, '/') !== 0) {
1350 debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER);
1353 return $value;
1357 * Flatten the options for Mustache.
1359 * This also cleans the URLs.
1361 * @param array $options The options.
1362 * @param array $nothing The nothing option.
1363 * @return array
1365 protected function flatten_options($options, $nothing) {
1366 $flattened = [];
1368 foreach ($options as $value => $option) {
1369 if (is_array($option)) {
1370 foreach ($option as $groupname => $optoptions) {
1371 if (!isset($flattened[$groupname])) {
1372 $flattened[$groupname] = [
1373 'name' => $groupname,
1374 'isgroup' => true,
1375 'options' => []
1378 foreach ($optoptions as $optvalue => $optoption) {
1379 $cleanedvalue = $this->clean_url($optvalue);
1380 $flattened[$groupname]['options'][$cleanedvalue] = [
1381 'name' => $optoption,
1382 'value' => $cleanedvalue,
1383 'selected' => $this->selected == $optvalue,
1388 } else {
1389 $cleanedvalue = $this->clean_url($value);
1390 $flattened[$cleanedvalue] = [
1391 'name' => $option,
1392 'value' => $cleanedvalue,
1393 'selected' => $this->selected == $value,
1398 if (!empty($nothing)) {
1399 $value = key($nothing);
1400 $name = reset($nothing);
1401 $flattened = [
1402 $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value]
1403 ] + $flattened;
1406 // Make non-associative array.
1407 foreach ($flattened as $key => $value) {
1408 if (!empty($value['options'])) {
1409 $flattened[$key]['options'] = array_values($value['options']);
1412 $flattened = array_values($flattened);
1414 return $flattened;
1418 * Export for template.
1420 * @param renderer_base $output Renderer.
1421 * @return stdClass
1423 public function export_for_template(renderer_base $output) {
1424 $attributes = $this->attributes;
1426 $data = new stdClass();
1427 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('url_select_f');
1428 $data->classes = $this->class;
1429 $data->label = $this->label;
1430 $data->disabled = $this->disabled;
1431 $data->title = $this->tooltip;
1432 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('url_select');
1433 $data->sesskey = sesskey();
1434 $data->action = (new moodle_url('/course/jumpto.php'))->out(false);
1436 // Remove attributes passed as property directly.
1437 unset($attributes['class']);
1438 unset($attributes['id']);
1439 unset($attributes['name']);
1440 unset($attributes['title']);
1441 unset($attributes['disabled']);
1443 $data->showbutton = $this->showbutton;
1445 // Select options.
1446 $nothing = false;
1447 if (is_string($this->nothing) && $this->nothing !== '') {
1448 $nothing = ['' => $this->nothing];
1449 } else if (is_array($this->nothing)) {
1450 $nothingvalue = reset($this->nothing);
1451 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1452 $nothing = [key($this->nothing) => get_string('choosedots')];
1453 } else {
1454 $nothing = $this->nothing;
1457 $data->options = $this->flatten_options($this->urls, $nothing);
1459 // Label attributes.
1460 $data->labelattributes = [];
1461 // Unset label attributes that are already in the template.
1462 unset($this->labelattributes['for']);
1463 // Map the label attributes.
1464 foreach ($this->labelattributes as $key => $value) {
1465 $data->labelattributes[] = ['name' => $key, 'value' => $value];
1468 // Help icon.
1469 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1471 // Finally all the remaining attributes.
1472 $data->attributes = [];
1473 foreach ($attributes as $key => $value) {
1474 $data->attributes[] = ['name' => $key, 'value' => $value];
1477 return $data;
1482 * Data structure describing html link with special action attached.
1484 * @copyright 2010 Petr Skoda
1485 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1486 * @since Moodle 2.0
1487 * @package core
1488 * @category output
1490 class action_link implements renderable {
1493 * @var moodle_url Href url
1495 public $url;
1498 * @var string Link text HTML fragment
1500 public $text;
1503 * @var array HTML attributes
1505 public $attributes;
1508 * @var array List of actions attached to link
1510 public $actions;
1513 * @var pix_icon Optional pix icon to render with the link
1515 public $icon;
1518 * Constructor
1519 * @param moodle_url $url
1520 * @param string $text HTML fragment
1521 * @param component_action $action
1522 * @param array $attributes associative array of html link attributes + disabled
1523 * @param pix_icon $icon optional pix_icon to render with the link text
1525 public function __construct(moodle_url $url,
1526 $text,
1527 component_action $action=null,
1528 array $attributes=null,
1529 pix_icon $icon=null) {
1530 $this->url = clone($url);
1531 $this->text = $text;
1532 $this->attributes = (array)$attributes;
1533 if ($action) {
1534 $this->add_action($action);
1536 $this->icon = $icon;
1540 * Add action to the link.
1542 * @param component_action $action
1544 public function add_action(component_action $action) {
1545 $this->actions[] = $action;
1549 * Adds a CSS class to this action link object
1550 * @param string $class
1552 public function add_class($class) {
1553 if (empty($this->attributes['class'])) {
1554 $this->attributes['class'] = $class;
1555 } else {
1556 $this->attributes['class'] .= ' ' . $class;
1561 * Returns true if the specified class has been added to this link.
1562 * @param string $class
1563 * @return bool
1565 public function has_class($class) {
1566 return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
1570 * Return the rendered HTML for the icon. Useful for rendering action links in a template.
1571 * @return string
1573 public function get_icon_html() {
1574 global $OUTPUT;
1575 if (!$this->icon) {
1576 return '';
1578 return $OUTPUT->render($this->icon);
1582 * Export for template.
1584 * @param renderer_base $output The renderer.
1585 * @return stdClass
1587 public function export_for_template(renderer_base $output) {
1588 $data = new stdClass();
1589 $attributes = $this->attributes;
1591 if (empty($attributes['id'])) {
1592 $attributes['id'] = html_writer::random_id('action_link');
1594 $data->id = $attributes['id'];
1595 unset($attributes['id']);
1597 $data->disabled = !empty($attributes['disabled']);
1598 unset($attributes['disabled']);
1600 $data->text = $this->text instanceof renderable ? $output->render($this->text) : (string) $this->text;
1601 $data->url = $this->url ? $this->url->out(false) : '';
1602 $data->icon = $this->icon ? $this->icon->export_for_pix() : null;
1603 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
1604 unset($attributes['class']);
1606 $data->attributes = array_map(function($key, $value) {
1607 return [
1608 'name' => $key,
1609 'value' => $value
1611 }, array_keys($attributes), $attributes);
1613 $data->actions = array_map(function($action) use ($output) {
1614 return $action->export_for_template($output);
1615 }, !empty($this->actions) ? $this->actions : []);
1616 $data->hasactions = !empty($this->actions);
1618 return $data;
1623 * Simple html output class
1625 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1626 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1627 * @since Moodle 2.0
1628 * @package core
1629 * @category output
1631 class html_writer {
1634 * Outputs a tag with attributes and contents
1636 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1637 * @param string $contents What goes between the opening and closing tags
1638 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1639 * @return string HTML fragment
1641 public static function tag($tagname, $contents, array $attributes = null) {
1642 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1646 * Outputs an opening tag with attributes
1648 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1649 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1650 * @return string HTML fragment
1652 public static function start_tag($tagname, array $attributes = null) {
1653 return '<' . $tagname . self::attributes($attributes) . '>';
1657 * Outputs a closing tag
1659 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1660 * @return string HTML fragment
1662 public static function end_tag($tagname) {
1663 return '</' . $tagname . '>';
1667 * Outputs an empty tag with attributes
1669 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1670 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1671 * @return string HTML fragment
1673 public static function empty_tag($tagname, array $attributes = null) {
1674 return '<' . $tagname . self::attributes($attributes) . ' />';
1678 * Outputs a tag, but only if the contents are not empty
1680 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1681 * @param string $contents What goes between the opening and closing tags
1682 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1683 * @return string HTML fragment
1685 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1686 if ($contents === '' || is_null($contents)) {
1687 return '';
1689 return self::tag($tagname, $contents, $attributes);
1693 * Outputs a HTML attribute and value
1695 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1696 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1697 * @return string HTML fragment
1699 public static function attribute($name, $value) {
1700 if ($value instanceof moodle_url) {
1701 return ' ' . $name . '="' . $value->out() . '"';
1704 // special case, we do not want these in output
1705 if ($value === null) {
1706 return '';
1709 // no sloppy trimming here!
1710 return ' ' . $name . '="' . s($value) . '"';
1714 * Outputs a list of HTML attributes and values
1716 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1717 * The values will be escaped with {@link s()}
1718 * @return string HTML fragment
1720 public static function attributes(array $attributes = null) {
1721 $attributes = (array)$attributes;
1722 $output = '';
1723 foreach ($attributes as $name => $value) {
1724 $output .= self::attribute($name, $value);
1726 return $output;
1730 * Generates a simple image tag with attributes.
1732 * @param string $src The source of image
1733 * @param string $alt The alternate text for image
1734 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1735 * @return string HTML fragment
1737 public static function img($src, $alt, array $attributes = null) {
1738 $attributes = (array)$attributes;
1739 $attributes['src'] = $src;
1740 $attributes['alt'] = $alt;
1742 return self::empty_tag('img', $attributes);
1746 * Generates random html element id.
1748 * @staticvar int $counter
1749 * @staticvar type $uniq
1750 * @param string $base A string fragment that will be included in the random ID.
1751 * @return string A unique ID
1753 public static function random_id($base='random') {
1754 static $counter = 0;
1755 static $uniq;
1757 if (!isset($uniq)) {
1758 $uniq = uniqid();
1761 $counter++;
1762 return $base.$uniq.$counter;
1766 * Generates a simple html link
1768 * @param string|moodle_url $url The URL
1769 * @param string $text The text
1770 * @param array $attributes HTML attributes
1771 * @return string HTML fragment
1773 public static function link($url, $text, array $attributes = null) {
1774 $attributes = (array)$attributes;
1775 $attributes['href'] = $url;
1776 return self::tag('a', $text, $attributes);
1780 * Generates a simple checkbox with optional label
1782 * @param string $name The name of the checkbox
1783 * @param string $value The value of the checkbox
1784 * @param bool $checked Whether the checkbox is checked
1785 * @param string $label The label for the checkbox
1786 * @param array $attributes Any attributes to apply to the checkbox
1787 * @return string html fragment
1789 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1790 $attributes = (array)$attributes;
1791 $output = '';
1793 if ($label !== '' and !is_null($label)) {
1794 if (empty($attributes['id'])) {
1795 $attributes['id'] = self::random_id('checkbox_');
1798 $attributes['type'] = 'checkbox';
1799 $attributes['value'] = $value;
1800 $attributes['name'] = $name;
1801 $attributes['checked'] = $checked ? 'checked' : null;
1803 $output .= self::empty_tag('input', $attributes);
1805 if ($label !== '' and !is_null($label)) {
1806 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1809 return $output;
1813 * Generates a simple select yes/no form field
1815 * @param string $name name of select element
1816 * @param bool $selected
1817 * @param array $attributes - html select element attributes
1818 * @return string HTML fragment
1820 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1821 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1822 return self::select($options, $name, $selected, null, $attributes);
1826 * Generates a simple select form field
1828 * @param array $options associative array value=>label ex.:
1829 * array(1=>'One, 2=>Two)
1830 * it is also possible to specify optgroup as complex label array ex.:
1831 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1832 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1833 * @param string $name name of select element
1834 * @param string|array $selected value or array of values depending on multiple attribute
1835 * @param array|bool $nothing add nothing selected option, or false of not added
1836 * @param array $attributes html select element attributes
1837 * @return string HTML fragment
1839 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1840 $attributes = (array)$attributes;
1841 if (is_array($nothing)) {
1842 foreach ($nothing as $k=>$v) {
1843 if ($v === 'choose' or $v === 'choosedots') {
1844 $nothing[$k] = get_string('choosedots');
1847 $options = $nothing + $options; // keep keys, do not override
1849 } else if (is_string($nothing) and $nothing !== '') {
1850 // BC
1851 $options = array(''=>$nothing) + $options;
1854 // we may accept more values if multiple attribute specified
1855 $selected = (array)$selected;
1856 foreach ($selected as $k=>$v) {
1857 $selected[$k] = (string)$v;
1860 if (!isset($attributes['id'])) {
1861 $id = 'menu'.$name;
1862 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1863 $id = str_replace('[', '', $id);
1864 $id = str_replace(']', '', $id);
1865 $attributes['id'] = $id;
1868 if (!isset($attributes['class'])) {
1869 $class = 'menu'.$name;
1870 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1871 $class = str_replace('[', '', $class);
1872 $class = str_replace(']', '', $class);
1873 $attributes['class'] = $class;
1875 $attributes['class'] = 'select custom-select ' . $attributes['class']; // Add 'select' selector always.
1877 $attributes['name'] = $name;
1879 if (!empty($attributes['disabled'])) {
1880 $attributes['disabled'] = 'disabled';
1881 } else {
1882 unset($attributes['disabled']);
1885 $output = '';
1886 foreach ($options as $value=>$label) {
1887 if (is_array($label)) {
1888 // ignore key, it just has to be unique
1889 $output .= self::select_optgroup(key($label), current($label), $selected);
1890 } else {
1891 $output .= self::select_option($label, $value, $selected);
1894 return self::tag('select', $output, $attributes);
1898 * Returns HTML to display a select box option.
1900 * @param string $label The label to display as the option.
1901 * @param string|int $value The value the option represents
1902 * @param array $selected An array of selected options
1903 * @return string HTML fragment
1905 private static function select_option($label, $value, array $selected) {
1906 $attributes = array();
1907 $value = (string)$value;
1908 if (in_array($value, $selected, true)) {
1909 $attributes['selected'] = 'selected';
1911 $attributes['value'] = $value;
1912 return self::tag('option', $label, $attributes);
1916 * Returns HTML to display a select box option group.
1918 * @param string $groupname The label to use for the group
1919 * @param array $options The options in the group
1920 * @param array $selected An array of selected values.
1921 * @return string HTML fragment.
1923 private static function select_optgroup($groupname, $options, array $selected) {
1924 if (empty($options)) {
1925 return '';
1927 $attributes = array('label'=>$groupname);
1928 $output = '';
1929 foreach ($options as $value=>$label) {
1930 $output .= self::select_option($label, $value, $selected);
1932 return self::tag('optgroup', $output, $attributes);
1936 * This is a shortcut for making an hour selector menu.
1938 * @param string $type The type of selector (years, months, days, hours, minutes)
1939 * @param string $name fieldname
1940 * @param int $currenttime A default timestamp in GMT
1941 * @param int $step minute spacing
1942 * @param array $attributes - html select element attributes
1943 * @return HTML fragment
1945 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1946 global $OUTPUT;
1948 if (!$currenttime) {
1949 $currenttime = time();
1951 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1952 $currentdate = $calendartype->timestamp_to_date_array($currenttime);
1953 $userdatetype = $type;
1954 $timeunits = array();
1956 switch ($type) {
1957 case 'years':
1958 $timeunits = $calendartype->get_years();
1959 $userdatetype = 'year';
1960 break;
1961 case 'months':
1962 $timeunits = $calendartype->get_months();
1963 $userdatetype = 'month';
1964 $currentdate['month'] = (int)$currentdate['mon'];
1965 break;
1966 case 'days':
1967 $timeunits = $calendartype->get_days();
1968 $userdatetype = 'mday';
1969 break;
1970 case 'hours':
1971 for ($i=0; $i<=23; $i++) {
1972 $timeunits[$i] = sprintf("%02d",$i);
1974 break;
1975 case 'minutes':
1976 if ($step != 1) {
1977 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1980 for ($i=0; $i<=59; $i+=$step) {
1981 $timeunits[$i] = sprintf("%02d",$i);
1983 break;
1984 default:
1985 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1988 $attributes = (array) $attributes;
1989 $data = (object) [
1990 'name' => $name,
1991 'id' => !empty($attributes['id']) ? $attributes['id'] : self::random_id('ts_'),
1992 'label' => get_string(substr($type, 0, -1), 'form'),
1993 'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) {
1994 return [
1995 'name' => $timeunits[$value],
1996 'value' => $value,
1997 'selected' => $currentdate[$userdatetype] == $value
1999 }, array_keys($timeunits)),
2002 unset($attributes['id']);
2003 unset($attributes['name']);
2004 $data->attributes = array_map(function($name) use ($attributes) {
2005 return [
2006 'name' => $name,
2007 'value' => $attributes[$name]
2009 }, array_keys($attributes));
2011 return $OUTPUT->render_from_template('core/select_time', $data);
2015 * Shortcut for quick making of lists
2017 * Note: 'list' is a reserved keyword ;-)
2019 * @param array $items
2020 * @param array $attributes
2021 * @param string $tag ul or ol
2022 * @return string
2024 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
2025 $output = html_writer::start_tag($tag, $attributes)."\n";
2026 foreach ($items as $item) {
2027 $output .= html_writer::tag('li', $item)."\n";
2029 $output .= html_writer::end_tag($tag);
2030 return $output;
2034 * Returns hidden input fields created from url parameters.
2036 * @param moodle_url $url
2037 * @param array $exclude list of excluded parameters
2038 * @return string HTML fragment
2040 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
2041 $exclude = (array)$exclude;
2042 $params = $url->params();
2043 foreach ($exclude as $key) {
2044 unset($params[$key]);
2047 $output = '';
2048 foreach ($params as $key => $value) {
2049 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
2050 $output .= self::empty_tag('input', $attributes)."\n";
2052 return $output;
2056 * Generate a script tag containing the the specified code.
2058 * @param string $jscode the JavaScript code
2059 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
2060 * @return string HTML, the code wrapped in <script> tags.
2062 public static function script($jscode, $url=null) {
2063 if ($jscode) {
2064 $attributes = array('type'=>'text/javascript');
2065 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
2067 } else if ($url) {
2068 $attributes = array('type'=>'text/javascript', 'src'=>$url);
2069 return self::tag('script', '', $attributes) . "\n";
2071 } else {
2072 return '';
2077 * Renders HTML table
2079 * This method may modify the passed instance by adding some default properties if they are not set yet.
2080 * If this is not what you want, you should make a full clone of your data before passing them to this
2081 * method. In most cases this is not an issue at all so we do not clone by default for performance
2082 * and memory consumption reasons.
2084 * @param html_table $table data to be rendered
2085 * @return string HTML code
2087 public static function table(html_table $table) {
2088 // prepare table data and populate missing properties with reasonable defaults
2089 if (!empty($table->align)) {
2090 foreach ($table->align as $key => $aa) {
2091 if ($aa) {
2092 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
2093 } else {
2094 $table->align[$key] = null;
2098 if (!empty($table->size)) {
2099 foreach ($table->size as $key => $ss) {
2100 if ($ss) {
2101 $table->size[$key] = 'width:'. $ss .';';
2102 } else {
2103 $table->size[$key] = null;
2107 if (!empty($table->wrap)) {
2108 foreach ($table->wrap as $key => $ww) {
2109 if ($ww) {
2110 $table->wrap[$key] = 'white-space:nowrap;';
2111 } else {
2112 $table->wrap[$key] = '';
2116 if (!empty($table->head)) {
2117 foreach ($table->head as $key => $val) {
2118 if (!isset($table->align[$key])) {
2119 $table->align[$key] = null;
2121 if (!isset($table->size[$key])) {
2122 $table->size[$key] = null;
2124 if (!isset($table->wrap[$key])) {
2125 $table->wrap[$key] = null;
2130 if (empty($table->attributes['class'])) {
2131 $table->attributes['class'] = 'generaltable';
2133 if (!empty($table->tablealign)) {
2134 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
2137 // explicitly assigned properties override those defined via $table->attributes
2138 $table->attributes['class'] = trim($table->attributes['class']);
2139 $attributes = array_merge($table->attributes, array(
2140 'id' => $table->id,
2141 'width' => $table->width,
2142 'summary' => $table->summary,
2143 'cellpadding' => $table->cellpadding,
2144 'cellspacing' => $table->cellspacing,
2146 $output = html_writer::start_tag('table', $attributes) . "\n";
2148 $countcols = 0;
2150 // Output a caption if present.
2151 if (!empty($table->caption)) {
2152 $captionattributes = array();
2153 if ($table->captionhide) {
2154 $captionattributes['class'] = 'accesshide';
2156 $output .= html_writer::tag(
2157 'caption',
2158 $table->caption,
2159 $captionattributes
2163 if (!empty($table->head)) {
2164 $countcols = count($table->head);
2166 $output .= html_writer::start_tag('thead', array()) . "\n";
2167 $output .= html_writer::start_tag('tr', array()) . "\n";
2168 $keys = array_keys($table->head);
2169 $lastkey = end($keys);
2171 foreach ($table->head as $key => $heading) {
2172 // Convert plain string headings into html_table_cell objects
2173 if (!($heading instanceof html_table_cell)) {
2174 $headingtext = $heading;
2175 $heading = new html_table_cell();
2176 $heading->text = $headingtext;
2177 $heading->header = true;
2180 if ($heading->header !== false) {
2181 $heading->header = true;
2184 if ($heading->header && empty($heading->scope)) {
2185 $heading->scope = 'col';
2188 $heading->attributes['class'] .= ' header c' . $key;
2189 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
2190 $heading->colspan = $table->headspan[$key];
2191 $countcols += $table->headspan[$key] - 1;
2194 if ($key == $lastkey) {
2195 $heading->attributes['class'] .= ' lastcol';
2197 if (isset($table->colclasses[$key])) {
2198 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
2200 $heading->attributes['class'] = trim($heading->attributes['class']);
2201 $attributes = array_merge($heading->attributes, array(
2202 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
2203 'scope' => $heading->scope,
2204 'colspan' => $heading->colspan,
2207 $tagtype = 'td';
2208 if ($heading->header === true) {
2209 $tagtype = 'th';
2211 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
2213 $output .= html_writer::end_tag('tr') . "\n";
2214 $output .= html_writer::end_tag('thead') . "\n";
2216 if (empty($table->data)) {
2217 // For valid XHTML strict every table must contain either a valid tr
2218 // or a valid tbody... both of which must contain a valid td
2219 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
2220 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
2221 $output .= html_writer::end_tag('tbody');
2225 if (!empty($table->data)) {
2226 $keys = array_keys($table->data);
2227 $lastrowkey = end($keys);
2228 $output .= html_writer::start_tag('tbody', array());
2230 foreach ($table->data as $key => $row) {
2231 if (($row === 'hr') && ($countcols)) {
2232 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
2233 } else {
2234 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
2235 if (!($row instanceof html_table_row)) {
2236 $newrow = new html_table_row();
2238 foreach ($row as $cell) {
2239 if (!($cell instanceof html_table_cell)) {
2240 $cell = new html_table_cell($cell);
2242 $newrow->cells[] = $cell;
2244 $row = $newrow;
2247 if (isset($table->rowclasses[$key])) {
2248 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
2251 if ($key == $lastrowkey) {
2252 $row->attributes['class'] .= ' lastrow';
2255 // Explicitly assigned properties should override those defined in the attributes.
2256 $row->attributes['class'] = trim($row->attributes['class']);
2257 $trattributes = array_merge($row->attributes, array(
2258 'id' => $row->id,
2259 'style' => $row->style,
2261 $output .= html_writer::start_tag('tr', $trattributes) . "\n";
2262 $keys2 = array_keys($row->cells);
2263 $lastkey = end($keys2);
2265 $gotlastkey = false; //flag for sanity checking
2266 foreach ($row->cells as $key => $cell) {
2267 if ($gotlastkey) {
2268 //This should never happen. Why do we have a cell after the last cell?
2269 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
2272 if (!($cell instanceof html_table_cell)) {
2273 $mycell = new html_table_cell();
2274 $mycell->text = $cell;
2275 $cell = $mycell;
2278 if (($cell->header === true) && empty($cell->scope)) {
2279 $cell->scope = 'row';
2282 if (isset($table->colclasses[$key])) {
2283 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
2286 $cell->attributes['class'] .= ' cell c' . $key;
2287 if ($key == $lastkey) {
2288 $cell->attributes['class'] .= ' lastcol';
2289 $gotlastkey = true;
2291 $tdstyle = '';
2292 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
2293 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
2294 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
2295 $cell->attributes['class'] = trim($cell->attributes['class']);
2296 $tdattributes = array_merge($cell->attributes, array(
2297 'style' => $tdstyle . $cell->style,
2298 'colspan' => $cell->colspan,
2299 'rowspan' => $cell->rowspan,
2300 'id' => $cell->id,
2301 'abbr' => $cell->abbr,
2302 'scope' => $cell->scope,
2304 $tagtype = 'td';
2305 if ($cell->header === true) {
2306 $tagtype = 'th';
2308 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
2311 $output .= html_writer::end_tag('tr') . "\n";
2313 $output .= html_writer::end_tag('tbody') . "\n";
2315 $output .= html_writer::end_tag('table') . "\n";
2317 return $output;
2321 * Renders form element label
2323 * By default, the label is suffixed with a label separator defined in the
2324 * current language pack (colon by default in the English lang pack).
2325 * Adding the colon can be explicitly disabled if needed. Label separators
2326 * are put outside the label tag itself so they are not read by
2327 * screenreaders (accessibility).
2329 * Parameter $for explicitly associates the label with a form control. When
2330 * set, the value of this attribute must be the same as the value of
2331 * the id attribute of the form control in the same document. When null,
2332 * the label being defined is associated with the control inside the label
2333 * element.
2335 * @param string $text content of the label tag
2336 * @param string|null $for id of the element this label is associated with, null for no association
2337 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
2338 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
2339 * @return string HTML of the label element
2341 public static function label($text, $for, $colonize = true, array $attributes=array()) {
2342 if (!is_null($for)) {
2343 $attributes = array_merge($attributes, array('for' => $for));
2345 $text = trim($text);
2346 $label = self::tag('label', $text, $attributes);
2348 // TODO MDL-12192 $colonize disabled for now yet
2349 // if (!empty($text) and $colonize) {
2350 // // the $text may end with the colon already, though it is bad string definition style
2351 // $colon = get_string('labelsep', 'langconfig');
2352 // if (!empty($colon)) {
2353 // $trimmed = trim($colon);
2354 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
2355 // //debugging('The label text should not end with colon or other label separator,
2356 // // please fix the string definition.', DEBUG_DEVELOPER);
2357 // } else {
2358 // $label .= $colon;
2359 // }
2360 // }
2361 // }
2363 return $label;
2367 * Combines a class parameter with other attributes. Aids in code reduction
2368 * because the class parameter is very frequently used.
2370 * If the class attribute is specified both in the attributes and in the
2371 * class parameter, the two values are combined with a space between.
2373 * @param string $class Optional CSS class (or classes as space-separated list)
2374 * @param array $attributes Optional other attributes as array
2375 * @return array Attributes (or null if still none)
2377 private static function add_class($class = '', array $attributes = null) {
2378 if ($class !== '') {
2379 $classattribute = array('class' => $class);
2380 if ($attributes) {
2381 if (array_key_exists('class', $attributes)) {
2382 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
2383 } else {
2384 $attributes = $classattribute + $attributes;
2386 } else {
2387 $attributes = $classattribute;
2390 return $attributes;
2394 * Creates a <div> tag. (Shortcut function.)
2396 * @param string $content HTML content of tag
2397 * @param string $class Optional CSS class (or classes as space-separated list)
2398 * @param array $attributes Optional other attributes as array
2399 * @return string HTML code for div
2401 public static function div($content, $class = '', array $attributes = null) {
2402 return self::tag('div', $content, self::add_class($class, $attributes));
2406 * Starts a <div> tag. (Shortcut function.)
2408 * @param string $class Optional CSS class (or classes as space-separated list)
2409 * @param array $attributes Optional other attributes as array
2410 * @return string HTML code for open div tag
2412 public static function start_div($class = '', array $attributes = null) {
2413 return self::start_tag('div', self::add_class($class, $attributes));
2417 * Ends a <div> tag. (Shortcut function.)
2419 * @return string HTML code for close div tag
2421 public static function end_div() {
2422 return self::end_tag('div');
2426 * Creates a <span> tag. (Shortcut function.)
2428 * @param string $content HTML content of tag
2429 * @param string $class Optional CSS class (or classes as space-separated list)
2430 * @param array $attributes Optional other attributes as array
2431 * @return string HTML code for span
2433 public static function span($content, $class = '', array $attributes = null) {
2434 return self::tag('span', $content, self::add_class($class, $attributes));
2438 * Starts a <span> tag. (Shortcut function.)
2440 * @param string $class Optional CSS class (or classes as space-separated list)
2441 * @param array $attributes Optional other attributes as array
2442 * @return string HTML code for open span tag
2444 public static function start_span($class = '', array $attributes = null) {
2445 return self::start_tag('span', self::add_class($class, $attributes));
2449 * Ends a <span> tag. (Shortcut function.)
2451 * @return string HTML code for close span tag
2453 public static function end_span() {
2454 return self::end_tag('span');
2459 * Simple javascript output class
2461 * @copyright 2010 Petr Skoda
2462 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2463 * @since Moodle 2.0
2464 * @package core
2465 * @category output
2467 class js_writer {
2470 * Returns javascript code calling the function
2472 * @param string $function function name, can be complex like Y.Event.purgeElement
2473 * @param array $arguments parameters
2474 * @param int $delay execution delay in seconds
2475 * @return string JS code fragment
2477 public static function function_call($function, array $arguments = null, $delay=0) {
2478 if ($arguments) {
2479 $arguments = array_map('json_encode', convert_to_array($arguments));
2480 $arguments = implode(', ', $arguments);
2481 } else {
2482 $arguments = '';
2484 $js = "$function($arguments);";
2486 if ($delay) {
2487 $delay = $delay * 1000; // in miliseconds
2488 $js = "setTimeout(function() { $js }, $delay);";
2490 return $js . "\n";
2494 * Special function which adds Y as first argument of function call.
2496 * @param string $function The function to call
2497 * @param array $extraarguments Any arguments to pass to it
2498 * @return string Some JS code
2500 public static function function_call_with_Y($function, array $extraarguments = null) {
2501 if ($extraarguments) {
2502 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
2503 $arguments = 'Y, ' . implode(', ', $extraarguments);
2504 } else {
2505 $arguments = 'Y';
2507 return "$function($arguments);\n";
2511 * Returns JavaScript code to initialise a new object
2513 * @param string $var If it is null then no var is assigned the new object.
2514 * @param string $class The class to initialise an object for.
2515 * @param array $arguments An array of args to pass to the init method.
2516 * @param array $requirements Any modules required for this class.
2517 * @param int $delay The delay before initialisation. 0 = no delay.
2518 * @return string Some JS code
2520 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
2521 if (is_array($arguments)) {
2522 $arguments = array_map('json_encode', convert_to_array($arguments));
2523 $arguments = implode(', ', $arguments);
2526 if ($var === null) {
2527 $js = "new $class(Y, $arguments);";
2528 } else if (strpos($var, '.')!==false) {
2529 $js = "$var = new $class(Y, $arguments);";
2530 } else {
2531 $js = "var $var = new $class(Y, $arguments);";
2534 if ($delay) {
2535 $delay = $delay * 1000; // in miliseconds
2536 $js = "setTimeout(function() { $js }, $delay);";
2539 if (count($requirements) > 0) {
2540 $requirements = implode("', '", $requirements);
2541 $js = "Y.use('$requirements', function(Y){ $js });";
2543 return $js."\n";
2547 * Returns code setting value to variable
2549 * @param string $name
2550 * @param mixed $value json serialised value
2551 * @param bool $usevar add var definition, ignored for nested properties
2552 * @return string JS code fragment
2554 public static function set_variable($name, $value, $usevar = true) {
2555 $output = '';
2557 if ($usevar) {
2558 if (strpos($name, '.')) {
2559 $output .= '';
2560 } else {
2561 $output .= 'var ';
2565 $output .= "$name = ".json_encode($value).";";
2567 return $output;
2571 * Writes event handler attaching code
2573 * @param array|string $selector standard YUI selector for elements, may be
2574 * array or string, element id is in the form "#idvalue"
2575 * @param string $event A valid DOM event (click, mousedown, change etc.)
2576 * @param string $function The name of the function to call
2577 * @param array $arguments An optional array of argument parameters to pass to the function
2578 * @return string JS code fragment
2580 public static function event_handler($selector, $event, $function, array $arguments = null) {
2581 $selector = json_encode($selector);
2582 $output = "Y.on('$event', $function, $selector, null";
2583 if (!empty($arguments)) {
2584 $output .= ', ' . json_encode($arguments);
2586 return $output . ");\n";
2591 * Holds all the information required to render a <table> by {@link core_renderer::table()}
2593 * Example of usage:
2594 * $t = new html_table();
2595 * ... // set various properties of the object $t as described below
2596 * echo html_writer::table($t);
2598 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
2599 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2600 * @since Moodle 2.0
2601 * @package core
2602 * @category output
2604 class html_table {
2607 * @var string Value to use for the id attribute of the table
2609 public $id = null;
2612 * @var array Attributes of HTML attributes for the <table> element
2614 public $attributes = array();
2617 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
2618 * For more control over the rendering of the headers, an array of html_table_cell objects
2619 * can be passed instead of an array of strings.
2621 * Example of usage:
2622 * $t->head = array('Student', 'Grade');
2624 public $head;
2627 * @var array An array that can be used to make a heading span multiple columns.
2628 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
2629 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
2631 * Example of usage:
2632 * $t->headspan = array(2,1);
2634 public $headspan;
2637 * @var array An array of column alignments.
2638 * The value is used as CSS 'text-align' property. Therefore, possible
2639 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
2640 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
2642 * Examples of usage:
2643 * $t->align = array(null, 'right');
2644 * or
2645 * $t->align[1] = 'right';
2647 public $align;
2650 * @var array The value is used as CSS 'size' property.
2652 * Examples of usage:
2653 * $t->size = array('50%', '50%');
2654 * or
2655 * $t->size[1] = '120px';
2657 public $size;
2660 * @var array An array of wrapping information.
2661 * The only possible value is 'nowrap' that sets the
2662 * CSS property 'white-space' to the value 'nowrap' in the given column.
2664 * Example of usage:
2665 * $t->wrap = array(null, 'nowrap');
2667 public $wrap;
2670 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2671 * $head specified, the string 'hr' (for horizontal ruler) can be used
2672 * instead of an array of cells data resulting in a divider rendered.
2674 * Example of usage with array of arrays:
2675 * $row1 = array('Harry Potter', '76 %');
2676 * $row2 = array('Hermione Granger', '100 %');
2677 * $t->data = array($row1, $row2);
2679 * Example with array of html_table_row objects: (used for more fine-grained control)
2680 * $cell1 = new html_table_cell();
2681 * $cell1->text = 'Harry Potter';
2682 * $cell1->colspan = 2;
2683 * $row1 = new html_table_row();
2684 * $row1->cells[] = $cell1;
2685 * $cell2 = new html_table_cell();
2686 * $cell2->text = 'Hermione Granger';
2687 * $cell3 = new html_table_cell();
2688 * $cell3->text = '100 %';
2689 * $row2 = new html_table_row();
2690 * $row2->cells = array($cell2, $cell3);
2691 * $t->data = array($row1, $row2);
2693 public $data = [];
2696 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2697 * @var string Width of the table, percentage of the page preferred.
2699 public $width = null;
2702 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2703 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2705 public $tablealign = null;
2708 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2709 * @var int Padding on each cell, in pixels
2711 public $cellpadding = null;
2714 * @var int Spacing between cells, in pixels
2715 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2717 public $cellspacing = null;
2720 * @var array Array of classes to add to particular rows, space-separated string.
2721 * Class 'lastrow' is added automatically for the last row in the table.
2723 * Example of usage:
2724 * $t->rowclasses[9] = 'tenth'
2726 public $rowclasses;
2729 * @var array An array of classes to add to every cell in a particular column,
2730 * space-separated string. Class 'cell' is added automatically by the renderer.
2731 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2732 * respectively. Class 'lastcol' is added automatically for all last cells
2733 * in a row.
2735 * Example of usage:
2736 * $t->colclasses = array(null, 'grade');
2738 public $colclasses;
2741 * @var string Description of the contents for screen readers.
2743 public $summary;
2746 * @var string Caption for the table, typically a title.
2748 * Example of usage:
2749 * $t->caption = "TV Guide";
2751 public $caption;
2754 * @var bool Whether to hide the table's caption from sighted users.
2756 * Example of usage:
2757 * $t->caption = "TV Guide";
2758 * $t->captionhide = true;
2760 public $captionhide = false;
2763 * Constructor
2765 public function __construct() {
2766 $this->attributes['class'] = '';
2771 * Component representing a table row.
2773 * @copyright 2009 Nicolas Connault
2774 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2775 * @since Moodle 2.0
2776 * @package core
2777 * @category output
2779 class html_table_row {
2782 * @var string Value to use for the id attribute of the row.
2784 public $id = null;
2787 * @var array Array of html_table_cell objects
2789 public $cells = array();
2792 * @var string Value to use for the style attribute of the table row
2794 public $style = null;
2797 * @var array Attributes of additional HTML attributes for the <tr> element
2799 public $attributes = array();
2802 * Constructor
2803 * @param array $cells
2805 public function __construct(array $cells=null) {
2806 $this->attributes['class'] = '';
2807 $cells = (array)$cells;
2808 foreach ($cells as $cell) {
2809 if ($cell instanceof html_table_cell) {
2810 $this->cells[] = $cell;
2811 } else {
2812 $this->cells[] = new html_table_cell($cell);
2819 * Component representing a table cell.
2821 * @copyright 2009 Nicolas Connault
2822 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2823 * @since Moodle 2.0
2824 * @package core
2825 * @category output
2827 class html_table_cell {
2830 * @var string Value to use for the id attribute of the cell.
2832 public $id = null;
2835 * @var string The contents of the cell.
2837 public $text;
2840 * @var string Abbreviated version of the contents of the cell.
2842 public $abbr = null;
2845 * @var int Number of columns this cell should span.
2847 public $colspan = null;
2850 * @var int Number of rows this cell should span.
2852 public $rowspan = null;
2855 * @var string Defines a way to associate header cells and data cells in a table.
2857 public $scope = null;
2860 * @var bool Whether or not this cell is a header cell.
2862 public $header = null;
2865 * @var string Value to use for the style attribute of the table cell
2867 public $style = null;
2870 * @var array Attributes of additional HTML attributes for the <td> element
2872 public $attributes = array();
2875 * Constructs a table cell
2877 * @param string $text
2879 public function __construct($text = null) {
2880 $this->text = $text;
2881 $this->attributes['class'] = '';
2886 * Component representing a paging bar.
2888 * @copyright 2009 Nicolas Connault
2889 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2890 * @since Moodle 2.0
2891 * @package core
2892 * @category output
2894 class paging_bar implements renderable, templatable {
2897 * @var int The maximum number of pagelinks to display.
2899 public $maxdisplay = 18;
2902 * @var int The total number of entries to be pages through..
2904 public $totalcount;
2907 * @var int The page you are currently viewing.
2909 public $page;
2912 * @var int The number of entries that should be shown per page.
2914 public $perpage;
2917 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2918 * an equals sign and the page number.
2919 * If this is a moodle_url object then the pagevar param will be replaced by
2920 * the page no, for each page.
2922 public $baseurl;
2925 * @var string This is the variable name that you use for the pagenumber in your
2926 * code (ie. 'tablepage', 'blogpage', etc)
2928 public $pagevar;
2931 * @var string A HTML link representing the "previous" page.
2933 public $previouslink = null;
2936 * @var string A HTML link representing the "next" page.
2938 public $nextlink = null;
2941 * @var string A HTML link representing the first page.
2943 public $firstlink = null;
2946 * @var string A HTML link representing the last page.
2948 public $lastlink = null;
2951 * @var array An array of strings. One of them is just a string: the current page
2953 public $pagelinks = array();
2956 * Constructor paging_bar with only the required params.
2958 * @param int $totalcount The total number of entries available to be paged through
2959 * @param int $page The page you are currently viewing
2960 * @param int $perpage The number of entries that should be shown per page
2961 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2962 * @param string $pagevar name of page parameter that holds the page number
2964 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2965 $this->totalcount = $totalcount;
2966 $this->page = $page;
2967 $this->perpage = $perpage;
2968 $this->baseurl = $baseurl;
2969 $this->pagevar = $pagevar;
2973 * Prepares the paging bar for output.
2975 * This method validates the arguments set up for the paging bar and then
2976 * produces fragments of HTML to assist display later on.
2978 * @param renderer_base $output
2979 * @param moodle_page $page
2980 * @param string $target
2981 * @throws coding_exception
2983 public function prepare(renderer_base $output, moodle_page $page, $target) {
2984 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2985 throw new coding_exception('paging_bar requires a totalcount value.');
2987 if (!isset($this->page) || is_null($this->page)) {
2988 throw new coding_exception('paging_bar requires a page value.');
2990 if (empty($this->perpage)) {
2991 throw new coding_exception('paging_bar requires a perpage value.');
2993 if (empty($this->baseurl)) {
2994 throw new coding_exception('paging_bar requires a baseurl value.');
2997 if ($this->totalcount > $this->perpage) {
2998 $pagenum = $this->page - 1;
3000 if ($this->page > 0) {
3001 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
3004 if ($this->perpage > 0) {
3005 $lastpage = ceil($this->totalcount / $this->perpage);
3006 } else {
3007 $lastpage = 1;
3010 if ($this->page > round(($this->maxdisplay/3)*2)) {
3011 $currpage = $this->page - round($this->maxdisplay/3);
3013 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
3014 } else {
3015 $currpage = 0;
3018 $displaycount = $displaypage = 0;
3020 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3021 $displaypage = $currpage + 1;
3023 if ($this->page == $currpage) {
3024 $this->pagelinks[] = html_writer::span($displaypage, 'current-page');
3025 } else {
3026 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
3027 $this->pagelinks[] = $pagelink;
3030 $displaycount++;
3031 $currpage++;
3034 if ($currpage < $lastpage) {
3035 $lastpageactual = $lastpage - 1;
3036 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
3039 $pagenum = $this->page + 1;
3041 if ($pagenum != $lastpage) {
3042 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
3048 * Export for template.
3050 * @param renderer_base $output The renderer.
3051 * @return stdClass
3053 public function export_for_template(renderer_base $output) {
3054 $data = new stdClass();
3055 $data->previous = null;
3056 $data->next = null;
3057 $data->first = null;
3058 $data->last = null;
3059 $data->label = get_string('page');
3060 $data->pages = [];
3061 $data->haspages = $this->totalcount > $this->perpage;
3063 if (!$data->haspages) {
3064 return $data;
3067 if ($this->page > 0) {
3068 $data->previous = [
3069 'page' => $this->page - 1,
3070 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page - 1]))->out(false)
3074 $currpage = 0;
3075 if ($this->page > round(($this->maxdisplay / 3) * 2)) {
3076 $currpage = $this->page - round($this->maxdisplay / 3);
3077 $data->first = [
3078 'page' => 1,
3079 'url' => (new moodle_url($this->baseurl, [$this->pagevar => 0]))->out(false)
3083 $lastpage = 1;
3084 if ($this->perpage > 0) {
3085 $lastpage = ceil($this->totalcount / $this->perpage);
3088 $displaycount = 0;
3089 $displaypage = 0;
3090 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3091 $displaypage = $currpage + 1;
3093 $iscurrent = $this->page == $currpage;
3094 $link = new moodle_url($this->baseurl, [$this->pagevar => $currpage]);
3096 $data->pages[] = [
3097 'page' => $displaypage,
3098 'active' => $iscurrent,
3099 'url' => $iscurrent ? null : $link->out(false)
3102 $displaycount++;
3103 $currpage++;
3106 if ($currpage < $lastpage) {
3107 $data->last = [
3108 'page' => $lastpage,
3109 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $lastpage - 1]))->out(false)
3113 if ($this->page + 1 != $lastpage) {
3114 $data->next = [
3115 'page' => $this->page + 1,
3116 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page + 1]))->out(false)
3120 return $data;
3125 * Component representing initials bar.
3127 * @copyright 2017 Ilya Tregubov
3128 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3129 * @since Moodle 3.3
3130 * @package core
3131 * @category output
3133 class initials_bar implements renderable, templatable {
3136 * @var string Currently selected letter.
3138 public $current;
3141 * @var string Class name to add to this initial bar.
3143 public $class;
3146 * @var string The name to put in front of this initial bar.
3148 public $title;
3151 * @var string URL parameter name for this initial.
3153 public $urlvar;
3156 * @var string URL object.
3158 public $url;
3161 * @var array An array of letters in the alphabet.
3163 public $alpha;
3166 * Constructor initials_bar with only the required params.
3168 * @param string $current the currently selected letter.
3169 * @param string $class class name to add to this initial bar.
3170 * @param string $title the name to put in front of this initial bar.
3171 * @param string $urlvar URL parameter name for this initial.
3172 * @param string $url URL object.
3173 * @param array $alpha of letters in the alphabet.
3175 public function __construct($current, $class, $title, $urlvar, $url, $alpha = null) {
3176 $this->current = $current;
3177 $this->class = $class;
3178 $this->title = $title;
3179 $this->urlvar = $urlvar;
3180 $this->url = $url;
3181 $this->alpha = $alpha;
3185 * Export for template.
3187 * @param renderer_base $output The renderer.
3188 * @return stdClass
3190 public function export_for_template(renderer_base $output) {
3191 $data = new stdClass();
3193 if ($this->alpha == null) {
3194 $this->alpha = explode(',', get_string('alphabet', 'langconfig'));
3197 if ($this->current == 'all') {
3198 $this->current = '';
3201 // We want to find a letter grouping size which suits the language so
3202 // find the largest group size which is less than 15 chars.
3203 // The choice of 15 chars is the largest number of chars that reasonably
3204 // fits on the smallest supported screen size. By always using a max number
3205 // of groups which is a factor of 2, we always get nice wrapping, and the
3206 // last row is always the shortest.
3207 $groupsize = count($this->alpha);
3208 $groups = 1;
3209 while ($groupsize > 15) {
3210 $groups *= 2;
3211 $groupsize = ceil(count($this->alpha) / $groups);
3214 $groupsizelimit = 0;
3215 $groupnumber = 0;
3216 foreach ($this->alpha as $letter) {
3217 if ($groupsizelimit++ > 0 && $groupsizelimit % $groupsize == 1) {
3218 $groupnumber++;
3220 $groupletter = new stdClass();
3221 $groupletter->name = $letter;
3222 $groupletter->url = $this->url->out(false, array($this->urlvar => $letter));
3223 if ($letter == $this->current) {
3224 $groupletter->selected = $this->current;
3226 $data->group[$groupnumber]->letter[] = $groupletter;
3229 $data->class = $this->class;
3230 $data->title = $this->title;
3231 $data->url = $this->url->out(false, array($this->urlvar => ''));
3232 $data->current = $this->current;
3233 $data->all = get_string('all');
3235 return $data;
3240 * This class represents how a block appears on a page.
3242 * During output, each block instance is asked to return a block_contents object,
3243 * those are then passed to the $OUTPUT->block function for display.
3245 * contents should probably be generated using a moodle_block_..._renderer.
3247 * Other block-like things that need to appear on the page, for example the
3248 * add new block UI, are also represented as block_contents objects.
3250 * @copyright 2009 Tim Hunt
3251 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3252 * @since Moodle 2.0
3253 * @package core
3254 * @category output
3256 class block_contents {
3258 /** Used when the block cannot be collapsed **/
3259 const NOT_HIDEABLE = 0;
3261 /** Used when the block can be collapsed but currently is not **/
3262 const VISIBLE = 1;
3264 /** Used when the block has been collapsed **/
3265 const HIDDEN = 2;
3268 * @var int Used to set $skipid.
3270 protected static $idcounter = 1;
3273 * @var int All the blocks (or things that look like blocks) printed on
3274 * a page are given a unique number that can be used to construct id="" attributes.
3275 * This is set automatically be the {@link prepare()} method.
3276 * Do not try to set it manually.
3278 public $skipid;
3281 * @var int If this is the contents of a real block, this should be set
3282 * to the block_instance.id. Otherwise this should be set to 0.
3284 public $blockinstanceid = 0;
3287 * @var int If this is a real block instance, and there is a corresponding
3288 * block_position.id for the block on this page, this should be set to that id.
3289 * Otherwise it should be 0.
3291 public $blockpositionid = 0;
3294 * @var array An array of attribute => value pairs that are put on the outer div of this
3295 * block. {@link $id} and {@link $classes} attributes should be set separately.
3297 public $attributes;
3300 * @var string The title of this block. If this came from user input, it should already
3301 * have had format_string() processing done on it. This will be output inside
3302 * <h2> tags. Please do not cause invalid XHTML.
3304 public $title = '';
3307 * @var string The label to use when the block does not, or will not have a visible title.
3308 * You should never set this as well as title... it will just be ignored.
3310 public $arialabel = '';
3313 * @var string HTML for the content
3315 public $content = '';
3318 * @var array An alternative to $content, it you want a list of things with optional icons.
3320 public $footer = '';
3323 * @var string Any small print that should appear under the block to explain
3324 * to the teacher about the block, for example 'This is a sticky block that was
3325 * added in the system context.'
3327 public $annotation = '';
3330 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
3331 * the user can toggle whether this block is visible.
3333 public $collapsible = self::NOT_HIDEABLE;
3336 * Set this to true if the block is dockable.
3337 * @var bool
3339 public $dockable = false;
3342 * @var array A (possibly empty) array of editing controls. Each element of
3343 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
3344 * $icon is the icon name. Fed to $OUTPUT->image_url.
3346 public $controls = array();
3350 * Create new instance of block content
3351 * @param array $attributes
3353 public function __construct(array $attributes = null) {
3354 $this->skipid = self::$idcounter;
3355 self::$idcounter += 1;
3357 if ($attributes) {
3358 // standard block
3359 $this->attributes = $attributes;
3360 } else {
3361 // simple "fake" blocks used in some modules and "Add new block" block
3362 $this->attributes = array('class'=>'block');
3367 * Add html class to block
3369 * @param string $class
3371 public function add_class($class) {
3372 $this->attributes['class'] .= ' '.$class;
3378 * This class represents a target for where a block can go when it is being moved.
3380 * This needs to be rendered as a form with the given hidden from fields, and
3381 * clicking anywhere in the form should submit it. The form action should be
3382 * $PAGE->url.
3384 * @copyright 2009 Tim Hunt
3385 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3386 * @since Moodle 2.0
3387 * @package core
3388 * @category output
3390 class block_move_target {
3393 * @var moodle_url Move url
3395 public $url;
3398 * Constructor
3399 * @param moodle_url $url
3401 public function __construct(moodle_url $url) {
3402 $this->url = $url;
3407 * Custom menu item
3409 * This class is used to represent one item within a custom menu that may or may
3410 * not have children.
3412 * @copyright 2010 Sam Hemelryk
3413 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3414 * @since Moodle 2.0
3415 * @package core
3416 * @category output
3418 class custom_menu_item implements renderable, templatable {
3421 * @var string The text to show for the item
3423 protected $text;
3426 * @var moodle_url The link to give the icon if it has no children
3428 protected $url;
3431 * @var string A title to apply to the item. By default the text
3433 protected $title;
3436 * @var int A sort order for the item, not necessary if you order things in
3437 * the CFG var.
3439 protected $sort;
3442 * @var custom_menu_item A reference to the parent for this item or NULL if
3443 * it is a top level item
3445 protected $parent;
3448 * @var array A array in which to store children this item has.
3450 protected $children = array();
3453 * @var int A reference to the sort var of the last child that was added
3455 protected $lastsort = 0;
3458 * Constructs the new custom menu item
3460 * @param string $text
3461 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
3462 * @param string $title A title to apply to this item [Optional]
3463 * @param int $sort A sort or to use if we need to sort differently [Optional]
3464 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
3465 * belongs to, only if the child has a parent. [Optional]
3467 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
3468 $this->text = $text;
3469 $this->url = $url;
3470 $this->title = $title;
3471 $this->sort = (int)$sort;
3472 $this->parent = $parent;
3476 * Adds a custom menu item as a child of this node given its properties.
3478 * @param string $text
3479 * @param moodle_url $url
3480 * @param string $title
3481 * @param int $sort
3482 * @return custom_menu_item
3484 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
3485 $key = count($this->children);
3486 if (empty($sort)) {
3487 $sort = $this->lastsort + 1;
3489 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
3490 $this->lastsort = (int)$sort;
3491 return $this->children[$key];
3495 * Removes a custom menu item that is a child or descendant to the current menu.
3497 * Returns true if child was found and removed.
3499 * @param custom_menu_item $menuitem
3500 * @return bool
3502 public function remove_child(custom_menu_item $menuitem) {
3503 $removed = false;
3504 if (($key = array_search($menuitem, $this->children)) !== false) {
3505 unset($this->children[$key]);
3506 $this->children = array_values($this->children);
3507 $removed = true;
3508 } else {
3509 foreach ($this->children as $child) {
3510 if ($removed = $child->remove_child($menuitem)) {
3511 break;
3515 return $removed;
3519 * Returns the text for this item
3520 * @return string
3522 public function get_text() {
3523 return $this->text;
3527 * Returns the url for this item
3528 * @return moodle_url
3530 public function get_url() {
3531 return $this->url;
3535 * Returns the title for this item
3536 * @return string
3538 public function get_title() {
3539 return $this->title;
3543 * Sorts and returns the children for this item
3544 * @return array
3546 public function get_children() {
3547 $this->sort();
3548 return $this->children;
3552 * Gets the sort order for this child
3553 * @return int
3555 public function get_sort_order() {
3556 return $this->sort;
3560 * Gets the parent this child belong to
3561 * @return custom_menu_item
3563 public function get_parent() {
3564 return $this->parent;
3568 * Sorts the children this item has
3570 public function sort() {
3571 usort($this->children, array('custom_menu','sort_custom_menu_items'));
3575 * Returns true if this item has any children
3576 * @return bool
3578 public function has_children() {
3579 return (count($this->children) > 0);
3583 * Sets the text for the node
3584 * @param string $text
3586 public function set_text($text) {
3587 $this->text = (string)$text;
3591 * Sets the title for the node
3592 * @param string $title
3594 public function set_title($title) {
3595 $this->title = (string)$title;
3599 * Sets the url for the node
3600 * @param moodle_url $url
3602 public function set_url(moodle_url $url) {
3603 $this->url = $url;
3607 * Export this data so it can be used as the context for a mustache template.
3609 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
3610 * @return array
3612 public function export_for_template(renderer_base $output) {
3613 global $CFG;
3615 require_once($CFG->libdir . '/externallib.php');
3617 $syscontext = context_system::instance();
3619 $context = new stdClass();
3620 $context->text = external_format_string($this->text, $syscontext->id);
3621 $context->url = $this->url ? $this->url->out() : null;
3622 $context->title = external_format_string($this->title, $syscontext->id);
3623 $context->sort = $this->sort;
3624 $context->children = array();
3625 if (preg_match("/^#+$/", $this->text)) {
3626 $context->divider = true;
3628 $context->haschildren = !empty($this->children) && (count($this->children) > 0);
3629 foreach ($this->children as $child) {
3630 $child = $child->export_for_template($output);
3631 array_push($context->children, $child);
3634 return $context;
3639 * Custom menu class
3641 * This class is used to operate a custom menu that can be rendered for the page.
3642 * The custom menu is built using $CFG->custommenuitems and is a structured collection
3643 * of custom_menu_item nodes that can be rendered by the core renderer.
3645 * To configure the custom menu:
3646 * Settings: Administration > Appearance > Themes > Theme settings
3648 * @copyright 2010 Sam Hemelryk
3649 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3650 * @since Moodle 2.0
3651 * @package core
3652 * @category output
3654 class custom_menu extends custom_menu_item {
3657 * @var string The language we should render for, null disables multilang support.
3659 protected $currentlanguage = null;
3662 * Creates the custom menu
3664 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
3665 * @param string $currentlanguage the current language code, null disables multilang support
3667 public function __construct($definition = '', $currentlanguage = null) {
3668 $this->currentlanguage = $currentlanguage;
3669 parent::__construct('root'); // create virtual root element of the menu
3670 if (!empty($definition)) {
3671 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
3676 * Overrides the children of this custom menu. Useful when getting children
3677 * from $CFG->custommenuitems
3679 * @param array $children
3681 public function override_children(array $children) {
3682 $this->children = array();
3683 foreach ($children as $child) {
3684 if ($child instanceof custom_menu_item) {
3685 $this->children[] = $child;
3691 * Converts a string into a structured array of custom_menu_items which can
3692 * then be added to a custom menu.
3694 * Structure:
3695 * text|url|title|langs
3696 * The number of hyphens at the start determines the depth of the item. The
3697 * languages are optional, comma separated list of languages the line is for.
3699 * Example structure:
3700 * First level first item|http://www.moodle.com/
3701 * -Second level first item|http://www.moodle.com/partners/
3702 * -Second level second item|http://www.moodle.com/hq/
3703 * --Third level first item|http://www.moodle.com/jobs/
3704 * -Second level third item|http://www.moodle.com/development/
3705 * First level second item|http://www.moodle.com/feedback/
3706 * First level third item
3707 * English only|http://moodle.com|English only item|en
3708 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
3711 * @static
3712 * @param string $text the menu items definition
3713 * @param string $language the language code, null disables multilang support
3714 * @return array
3716 public static function convert_text_to_menu_nodes($text, $language = null) {
3717 $root = new custom_menu();
3718 $lastitem = $root;
3719 $lastdepth = 0;
3720 $hiddenitems = array();
3721 $lines = explode("\n", $text);
3722 foreach ($lines as $linenumber => $line) {
3723 $line = trim($line);
3724 if (strlen($line) == 0) {
3725 continue;
3727 // Parse item settings.
3728 $itemtext = null;
3729 $itemurl = null;
3730 $itemtitle = null;
3731 $itemvisible = true;
3732 $settings = explode('|', $line);
3733 foreach ($settings as $i => $setting) {
3734 $setting = trim($setting);
3735 if (!empty($setting)) {
3736 switch ($i) {
3737 case 0:
3738 $itemtext = ltrim($setting, '-');
3739 $itemtitle = $itemtext;
3740 break;
3741 case 1:
3742 try {
3743 $itemurl = new moodle_url($setting);
3744 } catch (moodle_exception $exception) {
3745 // We're not actually worried about this, we don't want to mess up the display
3746 // just for a wrongly entered URL.
3747 $itemurl = null;
3749 break;
3750 case 2:
3751 $itemtitle = $setting;
3752 break;
3753 case 3:
3754 if (!empty($language)) {
3755 $itemlanguages = array_map('trim', explode(',', $setting));
3756 $itemvisible &= in_array($language, $itemlanguages);
3758 break;
3762 // Get depth of new item.
3763 preg_match('/^(\-*)/', $line, $match);
3764 $itemdepth = strlen($match[1]) + 1;
3765 // Find parent item for new item.
3766 while (($lastdepth - $itemdepth) >= 0) {
3767 $lastitem = $lastitem->get_parent();
3768 $lastdepth--;
3770 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1);
3771 $lastdepth++;
3772 if (!$itemvisible) {
3773 $hiddenitems[] = $lastitem;
3776 foreach ($hiddenitems as $item) {
3777 $item->parent->remove_child($item);
3779 return $root->get_children();
3783 * Sorts two custom menu items
3785 * This function is designed to be used with the usort method
3786 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
3788 * @static
3789 * @param custom_menu_item $itema
3790 * @param custom_menu_item $itemb
3791 * @return int
3793 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
3794 $itema = $itema->get_sort_order();
3795 $itemb = $itemb->get_sort_order();
3796 if ($itema == $itemb) {
3797 return 0;
3799 return ($itema > $itemb) ? +1 : -1;
3804 * Stores one tab
3806 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3807 * @package core
3809 class tabobject implements renderable, templatable {
3810 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
3811 var $id;
3812 /** @var moodle_url|string link */
3813 var $link;
3814 /** @var string text on the tab */
3815 var $text;
3816 /** @var string title under the link, by defaul equals to text */
3817 var $title;
3818 /** @var bool whether to display a link under the tab name when it's selected */
3819 var $linkedwhenselected = false;
3820 /** @var bool whether the tab is inactive */
3821 var $inactive = false;
3822 /** @var bool indicates that this tab's child is selected */
3823 var $activated = false;
3824 /** @var bool indicates that this tab is selected */
3825 var $selected = false;
3826 /** @var array stores children tabobjects */
3827 var $subtree = array();
3828 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
3829 var $level = 1;
3832 * Constructor
3834 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
3835 * @param string|moodle_url $link
3836 * @param string $text text on the tab
3837 * @param string $title title under the link, by defaul equals to text
3838 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
3840 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
3841 $this->id = $id;
3842 $this->link = $link;
3843 $this->text = $text;
3844 $this->title = $title ? $title : $text;
3845 $this->linkedwhenselected = $linkedwhenselected;
3849 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
3851 * @param string $selected the id of the selected tab (whatever row it's on),
3852 * if null marks all tabs as unselected
3853 * @return bool whether this tab is selected or contains selected tab in its subtree
3855 protected function set_selected($selected) {
3856 if ((string)$selected === (string)$this->id) {
3857 $this->selected = true;
3858 // This tab is selected. No need to travel through subtree.
3859 return true;
3861 foreach ($this->subtree as $subitem) {
3862 if ($subitem->set_selected($selected)) {
3863 // This tab has child that is selected. Mark it as activated. No need to check other children.
3864 $this->activated = true;
3865 return true;
3868 return false;
3872 * Travels through tree and finds a tab with specified id
3874 * @param string $id
3875 * @return tabtree|null
3877 public function find($id) {
3878 if ((string)$this->id === (string)$id) {
3879 return $this;
3881 foreach ($this->subtree as $tab) {
3882 if ($obj = $tab->find($id)) {
3883 return $obj;
3886 return null;
3890 * Allows to mark each tab's level in the tree before rendering.
3892 * @param int $level
3894 protected function set_level($level) {
3895 $this->level = $level;
3896 foreach ($this->subtree as $tab) {
3897 $tab->set_level($level + 1);
3902 * Export for template.
3904 * @param renderer_base $output Renderer.
3905 * @return object
3907 public function export_for_template(renderer_base $output) {
3908 if ($this->inactive || ($this->selected && !$this->linkedwhenselected) || $this->activated) {
3909 $link = null;
3910 } else {
3911 $link = $this->link;
3913 $active = $this->activated || $this->selected;
3915 return (object) [
3916 'id' => $this->id,
3917 'link' => is_object($link) ? $link->out(false) : $link,
3918 'text' => $this->text,
3919 'title' => $this->title,
3920 'inactive' => !$active && $this->inactive,
3921 'active' => $active,
3922 'level' => $this->level,
3929 * Renderable for the main page header.
3931 * @package core
3932 * @category output
3933 * @since 2.9
3934 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
3935 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3937 class context_header implements renderable {
3940 * @var string $heading Main heading.
3942 public $heading;
3944 * @var int $headinglevel Main heading 'h' tag level.
3946 public $headinglevel;
3948 * @var string|null $imagedata HTML code for the picture in the page header.
3950 public $imagedata;
3952 * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
3953 * array elements - title => alternate text for the image, or if no image is available the button text.
3954 * url => Link for the button to head to. Should be a moodle_url.
3955 * image => location to the image, or name of the image in /pix/t/{image name}.
3956 * linkattributes => additional attributes for the <a href> element.
3957 * page => page object. Don't include if the image is an external image.
3959 public $additionalbuttons;
3962 * Constructor.
3964 * @param string $heading Main heading data.
3965 * @param int $headinglevel Main heading 'h' tag level.
3966 * @param string|null $imagedata HTML code for the picture in the page header.
3967 * @param string $additionalbuttons Buttons for the header e.g. Messaging button for the user header.
3969 public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null) {
3971 $this->heading = $heading;
3972 $this->headinglevel = $headinglevel;
3973 $this->imagedata = $imagedata;
3974 $this->additionalbuttons = $additionalbuttons;
3975 // If we have buttons then format them.
3976 if (isset($this->additionalbuttons)) {
3977 $this->format_button_images();
3982 * Adds an array element for a formatted image.
3984 protected function format_button_images() {
3986 foreach ($this->additionalbuttons as $buttontype => $button) {
3987 $page = $button['page'];
3988 // If no image is provided then just use the title.
3989 if (!isset($button['image'])) {
3990 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['title'];
3991 } else {
3992 // Check to see if this is an internal Moodle icon.
3993 $internalimage = $page->theme->resolve_image_location('t/' . $button['image'], 'moodle');
3994 if ($internalimage) {
3995 $this->additionalbuttons[$buttontype]['formattedimage'] = 't/' . $button['image'];
3996 } else {
3997 // Treat as an external image.
3998 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['image'];
4002 if (isset($button['linkattributes']['class'])) {
4003 $class = $button['linkattributes']['class'] . ' btn';
4004 } else {
4005 $class = 'btn';
4007 // Add the bootstrap 'btn' class for formatting.
4008 $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
4009 array('class' => $class));
4015 * Stores tabs list
4017 * Example how to print a single line tabs:
4018 * $rows = array(
4019 * new tabobject(...),
4020 * new tabobject(...)
4021 * );
4022 * echo $OUTPUT->tabtree($rows, $selectedid);
4024 * Multiple row tabs may not look good on some devices but if you want to use them
4025 * you can specify ->subtree for the active tabobject.
4027 * @copyright 2013 Marina Glancy
4028 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4029 * @since Moodle 2.5
4030 * @package core
4031 * @category output
4033 class tabtree extends tabobject {
4035 * Constuctor
4037 * It is highly recommended to call constructor when list of tabs is already
4038 * populated, this way you ensure that selected and inactive tabs are located
4039 * and attribute level is set correctly.
4041 * @param array $tabs array of tabs, each of them may have it's own ->subtree
4042 * @param string|null $selected which tab to mark as selected, all parent tabs will
4043 * automatically be marked as activated
4044 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4045 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
4047 public function __construct($tabs, $selected = null, $inactive = null) {
4048 $this->subtree = $tabs;
4049 if ($selected !== null) {
4050 $this->set_selected($selected);
4052 if ($inactive !== null) {
4053 if (is_array($inactive)) {
4054 foreach ($inactive as $id) {
4055 if ($tab = $this->find($id)) {
4056 $tab->inactive = true;
4059 } else if ($tab = $this->find($inactive)) {
4060 $tab->inactive = true;
4063 $this->set_level(0);
4067 * Export for template.
4069 * @param renderer_base $output Renderer.
4070 * @return object
4072 public function export_for_template(renderer_base $output) {
4073 $tabs = [];
4074 $secondrow = false;
4076 foreach ($this->subtree as $tab) {
4077 $tabs[] = $tab->export_for_template($output);
4078 if (!empty($tab->subtree) && ($tab->level == 0 || $tab->selected || $tab->activated)) {
4079 $secondrow = new tabtree($tab->subtree);
4083 return (object) [
4084 'tabs' => $tabs,
4085 'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false
4091 * An action menu.
4093 * This action menu component takes a series of primary and secondary actions.
4094 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
4095 * down menu.
4097 * @package core
4098 * @category output
4099 * @copyright 2013 Sam Hemelryk
4100 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4102 class action_menu implements renderable, templatable {
4105 * Top right alignment.
4107 const TL = 1;
4110 * Top right alignment.
4112 const TR = 2;
4115 * Top right alignment.
4117 const BL = 3;
4120 * Top right alignment.
4122 const BR = 4;
4125 * The instance number. This is unique to this instance of the action menu.
4126 * @var int
4128 protected $instance = 0;
4131 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
4132 * @var array
4134 protected $primaryactions = array();
4137 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
4138 * @var array
4140 protected $secondaryactions = array();
4143 * An array of attributes added to the container of the action menu.
4144 * Initialised with defaults during construction.
4145 * @var array
4147 public $attributes = array();
4149 * An array of attributes added to the container of the primary actions.
4150 * Initialised with defaults during construction.
4151 * @var array
4153 public $attributesprimary = array();
4155 * An array of attributes added to the container of the secondary actions.
4156 * Initialised with defaults during construction.
4157 * @var array
4159 public $attributessecondary = array();
4162 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
4163 * @var array
4165 public $actiontext = null;
4168 * The string to use for the accessible label for the menu.
4169 * @var array
4171 public $actionlabel = null;
4174 * An icon to use for the toggling the secondary menu (dropdown).
4175 * @var actionicon
4177 public $actionicon;
4180 * Any text to use for the toggling the secondary menu (dropdown).
4181 * @var menutrigger
4183 public $menutrigger = '';
4186 * Any extra classes for toggling to the secondary menu.
4187 * @var triggerextraclasses
4189 public $triggerextraclasses = '';
4192 * Place the action menu before all other actions.
4193 * @var prioritise
4195 public $prioritise = false;
4198 * Constructs the action menu with the given items.
4200 * @param array $actions An array of actions.
4202 public function __construct(array $actions = array()) {
4203 static $initialised = 0;
4204 $this->instance = $initialised;
4205 $initialised++;
4207 $this->attributes = array(
4208 'id' => 'action-menu-'.$this->instance,
4209 'class' => 'moodle-actionmenu',
4210 'data-enhance' => 'moodle-core-actionmenu'
4212 $this->attributesprimary = array(
4213 'id' => 'action-menu-'.$this->instance.'-menubar',
4214 'class' => 'menubar',
4215 'role' => 'menubar'
4217 $this->attributessecondary = array(
4218 'id' => 'action-menu-'.$this->instance.'-menu',
4219 'class' => 'menu',
4220 'data-rel' => 'menu-content',
4221 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
4222 'role' => 'menu'
4224 $this->set_alignment(self::TR, self::BR);
4225 foreach ($actions as $action) {
4226 $this->add($action);
4231 * Sets the label for the menu trigger.
4233 * @param string $label The text
4234 * @return null
4236 public function set_action_label($label) {
4237 $this->actionlabel = $label;
4241 * Sets the menu trigger text.
4243 * @param string $trigger The text
4244 * @param string $extraclasses Extra classes to style the secondary menu toggle.
4245 * @return null
4247 public function set_menu_trigger($trigger, $extraclasses = '') {
4248 $this->menutrigger = $trigger;
4249 $this->triggerextraclasses = $extraclasses;
4253 * Return true if there is at least one visible link in the menu.
4255 * @return bool
4257 public function is_empty() {
4258 return !count($this->primaryactions) && !count($this->secondaryactions);
4262 * Initialises JS required fore the action menu.
4263 * The JS is only required once as it manages all action menu's on the page.
4265 * @param moodle_page $page
4267 public function initialise_js(moodle_page $page) {
4268 static $initialised = false;
4269 if (!$initialised) {
4270 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
4271 $initialised = true;
4276 * Adds an action to this action menu.
4278 * @param action_menu_link|pix_icon|string $action
4280 public function add($action) {
4281 if ($action instanceof action_link) {
4282 if ($action->primary) {
4283 $this->add_primary_action($action);
4284 } else {
4285 $this->add_secondary_action($action);
4287 } else if ($action instanceof pix_icon) {
4288 $this->add_primary_action($action);
4289 } else {
4290 $this->add_secondary_action($action);
4295 * Adds a primary action to the action menu.
4297 * @param action_menu_link|action_link|pix_icon|string $action
4299 public function add_primary_action($action) {
4300 if ($action instanceof action_link || $action instanceof pix_icon) {
4301 $action->attributes['role'] = 'menuitem';
4302 if ($action instanceof action_menu_link) {
4303 $action->actionmenu = $this;
4306 $this->primaryactions[] = $action;
4310 * Adds a secondary action to the action menu.
4312 * @param action_link|pix_icon|string $action
4314 public function add_secondary_action($action) {
4315 if ($action instanceof action_link || $action instanceof pix_icon) {
4316 $action->attributes['role'] = 'menuitem';
4317 if ($action instanceof action_menu_link) {
4318 $action->actionmenu = $this;
4321 $this->secondaryactions[] = $action;
4325 * Returns the primary actions ready to be rendered.
4327 * @param core_renderer $output The renderer to use for getting icons.
4328 * @return array
4330 public function get_primary_actions(core_renderer $output = null) {
4331 global $OUTPUT;
4332 if ($output === null) {
4333 $output = $OUTPUT;
4335 $pixicon = $this->actionicon;
4336 $linkclasses = array('toggle-display');
4338 $title = '';
4339 if (!empty($this->menutrigger)) {
4340 $pixicon = '<b class="caret"></b>';
4341 $linkclasses[] = 'textmenu';
4342 } else {
4343 $title = new lang_string('actionsmenu', 'moodle');
4344 $this->actionicon = new pix_icon(
4345 't/edit_menu',
4347 'moodle',
4348 array('class' => 'iconsmall actionmenu', 'title' => '')
4350 $pixicon = $this->actionicon;
4352 if ($pixicon instanceof renderable) {
4353 $pixicon = $output->render($pixicon);
4354 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
4355 $title = $pixicon->attributes['alt'];
4358 $string = '';
4359 if ($this->actiontext) {
4360 $string = $this->actiontext;
4362 $label = '';
4363 if ($this->actionlabel) {
4364 $label = $this->actionlabel;
4365 } else {
4366 $label = $title;
4368 $actions = $this->primaryactions;
4369 $attributes = array(
4370 'class' => implode(' ', $linkclasses),
4371 'title' => $title,
4372 'aria-label' => $label,
4373 'id' => 'action-menu-toggle-'.$this->instance,
4374 'role' => 'menuitem'
4376 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
4377 if ($this->prioritise) {
4378 array_unshift($actions, $link);
4379 } else {
4380 $actions[] = $link;
4382 return $actions;
4386 * Returns the secondary actions ready to be rendered.
4387 * @return array
4389 public function get_secondary_actions() {
4390 return $this->secondaryactions;
4394 * Sets the selector that should be used to find the owning node of this menu.
4395 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
4397 public function set_owner_selector($selector) {
4398 $this->attributes['data-owner'] = $selector;
4402 * Sets the alignment of the dialogue in relation to button used to toggle it.
4404 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4405 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4407 public function set_alignment($dialogue, $button) {
4408 if (isset($this->attributessecondary['data-align'])) {
4409 // We've already got one set, lets remove the old class so as to avoid troubles.
4410 $class = $this->attributessecondary['class'];
4411 $search = 'align-'.$this->attributessecondary['data-align'];
4412 $this->attributessecondary['class'] = str_replace($search, '', $class);
4414 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
4415 $this->attributessecondary['data-align'] = $align;
4416 $this->attributessecondary['class'] .= ' align-'.$align;
4420 * Returns a string to describe the alignment.
4422 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4423 * @return string
4425 protected function get_align_string($align) {
4426 switch ($align) {
4427 case self::TL :
4428 return 'tl';
4429 case self::TR :
4430 return 'tr';
4431 case self::BL :
4432 return 'bl';
4433 case self::BR :
4434 return 'br';
4435 default :
4436 return 'tl';
4441 * Sets a constraint for the dialogue.
4443 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
4444 * element the constraint identifies.
4446 * This is required whenever the action menu is displayed inside any CSS element with the .no-overflow class
4447 * (flexible_table and any of it's child classes are a likely candidate).
4449 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
4451 public function set_constraint($ancestorselector) {
4452 $this->attributessecondary['data-constraint'] = $ancestorselector;
4456 * If you call this method the action menu will be displayed but will not be enhanced.
4458 * By not displaying the menu enhanced all items will be displayed in a single row.
4460 * @deprecated since Moodle 3.2
4462 public function do_not_enhance() {
4463 debugging('The method action_menu::do_not_enhance() is deprecated, use a list of action_icon instead.', DEBUG_DEVELOPER);
4467 * Returns true if this action menu will be enhanced.
4469 * @return bool
4471 public function will_be_enhanced() {
4472 return isset($this->attributes['data-enhance']);
4476 * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
4478 * This property can be useful when the action menu is displayed within a parent element that is either floated
4479 * or relatively positioned.
4480 * In that situation the width of the menu is determined by the width of the parent element which may not be large
4481 * enough for the menu items without them wrapping.
4482 * This disables the wrapping so that the menu takes on the width of the longest item.
4484 * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
4486 public function set_nowrap_on_items($value = true) {
4487 $class = 'nowrap-items';
4488 if (!empty($this->attributes['class'])) {
4489 $pos = strpos($this->attributes['class'], $class);
4490 if ($value === true && $pos === false) {
4491 // The value is true and the class has not been set yet. Add it.
4492 $this->attributes['class'] .= ' '.$class;
4493 } else if ($value === false && $pos !== false) {
4494 // The value is false and the class has been set. Remove it.
4495 $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class));
4497 } else if ($value) {
4498 // The value is true and the class has not been set yet. Add it.
4499 $this->attributes['class'] = $class;
4504 * Export for template.
4506 * @param renderer_base $output The renderer.
4507 * @return stdClass
4509 public function export_for_template(renderer_base $output) {
4510 $data = new stdClass();
4511 $attributes = $this->attributes;
4512 $attributesprimary = $this->attributesprimary;
4513 $attributessecondary = $this->attributessecondary;
4515 $data->instance = $this->instance;
4517 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
4518 unset($attributes['class']);
4520 $data->attributes = array_map(function($key, $value) {
4521 return [ 'name' => $key, 'value' => $value ];
4522 }, array_keys($attributes), $attributes);
4524 $primary = new stdClass();
4525 $primary->title = '';
4526 $primary->prioritise = $this->prioritise;
4528 $primary->classes = isset($attributesprimary['class']) ? $attributesprimary['class'] : '';
4529 unset($attributesprimary['class']);
4530 $primary->attributes = array_map(function($key, $value) {
4531 return [ 'name' => $key, 'value' => $value ];
4532 }, array_keys($attributesprimary), $attributesprimary);
4534 $actionicon = $this->actionicon;
4535 if (!empty($this->menutrigger)) {
4536 $primary->menutrigger = $this->menutrigger;
4537 $primary->triggerextraclasses = $this->triggerextraclasses;
4538 if ($this->actionlabel) {
4539 $primary->title = $this->actionlabel;
4540 } else if ($this->actiontext) {
4541 $primary->title = $this->actiontext;
4542 } else {
4543 $primary->title = strip_tags($this->menutrigger);
4545 } else {
4546 $primary->title = get_string('actionsmenu');
4547 $iconattributes = ['class' => 'iconsmall actionmenu', 'title' => $primary->title];
4548 $actionicon = new pix_icon('t/edit_menu', '', 'moodle', $iconattributes);
4551 if ($actionicon instanceof pix_icon) {
4552 $primary->icon = $actionicon->export_for_pix();
4553 if (!empty($actionicon->attributes['alt'])) {
4554 $primary->title = $actionicon->attributes['alt'];
4556 } else {
4557 $primary->iconraw = $actionicon ? $output->render($actionicon) : '';
4560 $primary->actiontext = $this->actiontext ? (string) $this->actiontext : '';
4561 $primary->items = array_map(function($item) use ($output) {
4562 $data = (object) [];
4563 if ($item instanceof action_menu_link) {
4564 $data->actionmenulink = $item->export_for_template($output);
4565 } else if ($item instanceof action_menu_filler) {
4566 $data->actionmenufiller = $item->export_for_template($output);
4567 } else if ($item instanceof action_link) {
4568 $data->actionlink = $item->export_for_template($output);
4569 } else if ($item instanceof pix_icon) {
4570 $data->pixicon = $item->export_for_template($output);
4571 } else {
4572 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4574 return $data;
4575 }, $this->primaryactions);
4577 $secondary = new stdClass();
4578 $secondary->classes = isset($attributessecondary['class']) ? $attributessecondary['class'] : '';
4579 unset($attributessecondary['class']);
4580 $secondary->attributes = array_map(function($key, $value) {
4581 return [ 'name' => $key, 'value' => $value ];
4582 }, array_keys($attributessecondary), $attributessecondary);
4583 $secondary->items = array_map(function($item) use ($output) {
4584 $data = (object) [];
4585 if ($item instanceof action_menu_link) {
4586 $data->actionmenulink = $item->export_for_template($output);
4587 } else if ($item instanceof action_menu_filler) {
4588 $data->actionmenufiller = $item->export_for_template($output);
4589 } else if ($item instanceof action_link) {
4590 $data->actionlink = $item->export_for_template($output);
4591 } else if ($item instanceof pix_icon) {
4592 $data->pixicon = $item->export_for_template($output);
4593 } else {
4594 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4596 return $data;
4597 }, $this->secondaryactions);
4599 $data->primary = $primary;
4600 $data->secondary = $secondary;
4602 return $data;
4608 * An action menu filler
4610 * @package core
4611 * @category output
4612 * @copyright 2013 Andrew Nicols
4613 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4615 class action_menu_filler extends action_link implements renderable {
4618 * True if this is a primary action. False if not.
4619 * @var bool
4621 public $primary = true;
4624 * Constructs the object.
4626 public function __construct() {
4631 * An action menu action
4633 * @package core
4634 * @category output
4635 * @copyright 2013 Sam Hemelryk
4636 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4638 class action_menu_link extends action_link implements renderable {
4641 * True if this is a primary action. False if not.
4642 * @var bool
4644 public $primary = true;
4647 * The action menu this link has been added to.
4648 * @var action_menu
4650 public $actionmenu = null;
4653 * Constructs the object.
4655 * @param moodle_url $url The URL for the action.
4656 * @param pix_icon $icon The icon to represent the action.
4657 * @param string $text The text to represent the action.
4658 * @param bool $primary Whether this is a primary action or not.
4659 * @param array $attributes Any attribtues associated with the action.
4661 public function __construct(moodle_url $url, pix_icon $icon = null, $text, $primary = true, array $attributes = array()) {
4662 parent::__construct($url, $text, null, $attributes, $icon);
4663 $this->primary = (bool)$primary;
4664 $this->add_class('menu-action');
4665 $this->attributes['role'] = 'menuitem';
4669 * Export for template.
4671 * @param renderer_base $output The renderer.
4672 * @return stdClass
4674 public function export_for_template(renderer_base $output) {
4675 static $instance = 1;
4677 $data = parent::export_for_template($output);
4678 $data->instance = $instance++;
4680 // Ignore what the parent did with the attributes, except for ID and class.
4681 $data->attributes = [];
4682 $attributes = $this->attributes;
4683 unset($attributes['id']);
4684 unset($attributes['class']);
4686 // Handle text being a renderable.
4687 if ($this->text instanceof renderable) {
4688 $data->text = $this->render($this->text);
4691 $data->showtext = (!$this->icon || $this->primary === false);
4693 $data->icon = null;
4694 if ($this->icon) {
4695 $icon = $this->icon;
4696 if ($this->primary || !$this->actionmenu->will_be_enhanced()) {
4697 $attributes['title'] = $data->text;
4699 $data->icon = $icon ? $icon->export_for_pix() : null;
4702 $data->disabled = !empty($attributes['disabled']);
4703 unset($attributes['disabled']);
4705 $data->attributes = array_map(function($key, $value) {
4706 return [
4707 'name' => $key,
4708 'value' => $value
4710 }, array_keys($attributes), $attributes);
4712 return $data;
4717 * A primary action menu action
4719 * @package core
4720 * @category output
4721 * @copyright 2013 Sam Hemelryk
4722 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4724 class action_menu_link_primary extends action_menu_link {
4726 * Constructs the object.
4728 * @param moodle_url $url
4729 * @param pix_icon $icon
4730 * @param string $text
4731 * @param array $attributes
4733 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
4734 parent::__construct($url, $icon, $text, true, $attributes);
4739 * A secondary action menu action
4741 * @package core
4742 * @category output
4743 * @copyright 2013 Sam Hemelryk
4744 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4746 class action_menu_link_secondary extends action_menu_link {
4748 * Constructs the object.
4750 * @param moodle_url $url
4751 * @param pix_icon $icon
4752 * @param string $text
4753 * @param array $attributes
4755 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
4756 parent::__construct($url, $icon, $text, false, $attributes);
4761 * Represents a set of preferences groups.
4763 * @package core
4764 * @category output
4765 * @copyright 2015 Frédéric Massart - FMCorz.net
4766 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4768 class preferences_groups implements renderable {
4771 * Array of preferences_group.
4772 * @var array
4774 public $groups;
4777 * Constructor.
4778 * @param array $groups of preferences_group
4780 public function __construct($groups) {
4781 $this->groups = $groups;
4787 * Represents a group of preferences page link.
4789 * @package core
4790 * @category output
4791 * @copyright 2015 Frédéric Massart - FMCorz.net
4792 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4794 class preferences_group implements renderable {
4797 * Title of the group.
4798 * @var string
4800 public $title;
4803 * Array of navigation_node.
4804 * @var array
4806 public $nodes;
4809 * Constructor.
4810 * @param string $title The title.
4811 * @param array $nodes of navigation_node.
4813 public function __construct($title, $nodes) {
4814 $this->title = $title;
4815 $this->nodes = $nodes;
4820 * Progress bar class.
4822 * Manages the display of a progress bar.
4824 * To use this class.
4825 * - construct
4826 * - call create (or use the 3rd param to the constructor)
4827 * - call update or update_full() or update() repeatedly
4829 * @copyright 2008 jamiesensei
4830 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4831 * @package core
4832 * @category output
4834 class progress_bar implements renderable, templatable {
4835 /** @var string html id */
4836 private $html_id;
4837 /** @var int total width */
4838 private $width;
4839 /** @var int last percentage printed */
4840 private $percent = 0;
4841 /** @var int time when last printed */
4842 private $lastupdate = 0;
4843 /** @var int when did we start printing this */
4844 private $time_start = 0;
4847 * Constructor
4849 * Prints JS code if $autostart true.
4851 * @param string $htmlid The container ID.
4852 * @param int $width The suggested width.
4853 * @param bool $autostart Whether to start the progress bar right away.
4855 public function __construct($htmlid = '', $width = 500, $autostart = false) {
4856 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
4857 debugging('progress_bar used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', DEBUG_DEVELOPER);
4860 if (!empty($htmlid)) {
4861 $this->html_id = $htmlid;
4862 } else {
4863 $this->html_id = 'pbar_'.uniqid();
4866 $this->width = $width;
4868 if ($autostart) {
4869 $this->create();
4874 * Create a new progress bar, this function will output html.
4876 * @return void Echo's output
4878 public function create() {
4879 global $OUTPUT;
4881 $this->time_start = microtime(true);
4882 if (CLI_SCRIPT) {
4883 return; // Temporary solution for cli scripts.
4886 flush();
4887 echo $OUTPUT->render($this);
4888 flush();
4892 * Update the progress bar.
4894 * @param int $percent From 1-100.
4895 * @param string $msg The message.
4896 * @return void Echo's output
4897 * @throws coding_exception
4899 private function _update($percent, $msg) {
4900 if (empty($this->time_start)) {
4901 throw new coding_exception('You must call create() (or use the $autostart ' .
4902 'argument to the constructor) before you try updating the progress bar.');
4905 if (CLI_SCRIPT) {
4906 return; // Temporary solution for cli scripts.
4909 $estimate = $this->estimate($percent);
4911 if ($estimate === null) {
4912 // Always do the first and last updates.
4913 } else if ($estimate == 0) {
4914 // Always do the last updates.
4915 } else if ($this->lastupdate + 20 < time()) {
4916 // We must update otherwise browser would time out.
4917 } else if (round($this->percent, 2) === round($percent, 2)) {
4918 // No significant change, no need to update anything.
4919 return;
4922 $estimatemsg = null;
4923 if (is_numeric($estimate)) {
4924 $estimatemsg = get_string('secondsleft', 'moodle', round($estimate, 2));
4927 $this->percent = round($percent, 2);
4928 $this->lastupdate = microtime(true);
4930 echo html_writer::script(js_writer::function_call('updateProgressBar',
4931 array($this->html_id, $this->percent, $msg, $estimatemsg)));
4932 flush();
4936 * Estimate how much time it is going to take.
4938 * @param int $pt From 1-100.
4939 * @return mixed Null (unknown), or int.
4941 private function estimate($pt) {
4942 if ($this->lastupdate == 0) {
4943 return null;
4945 if ($pt < 0.00001) {
4946 return null; // We do not know yet how long it will take.
4948 if ($pt > 99.99999) {
4949 return 0; // Nearly done, right?
4951 $consumed = microtime(true) - $this->time_start;
4952 if ($consumed < 0.001) {
4953 return null;
4956 return (100 - $pt) * ($consumed / $pt);
4960 * Update progress bar according percent.
4962 * @param int $percent From 1-100.
4963 * @param string $msg The message needed to be shown.
4965 public function update_full($percent, $msg) {
4966 $percent = max(min($percent, 100), 0);
4967 $this->_update($percent, $msg);
4971 * Update progress bar according the number of tasks.
4973 * @param int $cur Current task number.
4974 * @param int $total Total task number.
4975 * @param string $msg The message needed to be shown.
4977 public function update($cur, $total, $msg) {
4978 $percent = ($cur / $total) * 100;
4979 $this->update_full($percent, $msg);
4983 * Restart the progress bar.
4985 public function restart() {
4986 $this->percent = 0;
4987 $this->lastupdate = 0;
4988 $this->time_start = 0;
4992 * Export for template.
4994 * @param renderer_base $output The renderer.
4995 * @return array
4997 public function export_for_template(renderer_base $output) {
4998 return [
4999 'id' => $this->html_id,
5000 'width' => $this->width,