2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Classes representing HTML elements, used by $OUTPUT methods
20 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
25 * @copyright 2009 Tim Hunt
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
32 * Interface marking other classes as suitable for renderer_base::render()
34 * @copyright 2010 Petr Skoda (skodak) info@skodak.org
38 interface renderable {
39 // intentionally empty
43 * Data structure representing a file picker.
45 * @copyright 2010 Dongsheng Cai
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
51 class file_picker implements renderable {
54 * @var stdClass An object containing options for the file picker
59 * Constructs a file picker object.
61 * The following are possible options for the filepicker:
62 * - accepted_types (*)
63 * - return_types (FILE_INTERNAL)
65 * - client_id (uniqid)
69 * - buttonname (false)
71 * @param stdClass $options An object containing options for the file picker.
73 public function __construct(stdClass $options) {
74 global $CFG, $USER, $PAGE;
75 require_once($CFG->dirroot. '/repository/lib.php');
77 'accepted_types'=>'*',
78 'return_types'=>FILE_INTERNAL,
79 'env' => 'filepicker',
80 'client_id' => uniqid(),
86 foreach ($defaults as $key=>$value) {
87 if (empty($options->$key)) {
88 $options->$key = $value;
92 $options->currentfile = '';
93 if (!empty($options->itemid)) {
94 $fs = get_file_storage();
95 $usercontext = context_user::instance($USER->id);
96 if (empty($options->filename)) {
97 if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
98 $file = reset($files);
101 $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
104 $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
108 // initilise options, getting files in root path
109 $this->options = initialise_filepicker($options);
111 // copying other options
112 foreach ($options as $name=>$value) {
113 if (!isset($this->options->$name)) {
114 $this->options->$name = $value;
121 * Data structure representing a user picture.
123 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
124 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
129 class user_picture implements renderable {
131 * @var array List of mandatory fields in user record here. (do not include
132 * TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
134 protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'firstnamephonetic', 'lastnamephonetic',
135 'middlename', 'alternatename', 'imagealt', 'email');
138 * @var stdClass A user object with at least fields all columns specified
139 * in $fields array constant set.
144 * @var int The course id. Used when constructing the link to the user's
145 * profile, page course id used if not specified.
150 * @var bool Add course profile link to image
155 * @var int Size in pixels. Special values are (true/1 = 100px) and
157 * for backward compatibility.
162 * @var bool Add non-blank alt-text to the image.
163 * Default true, set to false when image alt just duplicates text in screenreaders.
165 public $alttext = true;
168 * @var bool Whether or not to open the link in a popup window.
170 public $popup = false;
173 * @var string Image class attribute
175 public $class = 'userpicture';
178 * User picture constructor.
180 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
181 * It is recommended to add also contextid of the user for performance reasons.
183 public function __construct(stdClass $user) {
186 if (empty($user->id)) {
187 throw new coding_exception('User id is required when printing user avatar image.');
190 // only touch the DB if we are missing data and complain loudly...
192 foreach (self::$fields as $field) {
193 if (!array_key_exists($field, $user)) {
195 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
196 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
202 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
204 $this->user = clone($user);
209 * Returns a list of required user fields, useful when fetching required user info from db.
211 * In some cases we have to fetch the user data together with some other information,
212 * the idalias is useful there because the id would otherwise override the main
213 * id of the result record. Please note it has to be converted back to id before rendering.
215 * @param string $tableprefix name of database table prefix in query
216 * @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)
217 * @param string $idalias alias of id field
218 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
221 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
222 if (!$tableprefix and !$extrafields and !$idalias) {
223 return implode(',', self::$fields);
228 foreach (self::$fields as $field) {
229 if ($field === 'id' and $idalias and $idalias !== 'id') {
230 $fields[$field] = "$tableprefix$field AS $idalias";
232 if ($fieldprefix and $field !== 'id') {
233 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
235 $fields[$field] = "$tableprefix$field";
239 // add extra fields if not already there
241 foreach ($extrafields as $e) {
242 if ($e === 'id' or isset($fields[$e])) {
246 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
248 $fields[$e] = "$tableprefix$e";
252 return implode(',', $fields);
256 * Extract the aliased user fields from a given record
258 * Given a record that was previously obtained using {@link self::fields()} with aliases,
259 * this method extracts user related unaliased fields.
261 * @param stdClass $record containing user picture fields
262 * @param array $extrafields extra fields included in the $record
263 * @param string $idalias alias of the id field
264 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
265 * @return stdClass object with unaliased user fields
267 public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
269 if (empty($idalias)) {
273 $return = new stdClass();
275 foreach (self::$fields as $field) {
276 if ($field === 'id') {
277 if (property_exists($record, $idalias)) {
278 $return->id = $record->{$idalias};
281 if (property_exists($record, $fieldprefix.$field)) {
282 $return->{$field} = $record->{$fieldprefix.$field};
286 // add extra fields if not already there
288 foreach ($extrafields as $e) {
289 if ($e === 'id' or property_exists($return, $e)) {
292 $return->{$e} = $record->{$fieldprefix.$e};
300 * Works out the URL for the users picture.
302 * This method is recommended as it avoids costly redirects of user pictures
303 * if requests are made for non-existent files etc.
305 * @param moodle_page $page
306 * @param renderer_base $renderer
309 public function get_url(moodle_page $page, renderer_base $renderer = null) {
312 if (is_null($renderer)) {
313 $renderer = $page->get_renderer('core');
316 // Sort out the filename and size. Size is only required for the gravatar
317 // implementation presently.
318 if (empty($this->size)) {
321 } else if ($this->size === true or $this->size == 1) {
324 } else if ($this->size > 100) {
326 $size = (int)$this->size;
327 } else if ($this->size >= 50) {
329 $size = (int)$this->size;
332 $size = (int)$this->size;
335 $defaulturl = $renderer->pix_url('u/'.$filename); // default image
337 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
338 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
339 // Protect images if login required and not logged in;
340 // also if login is required for profile images and is not logged in or guest
341 // do not use require_login() because it is expensive and not suitable here anyway.
345 // First try to detect deleted users - but do not read from database for performance reasons!
346 if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
347 // All deleted users should have email replaced by md5 hash,
348 // all active users are expected to have valid email.
352 // Did the user upload a picture?
353 if ($this->user->picture > 0) {
354 if (!empty($this->user->contextid)) {
355 $contextid = $this->user->contextid;
357 $context = context_user::instance($this->user->id, IGNORE_MISSING);
359 // This must be an incorrectly deleted user, all other users have context.
362 $contextid = $context->id;
366 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
367 // We append the theme name to the file path if we have it so that
368 // in the circumstance that the profile picture is not available
369 // when the user actually requests it they still get the profile
370 // picture for the correct theme.
371 $path .= $page->theme->name.'/';
373 // Set the image URL to the URL for the uploaded file and return.
374 $url = moodle_url::make_pluginfile_url($contextid, 'user', 'icon', NULL, $path, $filename);
375 $url->param('rev', $this->user->picture);
379 if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
380 // Normalise the size variable to acceptable bounds
381 if ($size < 1 || $size > 512) {
384 // Hash the users email address
385 $md5 = md5(strtolower(trim($this->user->email)));
386 // Build a gravatar URL with what we know.
388 // Find the best default image URL we can (MDL-35669)
389 if (empty($CFG->gravatardefaulturl)) {
390 $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
391 if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
392 $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
394 $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
397 $gravatardefault = $CFG->gravatardefaulturl;
400 // If the currently requested page is https then we'll return an
401 // https gravatar page.
402 if (strpos($CFG->httpswwwroot, 'https:') === 0) {
403 $gravatardefault = str_replace($CFG->wwwroot, $CFG->httpswwwroot, $gravatardefault); // Replace by secure url.
404 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
406 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
415 * Data structure representing a help icon.
417 * @copyright 2010 Petr Skoda (info@skodak.org)
418 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
423 class help_icon implements renderable {
426 * @var string lang pack identifier (without the "_help" suffix),
427 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
433 * @var string Component name, the same as in get_string()
438 * @var string Extra descriptive text next to the icon
440 public $linktext = null;
445 * @param string $identifier string for help page title,
446 * string with _help suffix is used for the actual help text.
447 * string with _link suffix is used to create a link to further info (if it exists)
448 * @param string $component
450 public function __construct($identifier, $component) {
451 $this->identifier = $identifier;
452 $this->component = $component;
456 * Verifies that both help strings exists, shows debug warnings if not
458 public function diag_strings() {
459 $sm = get_string_manager();
460 if (!$sm->string_exists($this->identifier, $this->component)) {
461 debugging("Help title string does not exist: [$this->identifier, $this->component]");
463 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
464 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
471 * Data structure representing an icon.
473 * @copyright 2010 Petr Skoda
474 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
479 class pix_icon implements renderable {
482 * @var string The icon name
487 * @var string The component the icon belongs to.
492 * @var array An array of attributes to use on the icon
494 var $attributes = array();
499 * @param string $pix short icon name
500 * @param string $alt The alt text to use for the icon
501 * @param string $component component name
502 * @param array $attributes html attributes
504 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
506 $this->component = $component;
507 $this->attributes = (array)$attributes;
509 $this->attributes['alt'] = $alt;
510 if (empty($this->attributes['class'])) {
511 $this->attributes['class'] = 'smallicon';
513 if (!isset($this->attributes['title'])) {
514 $this->attributes['title'] = $this->attributes['alt'];
515 } else if (empty($this->attributes['title'])) {
516 // Remove the title attribute if empty, we probably want to use the parent node's title
517 // and some browsers might overwrite it with an empty title.
518 unset($this->attributes['title']);
524 * Data structure representing an emoticon image
526 * @copyright 2010 David Mudrak
527 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
532 class pix_emoticon extends pix_icon implements renderable {
536 * @param string $pix short icon name
537 * @param string $alt alternative text
538 * @param string $component emoticon image provider
539 * @param array $attributes explicit HTML attributes
541 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
542 if (empty($attributes['class'])) {
543 $attributes['class'] = 'emoticon';
545 parent::__construct($pix, $alt, $component, $attributes);
550 * Data structure representing a simple form with only one button.
552 * @copyright 2009 Petr Skoda
553 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
558 class single_button implements renderable {
561 * @var moodle_url Target url
566 * @var string Button label
571 * @var string Form submit method post or get
573 var $method = 'post';
576 * @var string Wrapping div class
578 var $class = 'singlebutton';
581 * @var bool True if button disabled, false if normal
583 var $disabled = false;
586 * @var string Button tooltip
591 * @var string Form id
596 * @var array List of attached actions
598 var $actions = array();
602 * @param moodle_url $url
603 * @param string $label button text
604 * @param string $method get or post submit method
606 public function __construct(moodle_url $url, $label, $method='post') {
607 $this->url = clone($url);
608 $this->label = $label;
609 $this->method = $method;
613 * Shortcut for adding a JS confirm dialog when the button is clicked.
614 * The message must be a yes/no question.
616 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
618 public function add_confirm_action($confirmmessage) {
619 $this->add_action(new confirm_action($confirmmessage));
623 * Add action to the button.
624 * @param component_action $action
626 public function add_action(component_action $action) {
627 $this->actions[] = $action;
633 * Simple form with just one select field that gets submitted automatically.
635 * If JS not enabled small go button is printed too.
637 * @copyright 2009 Petr Skoda
638 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
643 class single_select implements renderable {
646 * @var moodle_url Target url - includes hidden fields
651 * @var string Name of the select element.
656 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
657 * it is also possible to specify optgroup as complex label array ex.:
658 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
659 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
664 * @var string Selected option
669 * @var array Nothing selected
674 * @var array Extra select field attributes
676 var $attributes = array();
679 * @var string Button label
684 * @var array Button label's attributes
686 var $labelattributes = array();
689 * @var string Form submit method post or get
694 * @var string Wrapping div class
696 var $class = 'singleselect';
699 * @var bool True if button disabled, false if normal
701 var $disabled = false;
704 * @var string Button tooltip
709 * @var string Form id
714 * @var array List of attached actions
716 var $helpicon = null;
720 * @param moodle_url $url form action target, includes hidden fields
721 * @param string $name name of selection field - the changing parameter in url
722 * @param array $options list of options
723 * @param string $selected selected element
724 * @param array $nothing
725 * @param string $formid
727 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
730 $this->options = $options;
731 $this->selected = $selected;
732 $this->nothing = $nothing;
733 $this->formid = $formid;
737 * Shortcut for adding a JS confirm dialog when the button is clicked.
738 * The message must be a yes/no question.
740 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
742 public function add_confirm_action($confirmmessage) {
743 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
747 * Add action to the button.
749 * @param component_action $action
751 public function add_action(component_action $action) {
752 $this->actions[] = $action;
758 * @deprecated since Moodle 2.0
760 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
761 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
767 * @param string $identifier The keyword that defines a help page
768 * @param string $component
770 public function set_help_icon($identifier, $component = 'moodle') {
771 $this->helpicon = new help_icon($identifier, $component);
775 * Sets select's label
777 * @param string $label
778 * @param array $attributes (optional)
780 public function set_label($label, $attributes = array()) {
781 $this->label = $label;
782 $this->labelattributes = $attributes;
788 * Simple URL selection widget description.
790 * @copyright 2009 Petr Skoda
791 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
796 class url_select implements renderable {
798 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
799 * it is also possible to specify optgroup as complex label array ex.:
800 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
801 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
806 * @var string Selected option
811 * @var array Nothing selected
816 * @var array Extra select field attributes
818 var $attributes = array();
821 * @var string Button label
826 * @var array Button label's attributes
828 var $labelattributes = array();
831 * @var string Wrapping div class
833 var $class = 'urlselect';
836 * @var bool True if button disabled, false if normal
838 var $disabled = false;
841 * @var string Button tooltip
846 * @var string Form id
851 * @var array List of attached actions
853 var $helpicon = null;
856 * @var string If set, makes button visible with given name for button
858 var $showbutton = null;
862 * @param array $urls list of options
863 * @param string $selected selected element
864 * @param array $nothing
865 * @param string $formid
866 * @param string $showbutton Set to text of button if it should be visible
867 * or null if it should be hidden (hidden version always has text 'go')
869 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
871 $this->selected = $selected;
872 $this->nothing = $nothing;
873 $this->formid = $formid;
874 $this->showbutton = $showbutton;
880 * @deprecated since Moodle 2.0
882 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
883 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
889 * @param string $identifier The keyword that defines a help page
890 * @param string $component
892 public function set_help_icon($identifier, $component = 'moodle') {
893 $this->helpicon = new help_icon($identifier, $component);
897 * Sets select's label
899 * @param string $label
900 * @param array $attributes (optional)
902 public function set_label($label, $attributes = array()) {
903 $this->label = $label;
904 $this->labelattributes = $attributes;
909 * Data structure describing html link with special action attached.
911 * @copyright 2010 Petr Skoda
912 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
917 class action_link implements renderable {
920 * @var moodle_url Href url
925 * @var string Link text HTML fragment
930 * @var array HTML attributes
935 * @var array List of actions attached to link
941 * @param moodle_url $url
942 * @param string $text HTML fragment
943 * @param component_action $action
944 * @param array $attributes associative array of html link attributes + disabled
946 public function __construct(moodle_url $url, $text, component_action $action = null, array $attributes = null) {
947 $this->url = clone($url);
949 $this->attributes = (array)$attributes;
951 $this->add_action($action);
956 * Add action to the link.
958 * @param component_action $action
960 public function add_action(component_action $action) {
961 $this->actions[] = $action;
965 * Adds a CSS class to this action link object
966 * @param string $class
968 public function add_class($class) {
969 if (empty($this->attributes['class'])) {
970 $this->attributes['class'] = $class;
972 $this->attributes['class'] .= ' ' . $class;
978 * Simple html output class
980 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
981 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
989 * Outputs a tag with attributes and contents
991 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
992 * @param string $contents What goes between the opening and closing tags
993 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
994 * @return string HTML fragment
996 public static function tag($tagname, $contents, array $attributes = null) {
997 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1001 * Outputs an opening tag with attributes
1003 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1004 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1005 * @return string HTML fragment
1007 public static function start_tag($tagname, array $attributes = null) {
1008 return '<' . $tagname . self::attributes($attributes) . '>';
1012 * Outputs a closing tag
1014 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1015 * @return string HTML fragment
1017 public static function end_tag($tagname) {
1018 return '</' . $tagname . '>';
1022 * Outputs an empty tag with attributes
1024 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1025 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1026 * @return string HTML fragment
1028 public static function empty_tag($tagname, array $attributes = null) {
1029 return '<' . $tagname . self::attributes($attributes) . ' />';
1033 * Outputs a tag, but only if the contents are not empty
1035 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1036 * @param string $contents What goes between the opening and closing tags
1037 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1038 * @return string HTML fragment
1040 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1041 if ($contents === '' || is_null($contents)) {
1044 return self::tag($tagname, $contents, $attributes);
1048 * Outputs a HTML attribute and value
1050 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1051 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1052 * @return string HTML fragment
1054 public static function attribute($name, $value) {
1055 if ($value instanceof moodle_url) {
1056 return ' ' . $name . '="' . $value->out() . '"';
1059 // special case, we do not want these in output
1060 if ($value === null) {
1064 // no sloppy trimming here!
1065 return ' ' . $name . '="' . s($value) . '"';
1069 * Outputs a list of HTML attributes and values
1071 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1072 * The values will be escaped with {@link s()}
1073 * @return string HTML fragment
1075 public static function attributes(array $attributes = null) {
1076 $attributes = (array)$attributes;
1078 foreach ($attributes as $name => $value) {
1079 $output .= self::attribute($name, $value);
1085 * Generates random html element id.
1087 * @staticvar int $counter
1088 * @staticvar type $uniq
1089 * @param string $base A string fragment that will be included in the random ID.
1090 * @return string A unique ID
1092 public static function random_id($base='random') {
1093 static $counter = 0;
1096 if (!isset($uniq)) {
1101 return $base.$uniq.$counter;
1105 * Generates a simple html link
1107 * @param string|moodle_url $url The URL
1108 * @param string $text The text
1109 * @param array $attributes HTML attributes
1110 * @return string HTML fragment
1112 public static function link($url, $text, array $attributes = null) {
1113 $attributes = (array)$attributes;
1114 $attributes['href'] = $url;
1115 return self::tag('a', $text, $attributes);
1119 * Generates a simple checkbox with optional label
1121 * @param string $name The name of the checkbox
1122 * @param string $value The value of the checkbox
1123 * @param bool $checked Whether the checkbox is checked
1124 * @param string $label The label for the checkbox
1125 * @param array $attributes Any attributes to apply to the checkbox
1126 * @return string html fragment
1128 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1129 $attributes = (array)$attributes;
1132 if ($label !== '' and !is_null($label)) {
1133 if (empty($attributes['id'])) {
1134 $attributes['id'] = self::random_id('checkbox_');
1137 $attributes['type'] = 'checkbox';
1138 $attributes['value'] = $value;
1139 $attributes['name'] = $name;
1140 $attributes['checked'] = $checked ? 'checked' : null;
1142 $output .= self::empty_tag('input', $attributes);
1144 if ($label !== '' and !is_null($label)) {
1145 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1152 * Generates a simple select yes/no form field
1154 * @param string $name name of select element
1155 * @param bool $selected
1156 * @param array $attributes - html select element attributes
1157 * @return string HTML fragment
1159 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1160 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1161 return self::select($options, $name, $selected, null, $attributes);
1165 * Generates a simple select form field
1167 * @param array $options associative array value=>label ex.:
1168 * array(1=>'One, 2=>Two)
1169 * it is also possible to specify optgroup as complex label array ex.:
1170 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1171 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1172 * @param string $name name of select element
1173 * @param string|array $selected value or array of values depending on multiple attribute
1174 * @param array|bool $nothing add nothing selected option, or false of not added
1175 * @param array $attributes html select element attributes
1176 * @return string HTML fragment
1178 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1179 $attributes = (array)$attributes;
1180 if (is_array($nothing)) {
1181 foreach ($nothing as $k=>$v) {
1182 if ($v === 'choose' or $v === 'choosedots') {
1183 $nothing[$k] = get_string('choosedots');
1186 $options = $nothing + $options; // keep keys, do not override
1188 } else if (is_string($nothing) and $nothing !== '') {
1190 $options = array(''=>$nothing) + $options;
1193 // we may accept more values if multiple attribute specified
1194 $selected = (array)$selected;
1195 foreach ($selected as $k=>$v) {
1196 $selected[$k] = (string)$v;
1199 if (!isset($attributes['id'])) {
1201 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1202 $id = str_replace('[', '', $id);
1203 $id = str_replace(']', '', $id);
1204 $attributes['id'] = $id;
1207 if (!isset($attributes['class'])) {
1208 $class = 'menu'.$name;
1209 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1210 $class = str_replace('[', '', $class);
1211 $class = str_replace(']', '', $class);
1212 $attributes['class'] = $class;
1214 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
1216 $attributes['name'] = $name;
1218 if (!empty($attributes['disabled'])) {
1219 $attributes['disabled'] = 'disabled';
1221 unset($attributes['disabled']);
1225 foreach ($options as $value=>$label) {
1226 if (is_array($label)) {
1227 // ignore key, it just has to be unique
1228 $output .= self::select_optgroup(key($label), current($label), $selected);
1230 $output .= self::select_option($label, $value, $selected);
1233 return self::tag('select', $output, $attributes);
1237 * Returns HTML to display a select box option.
1239 * @param string $label The label to display as the option.
1240 * @param string|int $value The value the option represents
1241 * @param array $selected An array of selected options
1242 * @return string HTML fragment
1244 private static function select_option($label, $value, array $selected) {
1245 $attributes = array();
1246 $value = (string)$value;
1247 if (in_array($value, $selected, true)) {
1248 $attributes['selected'] = 'selected';
1250 $attributes['value'] = $value;
1251 return self::tag('option', $label, $attributes);
1255 * Returns HTML to display a select box option group.
1257 * @param string $groupname The label to use for the group
1258 * @param array $options The options in the group
1259 * @param array $selected An array of selected values.
1260 * @return string HTML fragment.
1262 private static function select_optgroup($groupname, $options, array $selected) {
1263 if (empty($options)) {
1266 $attributes = array('label'=>$groupname);
1268 foreach ($options as $value=>$label) {
1269 $output .= self::select_option($label, $value, $selected);
1271 return self::tag('optgroup', $output, $attributes);
1275 * This is a shortcut for making an hour selector menu.
1277 * @param string $type The type of selector (years, months, days, hours, minutes)
1278 * @param string $name fieldname
1279 * @param int $currenttime A default timestamp in GMT
1280 * @param int $step minute spacing
1281 * @param array $attributes - html select element attributes
1282 * @return HTML fragment
1284 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1285 if (!$currenttime) {
1286 $currenttime = time();
1288 $currentdate = usergetdate($currenttime);
1289 $userdatetype = $type;
1290 $timeunits = array();
1294 for ($i=1970; $i<=2020; $i++) {
1295 $timeunits[$i] = $i;
1297 $userdatetype = 'year';
1300 for ($i=1; $i<=12; $i++) {
1301 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1303 $userdatetype = 'month';
1304 $currentdate['month'] = (int)$currentdate['mon'];
1307 for ($i=1; $i<=31; $i++) {
1308 $timeunits[$i] = $i;
1310 $userdatetype = 'mday';
1313 for ($i=0; $i<=23; $i++) {
1314 $timeunits[$i] = sprintf("%02d",$i);
1319 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1322 for ($i=0; $i<=59; $i+=$step) {
1323 $timeunits[$i] = sprintf("%02d",$i);
1327 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1330 if (empty($attributes['id'])) {
1331 $attributes['id'] = self::random_id('ts_');
1333 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1334 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1336 return $label.$timerselector;
1340 * Shortcut for quick making of lists
1342 * Note: 'list' is a reserved keyword ;-)
1344 * @param array $items
1345 * @param array $attributes
1346 * @param string $tag ul or ol
1349 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1350 $output = html_writer::start_tag($tag, $attributes)."\n";
1351 foreach ($items as $item) {
1352 $output .= html_writer::tag('li', $item)."\n";
1354 $output .= html_writer::end_tag($tag);
1359 * Returns hidden input fields created from url parameters.
1361 * @param moodle_url $url
1362 * @param array $exclude list of excluded parameters
1363 * @return string HTML fragment
1365 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1366 $exclude = (array)$exclude;
1367 $params = $url->params();
1368 foreach ($exclude as $key) {
1369 unset($params[$key]);
1373 foreach ($params as $key => $value) {
1374 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1375 $output .= self::empty_tag('input', $attributes)."\n";
1381 * Generate a script tag containing the the specified code.
1383 * @param string $jscode the JavaScript code
1384 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
1385 * @return string HTML, the code wrapped in <script> tags.
1387 public static function script($jscode, $url=null) {
1389 $attributes = array('type'=>'text/javascript');
1390 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1393 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1394 return self::tag('script', '', $attributes) . "\n";
1402 * Renders HTML table
1404 * This method may modify the passed instance by adding some default properties if they are not set yet.
1405 * If this is not what you want, you should make a full clone of your data before passing them to this
1406 * method. In most cases this is not an issue at all so we do not clone by default for performance
1407 * and memory consumption reasons.
1409 * @param html_table $table data to be rendered
1410 * @return string HTML code
1412 public static function table(html_table $table) {
1413 // prepare table data and populate missing properties with reasonable defaults
1414 if (!empty($table->align)) {
1415 foreach ($table->align as $key => $aa) {
1417 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1419 $table->align[$key] = null;
1423 if (!empty($table->size)) {
1424 foreach ($table->size as $key => $ss) {
1426 $table->size[$key] = 'width:'. $ss .';';
1428 $table->size[$key] = null;
1432 if (!empty($table->wrap)) {
1433 foreach ($table->wrap as $key => $ww) {
1435 $table->wrap[$key] = 'white-space:nowrap;';
1437 $table->wrap[$key] = '';
1441 if (!empty($table->head)) {
1442 foreach ($table->head as $key => $val) {
1443 if (!isset($table->align[$key])) {
1444 $table->align[$key] = null;
1446 if (!isset($table->size[$key])) {
1447 $table->size[$key] = null;
1449 if (!isset($table->wrap[$key])) {
1450 $table->wrap[$key] = null;
1455 if (empty($table->attributes['class'])) {
1456 $table->attributes['class'] = 'generaltable';
1458 if (!empty($table->tablealign)) {
1459 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1462 // explicitly assigned properties override those defined via $table->attributes
1463 $table->attributes['class'] = trim($table->attributes['class']);
1464 $attributes = array_merge($table->attributes, array(
1466 'width' => $table->width,
1467 'summary' => $table->summary,
1468 'cellpadding' => $table->cellpadding,
1469 'cellspacing' => $table->cellspacing,
1471 $output = html_writer::start_tag('table', $attributes) . "\n";
1475 if (!empty($table->head)) {
1476 $countcols = count($table->head);
1478 $output .= html_writer::start_tag('thead', array()) . "\n";
1479 $output .= html_writer::start_tag('tr', array()) . "\n";
1480 $keys = array_keys($table->head);
1481 $lastkey = end($keys);
1483 foreach ($table->head as $key => $heading) {
1484 // Convert plain string headings into html_table_cell objects
1485 if (!($heading instanceof html_table_cell)) {
1486 $headingtext = $heading;
1487 $heading = new html_table_cell();
1488 $heading->text = $headingtext;
1489 $heading->header = true;
1492 if ($heading->header !== false) {
1493 $heading->header = true;
1496 if ($heading->header && empty($heading->scope)) {
1497 $heading->scope = 'col';
1500 $heading->attributes['class'] .= ' header c' . $key;
1501 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1502 $heading->colspan = $table->headspan[$key];
1503 $countcols += $table->headspan[$key] - 1;
1506 if ($key == $lastkey) {
1507 $heading->attributes['class'] .= ' lastcol';
1509 if (isset($table->colclasses[$key])) {
1510 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1512 $heading->attributes['class'] = trim($heading->attributes['class']);
1513 $attributes = array_merge($heading->attributes, array(
1514 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1515 'scope' => $heading->scope,
1516 'colspan' => $heading->colspan,
1520 if ($heading->header === true) {
1523 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1525 $output .= html_writer::end_tag('tr') . "\n";
1526 $output .= html_writer::end_tag('thead') . "\n";
1528 if (empty($table->data)) {
1529 // For valid XHTML strict every table must contain either a valid tr
1530 // or a valid tbody... both of which must contain a valid td
1531 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1532 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1533 $output .= html_writer::end_tag('tbody');
1537 if (!empty($table->data)) {
1539 $keys = array_keys($table->data);
1540 $lastrowkey = end($keys);
1541 $output .= html_writer::start_tag('tbody', array());
1543 foreach ($table->data as $key => $row) {
1544 if (($row === 'hr') && ($countcols)) {
1545 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1547 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1548 if (!($row instanceof html_table_row)) {
1549 $newrow = new html_table_row();
1551 foreach ($row as $cell) {
1552 if (!($cell instanceof html_table_cell)) {
1553 $cell = new html_table_cell($cell);
1555 $newrow->cells[] = $cell;
1560 $oddeven = $oddeven ? 0 : 1;
1561 if (isset($table->rowclasses[$key])) {
1562 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1565 $row->attributes['class'] .= ' r' . $oddeven;
1566 if ($key == $lastrowkey) {
1567 $row->attributes['class'] .= ' lastrow';
1570 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1571 $keys2 = array_keys($row->cells);
1572 $lastkey = end($keys2);
1574 $gotlastkey = false; //flag for sanity checking
1575 foreach ($row->cells as $key => $cell) {
1577 //This should never happen. Why do we have a cell after the last cell?
1578 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1581 if (!($cell instanceof html_table_cell)) {
1582 $mycell = new html_table_cell();
1583 $mycell->text = $cell;
1587 if (($cell->header === true) && empty($cell->scope)) {
1588 $cell->scope = 'row';
1591 if (isset($table->colclasses[$key])) {
1592 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1595 $cell->attributes['class'] .= ' cell c' . $key;
1596 if ($key == $lastkey) {
1597 $cell->attributes['class'] .= ' lastcol';
1601 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1602 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1603 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1604 $cell->attributes['class'] = trim($cell->attributes['class']);
1605 $tdattributes = array_merge($cell->attributes, array(
1606 'style' => $tdstyle . $cell->style,
1607 'colspan' => $cell->colspan,
1608 'rowspan' => $cell->rowspan,
1610 'abbr' => $cell->abbr,
1611 'scope' => $cell->scope,
1614 if ($cell->header === true) {
1617 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1620 $output .= html_writer::end_tag('tr') . "\n";
1622 $output .= html_writer::end_tag('tbody') . "\n";
1624 $output .= html_writer::end_tag('table') . "\n";
1630 * Renders form element label
1632 * By default, the label is suffixed with a label separator defined in the
1633 * current language pack (colon by default in the English lang pack).
1634 * Adding the colon can be explicitly disabled if needed. Label separators
1635 * are put outside the label tag itself so they are not read by
1636 * screenreaders (accessibility).
1638 * Parameter $for explicitly associates the label with a form control. When
1639 * set, the value of this attribute must be the same as the value of
1640 * the id attribute of the form control in the same document. When null,
1641 * the label being defined is associated with the control inside the label
1644 * @param string $text content of the label tag
1645 * @param string|null $for id of the element this label is associated with, null for no association
1646 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1647 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1648 * @return string HTML of the label element
1650 public static function label($text, $for, $colonize = true, array $attributes=array()) {
1651 if (!is_null($for)) {
1652 $attributes = array_merge($attributes, array('for' => $for));
1654 $text = trim($text);
1655 $label = self::tag('label', $text, $attributes);
1657 // TODO MDL-12192 $colonize disabled for now yet
1658 // if (!empty($text) and $colonize) {
1659 // // the $text may end with the colon already, though it is bad string definition style
1660 // $colon = get_string('labelsep', 'langconfig');
1661 // if (!empty($colon)) {
1662 // $trimmed = trim($colon);
1663 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1664 // //debugging('The label text should not end with colon or other label separator,
1665 // // please fix the string definition.', DEBUG_DEVELOPER);
1667 // $label .= $colon;
1676 * Combines a class parameter with other attributes. Aids in code reduction
1677 * because the class parameter is very frequently used.
1679 * If the class attribute is specified both in the attributes and in the
1680 * class parameter, the two values are combined with a space between.
1682 * @param string $class Optional CSS class (or classes as space-separated list)
1683 * @param array $attributes Optional other attributes as array
1684 * @return array Attributes (or null if still none)
1686 private static function add_class($class = '', array $attributes = null) {
1687 if ($class !== '') {
1688 $classattribute = array('class' => $class);
1690 if (array_key_exists('class', $attributes)) {
1691 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
1693 $attributes = $classattribute + $attributes;
1696 $attributes = $classattribute;
1703 * Creates a <div> tag. (Shortcut function.)
1705 * @param string $content HTML content of tag
1706 * @param string $class Optional CSS class (or classes as space-separated list)
1707 * @param array $attributes Optional other attributes as array
1708 * @return string HTML code for div
1710 public static function div($content, $class = '', array $attributes = null) {
1711 return self::tag('div', $content, self::add_class($class, $attributes));
1715 * Starts a <div> tag. (Shortcut function.)
1717 * @param string $class Optional CSS class (or classes as space-separated list)
1718 * @param array $attributes Optional other attributes as array
1719 * @return string HTML code for open div tag
1721 public static function start_div($class = '', array $attributes = null) {
1722 return self::start_tag('div', self::add_class($class, $attributes));
1726 * Ends a <div> tag. (Shortcut function.)
1728 * @return string HTML code for close div tag
1730 public static function end_div() {
1731 return self::end_tag('div');
1735 * Creates a <span> tag. (Shortcut function.)
1737 * @param string $content HTML content of tag
1738 * @param string $class Optional CSS class (or classes as space-separated list)
1739 * @param array $attributes Optional other attributes as array
1740 * @return string HTML code for span
1742 public static function span($content, $class = '', array $attributes = null) {
1743 return self::tag('span', $content, self::add_class($class, $attributes));
1747 * Starts a <span> tag. (Shortcut function.)
1749 * @param string $class Optional CSS class (or classes as space-separated list)
1750 * @param array $attributes Optional other attributes as array
1751 * @return string HTML code for open span tag
1753 public static function start_span($class = '', array $attributes = null) {
1754 return self::start_tag('span', self::add_class($class, $attributes));
1758 * Ends a <span> tag. (Shortcut function.)
1760 * @return string HTML code for close span tag
1762 public static function end_span() {
1763 return self::end_tag('span');
1768 * Simple javascript output class
1770 * @copyright 2010 Petr Skoda
1771 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1779 * Returns javascript code calling the function
1781 * @param string $function function name, can be complex like Y.Event.purgeElement
1782 * @param array $arguments parameters
1783 * @param int $delay execution delay in seconds
1784 * @return string JS code fragment
1786 public static function function_call($function, array $arguments = null, $delay=0) {
1788 $arguments = array_map('json_encode', convert_to_array($arguments));
1789 $arguments = implode(', ', $arguments);
1793 $js = "$function($arguments);";
1796 $delay = $delay * 1000; // in miliseconds
1797 $js = "setTimeout(function() { $js }, $delay);";
1803 * Special function which adds Y as first argument of function call.
1805 * @param string $function The function to call
1806 * @param array $extraarguments Any arguments to pass to it
1807 * @return string Some JS code
1809 public static function function_call_with_Y($function, array $extraarguments = null) {
1810 if ($extraarguments) {
1811 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1812 $arguments = 'Y, ' . implode(', ', $extraarguments);
1816 return "$function($arguments);\n";
1820 * Returns JavaScript code to initialise a new object
1822 * @param string $var If it is null then no var is assigned the new object.
1823 * @param string $class The class to initialise an object for.
1824 * @param array $arguments An array of args to pass to the init method.
1825 * @param array $requirements Any modules required for this class.
1826 * @param int $delay The delay before initialisation. 0 = no delay.
1827 * @return string Some JS code
1829 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1830 if (is_array($arguments)) {
1831 $arguments = array_map('json_encode', convert_to_array($arguments));
1832 $arguments = implode(', ', $arguments);
1835 if ($var === null) {
1836 $js = "new $class(Y, $arguments);";
1837 } else if (strpos($var, '.')!==false) {
1838 $js = "$var = new $class(Y, $arguments);";
1840 $js = "var $var = new $class(Y, $arguments);";
1844 $delay = $delay * 1000; // in miliseconds
1845 $js = "setTimeout(function() { $js }, $delay);";
1848 if (count($requirements) > 0) {
1849 $requirements = implode("', '", $requirements);
1850 $js = "Y.use('$requirements', function(Y){ $js });";
1856 * Returns code setting value to variable
1858 * @param string $name
1859 * @param mixed $value json serialised value
1860 * @param bool $usevar add var definition, ignored for nested properties
1861 * @return string JS code fragment
1863 public static function set_variable($name, $value, $usevar = true) {
1867 if (strpos($name, '.')) {
1874 $output .= "$name = ".json_encode($value).";";
1880 * Writes event handler attaching code
1882 * @param array|string $selector standard YUI selector for elements, may be
1883 * array or string, element id is in the form "#idvalue"
1884 * @param string $event A valid DOM event (click, mousedown, change etc.)
1885 * @param string $function The name of the function to call
1886 * @param array $arguments An optional array of argument parameters to pass to the function
1887 * @return string JS code fragment
1889 public static function event_handler($selector, $event, $function, array $arguments = null) {
1890 $selector = json_encode($selector);
1891 $output = "Y.on('$event', $function, $selector, null";
1892 if (!empty($arguments)) {
1893 $output .= ', ' . json_encode($arguments);
1895 return $output . ");\n";
1900 * Holds all the information required to render a <table> by {@link core_renderer::table()}
1903 * $t = new html_table();
1904 * ... // set various properties of the object $t as described below
1905 * echo html_writer::table($t);
1907 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1908 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1916 * @var string Value to use for the id attribute of the table
1921 * @var array Attributes of HTML attributes for the <table> element
1923 public $attributes = array();
1926 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
1927 * For more control over the rendering of the headers, an array of html_table_cell objects
1928 * can be passed instead of an array of strings.
1931 * $t->head = array('Student', 'Grade');
1936 * @var array An array that can be used to make a heading span multiple columns.
1937 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1938 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
1941 * $t->headspan = array(2,1);
1946 * @var array An array of column alignments.
1947 * The value is used as CSS 'text-align' property. Therefore, possible
1948 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1949 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1951 * Examples of usage:
1952 * $t->align = array(null, 'right');
1954 * $t->align[1] = 'right';
1959 * @var array The value is used as CSS 'size' property.
1961 * Examples of usage:
1962 * $t->size = array('50%', '50%');
1964 * $t->size[1] = '120px';
1969 * @var array An array of wrapping information.
1970 * The only possible value is 'nowrap' that sets the
1971 * CSS property 'white-space' to the value 'nowrap' in the given column.
1974 * $t->wrap = array(null, 'nowrap');
1979 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
1980 * $head specified, the string 'hr' (for horizontal ruler) can be used
1981 * instead of an array of cells data resulting in a divider rendered.
1983 * Example of usage with array of arrays:
1984 * $row1 = array('Harry Potter', '76 %');
1985 * $row2 = array('Hermione Granger', '100 %');
1986 * $t->data = array($row1, $row2);
1988 * Example with array of html_table_row objects: (used for more fine-grained control)
1989 * $cell1 = new html_table_cell();
1990 * $cell1->text = 'Harry Potter';
1991 * $cell1->colspan = 2;
1992 * $row1 = new html_table_row();
1993 * $row1->cells[] = $cell1;
1994 * $cell2 = new html_table_cell();
1995 * $cell2->text = 'Hermione Granger';
1996 * $cell3 = new html_table_cell();
1997 * $cell3->text = '100 %';
1998 * $row2 = new html_table_row();
1999 * $row2->cells = array($cell2, $cell3);
2000 * $t->data = array($row1, $row2);
2005 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2006 * @var string Width of the table, percentage of the page preferred.
2008 public $width = null;
2011 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2012 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2014 public $tablealign = null;
2017 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2018 * @var int Padding on each cell, in pixels
2020 public $cellpadding = null;
2023 * @var int Spacing between cells, in pixels
2024 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2026 public $cellspacing = null;
2029 * @var array Array of classes to add to particular rows, space-separated string.
2030 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
2031 * respectively. Class 'lastrow' is added automatically for the last row
2035 * $t->rowclasses[9] = 'tenth'
2040 * @var array An array of classes to add to every cell in a particular column,
2041 * space-separated string. Class 'cell' is added automatically by the renderer.
2042 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2043 * respectively. Class 'lastcol' is added automatically for all last cells
2047 * $t->colclasses = array(null, 'grade');
2052 * @var string Description of the contents for screen readers.
2059 public function __construct() {
2060 $this->attributes['class'] = '';
2065 * Component representing a table row.
2067 * @copyright 2009 Nicolas Connault
2068 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2073 class html_table_row {
2076 * @var string Value to use for the id attribute of the row.
2081 * @var array Array of html_table_cell objects
2083 public $cells = array();
2086 * @var string Value to use for the style attribute of the table row
2088 public $style = null;
2091 * @var array Attributes of additional HTML attributes for the <tr> element
2093 public $attributes = array();
2097 * @param array $cells
2099 public function __construct(array $cells=null) {
2100 $this->attributes['class'] = '';
2101 $cells = (array)$cells;
2102 foreach ($cells as $cell) {
2103 if ($cell instanceof html_table_cell) {
2104 $this->cells[] = $cell;
2106 $this->cells[] = new html_table_cell($cell);
2113 * Component representing a table cell.
2115 * @copyright 2009 Nicolas Connault
2116 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2121 class html_table_cell {
2124 * @var string Value to use for the id attribute of the cell.
2129 * @var string The contents of the cell.
2134 * @var string Abbreviated version of the contents of the cell.
2136 public $abbr = null;
2139 * @var int Number of columns this cell should span.
2141 public $colspan = null;
2144 * @var int Number of rows this cell should span.
2146 public $rowspan = null;
2149 * @var string Defines a way to associate header cells and data cells in a table.
2151 public $scope = null;
2154 * @var bool Whether or not this cell is a header cell.
2156 public $header = null;
2159 * @var string Value to use for the style attribute of the table cell
2161 public $style = null;
2164 * @var array Attributes of additional HTML attributes for the <td> element
2166 public $attributes = array();
2169 * Constructs a table cell
2171 * @param string $text
2173 public function __construct($text = null) {
2174 $this->text = $text;
2175 $this->attributes['class'] = '';
2180 * Component representing a paging bar.
2182 * @copyright 2009 Nicolas Connault
2183 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2188 class paging_bar implements renderable {
2191 * @var int The maximum number of pagelinks to display.
2193 public $maxdisplay = 18;
2196 * @var int The total number of entries to be pages through..
2201 * @var int The page you are currently viewing.
2206 * @var int The number of entries that should be shown per page.
2211 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2212 * an equals sign and the page number.
2213 * If this is a moodle_url object then the pagevar param will be replaced by
2214 * the page no, for each page.
2219 * @var string This is the variable name that you use for the pagenumber in your
2220 * code (ie. 'tablepage', 'blogpage', etc)
2225 * @var string A HTML link representing the "previous" page.
2227 public $previouslink = null;
2230 * @var string A HTML link representing the "next" page.
2232 public $nextlink = null;
2235 * @var string A HTML link representing the first page.
2237 public $firstlink = null;
2240 * @var string A HTML link representing the last page.
2242 public $lastlink = null;
2245 * @var array An array of strings. One of them is just a string: the current page
2247 public $pagelinks = array();
2250 * Constructor paging_bar with only the required params.
2252 * @param int $totalcount The total number of entries available to be paged through
2253 * @param int $page The page you are currently viewing
2254 * @param int $perpage The number of entries that should be shown per page
2255 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2256 * @param string $pagevar name of page parameter that holds the page number
2258 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2259 $this->totalcount = $totalcount;
2260 $this->page = $page;
2261 $this->perpage = $perpage;
2262 $this->baseurl = $baseurl;
2263 $this->pagevar = $pagevar;
2267 * Prepares the paging bar for output.
2269 * This method validates the arguments set up for the paging bar and then
2270 * produces fragments of HTML to assist display later on.
2272 * @param renderer_base $output
2273 * @param moodle_page $page
2274 * @param string $target
2275 * @throws coding_exception
2277 public function prepare(renderer_base $output, moodle_page $page, $target) {
2278 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2279 throw new coding_exception('paging_bar requires a totalcount value.');
2281 if (!isset($this->page) || is_null($this->page)) {
2282 throw new coding_exception('paging_bar requires a page value.');
2284 if (empty($this->perpage)) {
2285 throw new coding_exception('paging_bar requires a perpage value.');
2287 if (empty($this->baseurl)) {
2288 throw new coding_exception('paging_bar requires a baseurl value.');
2291 if ($this->totalcount > $this->perpage) {
2292 $pagenum = $this->page - 1;
2294 if ($this->page > 0) {
2295 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2298 if ($this->perpage > 0) {
2299 $lastpage = ceil($this->totalcount / $this->perpage);
2304 if ($this->page > round(($this->maxdisplay/3)*2)) {
2305 $currpage = $this->page - round($this->maxdisplay/3);
2307 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2312 $displaycount = $displaypage = 0;
2314 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2315 $displaypage = $currpage + 1;
2317 if ($this->page == $currpage) {
2318 $this->pagelinks[] = $displaypage;
2320 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2321 $this->pagelinks[] = $pagelink;
2328 if ($currpage < $lastpage) {
2329 $lastpageactual = $lastpage - 1;
2330 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2333 $pagenum = $this->page + 1;
2335 if ($pagenum != $displaypage) {
2336 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2343 * This class represents how a block appears on a page.
2345 * During output, each block instance is asked to return a block_contents object,
2346 * those are then passed to the $OUTPUT->block function for display.
2348 * contents should probably be generated using a moodle_block_..._renderer.
2350 * Other block-like things that need to appear on the page, for example the
2351 * add new block UI, are also represented as block_contents objects.
2353 * @copyright 2009 Tim Hunt
2354 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2359 class block_contents {
2361 /** Used when the block cannot be collapsed **/
2362 const NOT_HIDEABLE = 0;
2364 /** Used when the block can be collapsed but currently is not **/
2367 /** Used when the block has been collapsed **/
2371 * @var int Used to set $skipid.
2373 protected static $idcounter = 1;
2376 * @var int All the blocks (or things that look like blocks) printed on
2377 * a page are given a unique number that can be used to construct id="" attributes.
2378 * This is set automatically be the {@link prepare()} method.
2379 * Do not try to set it manually.
2384 * @var int If this is the contents of a real block, this should be set
2385 * to the block_instance.id. Otherwise this should be set to 0.
2387 public $blockinstanceid = 0;
2390 * @var int If this is a real block instance, and there is a corresponding
2391 * block_position.id for the block on this page, this should be set to that id.
2392 * Otherwise it should be 0.
2394 public $blockpositionid = 0;
2397 * @var array An array of attribute => value pairs that are put on the outer div of this
2398 * block. {@link $id} and {@link $classes} attributes should be set separately.
2403 * @var string The title of this block. If this came from user input, it should already
2404 * have had format_string() processing done on it. This will be output inside
2405 * <h2> tags. Please do not cause invalid XHTML.
2410 * @var string The label to use when the block does not, or will not have a visible title.
2411 * You should never set this as well as title... it will just be ignored.
2413 public $arialabel = '';
2416 * @var string HTML for the content
2418 public $content = '';
2421 * @var array An alternative to $content, it you want a list of things with optional icons.
2423 public $footer = '';
2426 * @var string Any small print that should appear under the block to explain
2427 * to the teacher about the block, for example 'This is a sticky block that was
2428 * added in the system context.'
2430 public $annotation = '';
2433 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2434 * the user can toggle whether this block is visible.
2436 public $collapsible = self::NOT_HIDEABLE;
2439 * @var array A (possibly empty) array of editing controls. Each element of
2440 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2441 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2443 public $controls = array();
2447 * Create new instance of block content
2448 * @param array $attributes
2450 public function __construct(array $attributes = null) {
2451 $this->skipid = self::$idcounter;
2452 self::$idcounter += 1;
2456 $this->attributes = $attributes;
2458 // simple "fake" blocks used in some modules and "Add new block" block
2459 $this->attributes = array('class'=>'block');
2464 * Add html class to block
2466 * @param string $class
2468 public function add_class($class) {
2469 $this->attributes['class'] .= ' '.$class;
2475 * This class represents a target for where a block can go when it is being moved.
2477 * This needs to be rendered as a form with the given hidden from fields, and
2478 * clicking anywhere in the form should submit it. The form action should be
2481 * @copyright 2009 Tim Hunt
2482 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2487 class block_move_target {
2490 * @var moodle_url Move url
2496 * @param moodle_url $url
2498 public function __construct(moodle_url $url) {
2506 * This class is used to represent one item within a custom menu that may or may
2507 * not have children.
2509 * @copyright 2010 Sam Hemelryk
2510 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2515 class custom_menu_item implements renderable {
2518 * @var string The text to show for the item
2523 * @var moodle_url The link to give the icon if it has no children
2528 * @var string A title to apply to the item. By default the text
2533 * @var int A sort order for the item, not necessary if you order things in
2539 * @var custom_menu_item A reference to the parent for this item or NULL if
2540 * it is a top level item
2545 * @var array A array in which to store children this item has.
2547 protected $children = array();
2550 * @var int A reference to the sort var of the last child that was added
2552 protected $lastsort = 0;
2555 * Constructs the new custom menu item
2557 * @param string $text
2558 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2559 * @param string $title A title to apply to this item [Optional]
2560 * @param int $sort A sort or to use if we need to sort differently [Optional]
2561 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2562 * belongs to, only if the child has a parent. [Optional]
2564 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
2565 $this->text = $text;
2567 $this->title = $title;
2568 $this->sort = (int)$sort;
2569 $this->parent = $parent;
2573 * Adds a custom menu item as a child of this node given its properties.
2575 * @param string $text
2576 * @param moodle_url $url
2577 * @param string $title
2579 * @return custom_menu_item
2581 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
2582 $key = count($this->children);
2584 $sort = $this->lastsort + 1;
2586 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2587 $this->lastsort = (int)$sort;
2588 return $this->children[$key];
2592 * Returns the text for this item
2595 public function get_text() {
2600 * Returns the url for this item
2601 * @return moodle_url
2603 public function get_url() {
2608 * Returns the title for this item
2611 public function get_title() {
2612 return $this->title;
2616 * Sorts and returns the children for this item
2619 public function get_children() {
2621 return $this->children;
2625 * Gets the sort order for this child
2628 public function get_sort_order() {
2633 * Gets the parent this child belong to
2634 * @return custom_menu_item
2636 public function get_parent() {
2637 return $this->parent;
2641 * Sorts the children this item has
2643 public function sort() {
2644 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2648 * Returns true if this item has any children
2651 public function has_children() {
2652 return (count($this->children) > 0);
2656 * Sets the text for the node
2657 * @param string $text
2659 public function set_text($text) {
2660 $this->text = (string)$text;
2664 * Sets the title for the node
2665 * @param string $title
2667 public function set_title($title) {
2668 $this->title = (string)$title;
2672 * Sets the url for the node
2673 * @param moodle_url $url
2675 public function set_url(moodle_url $url) {
2683 * This class is used to operate a custom menu that can be rendered for the page.
2684 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2685 * of custom_menu_item nodes that can be rendered by the core renderer.
2687 * To configure the custom menu:
2688 * Settings: Administration > Appearance > Themes > Theme settings
2690 * @copyright 2010 Sam Hemelryk
2691 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2696 class custom_menu extends custom_menu_item {
2699 * @var string The language we should render for, null disables multilang support.
2701 protected $currentlanguage = null;
2704 * Creates the custom menu
2706 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2707 * @param string $currentlanguage the current language code, null disables multilang support
2709 public function __construct($definition = '', $currentlanguage = null) {
2710 $this->currentlanguage = $currentlanguage;
2711 parent::__construct('root'); // create virtual root element of the menu
2712 if (!empty($definition)) {
2713 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2718 * Overrides the children of this custom menu. Useful when getting children
2719 * from $CFG->custommenuitems
2721 * @param array $children
2723 public function override_children(array $children) {
2724 $this->children = array();
2725 foreach ($children as $child) {
2726 if ($child instanceof custom_menu_item) {
2727 $this->children[] = $child;
2733 * Converts a string into a structured array of custom_menu_items which can
2734 * then be added to a custom menu.
2737 * text|url|title|langs
2738 * The number of hyphens at the start determines the depth of the item. The
2739 * languages are optional, comma separated list of languages the line is for.
2741 * Example structure:
2742 * First level first item|http://www.moodle.com/
2743 * -Second level first item|http://www.moodle.com/partners/
2744 * -Second level second item|http://www.moodle.com/hq/
2745 * --Third level first item|http://www.moodle.com/jobs/
2746 * -Second level third item|http://www.moodle.com/development/
2747 * First level second item|http://www.moodle.com/feedback/
2748 * First level third item
2749 * English only|http://moodle.com|English only item|en
2750 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2754 * @param string $text the menu items definition
2755 * @param string $language the language code, null disables multilang support
2758 public static function convert_text_to_menu_nodes($text, $language = null) {
2759 $lines = explode("\n", $text);
2760 $children = array();
2764 foreach ($lines as $line) {
2765 $line = trim($line);
2766 $bits = explode('|', $line, 4); // name|url|title|langs
2767 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2768 // Every item must have a name to be valid
2771 $bits[0] = ltrim($bits[0],'-');
2773 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2774 // Set the url to null
2777 // Make sure the url is a moodle url
2778 $bits[1] = new moodle_url(trim($bits[1]));
2780 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2781 // Set the title to null seeing as there isn't one
2782 $bits[2] = $bits[0];
2784 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2785 // The item is valid for all languages
2788 $itemlangs = array_map('trim', explode(',', $bits[3]));
2790 if (!empty($language) and !empty($itemlangs)) {
2791 // check that the item is intended for the current language
2792 if (!in_array($language, $itemlangs)) {
2796 // Set an incremental sort order to keep it simple.
2798 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2799 $depth = strlen($match[1]);
2800 if ($depth < $lastdepth) {
2801 $difference = $lastdepth - $depth;
2802 if ($lastdepth > 1 && $lastdepth != $difference) {
2803 $tempchild = $lastchild->get_parent();
2804 for ($i =0; $i < $difference; $i++) {
2805 $tempchild = $tempchild->get_parent();
2807 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2810 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2811 $children[] = $lastchild;
2813 } else if ($depth > $lastdepth) {
2814 $depth = $lastdepth + 1;
2815 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2818 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2819 $children[] = $lastchild;
2821 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2826 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2827 $children[] = $lastchild;
2829 $lastdepth = $depth;
2835 * Sorts two custom menu items
2837 * This function is designed to be used with the usort method
2838 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2841 * @param custom_menu_item $itema
2842 * @param custom_menu_item $itemb
2845 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2846 $itema = $itema->get_sort_order();
2847 $itemb = $itemb->get_sort_order();
2848 if ($itema == $itemb) {
2851 return ($itema > $itemb) ? +1 : -1;
2858 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2861 class tabobject implements renderable {
2862 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
2864 /** @var moodle_url|string link */
2866 /** @var string text on the tab */
2868 /** @var string title under the link, by defaul equals to text */
2870 /** @var bool whether to display a link under the tab name when it's selected */
2871 var $linkedwhenselected = false;
2872 /** @var bool whether the tab is inactive */
2873 var $inactive = false;
2874 /** @var bool indicates that this tab's child is selected */
2875 var $activated = false;
2876 /** @var bool indicates that this tab is selected */
2877 var $selected = false;
2878 /** @var array stores children tabobjects */
2879 var $subtree = array();
2880 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
2886 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
2887 * @param string|moodle_url $link
2888 * @param string $text text on the tab
2889 * @param string $title title under the link, by defaul equals to text
2890 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
2892 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
2894 $this->link = $link;
2895 $this->text = $text;
2896 $this->title = $title ? $title : $text;
2897 $this->linkedwhenselected = $linkedwhenselected;
2901 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
2903 * @param string $selected the id of the selected tab (whatever row it's on),
2904 * if null marks all tabs as unselected
2905 * @return bool whether this tab is selected or contains selected tab in its subtree
2907 protected function set_selected($selected) {
2908 if ((string)$selected === (string)$this->id) {
2909 $this->selected = true;
2910 // This tab is selected. No need to travel through subtree.
2913 foreach ($this->subtree as $subitem) {
2914 if ($subitem->set_selected($selected)) {
2915 // This tab has child that is selected. Mark it as activated. No need to check other children.
2916 $this->activated = true;
2924 * Travels through tree and finds a tab with specified id
2927 * @return tabtree|null
2929 public function find($id) {
2930 if ((string)$this->id === (string)$id) {
2933 foreach ($this->subtree as $tab) {
2934 if ($obj = $tab->find($id)) {
2942 * Allows to mark each tab's level in the tree before rendering.
2946 protected function set_level($level) {
2947 $this->level = $level;
2948 foreach ($this->subtree as $tab) {
2949 $tab->set_level($level + 1);
2957 * Example how to print a single line tabs:
2959 * new tabobject(...),
2960 * new tabobject(...)
2962 * echo $OUTPUT->tabtree($rows, $selectedid);
2964 * Multiple row tabs may not look good on some devices but if you want to use them
2965 * you can specify ->subtree for the active tabobject.
2967 * @copyright 2013 Marina Glancy
2968 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2973 class tabtree extends tabobject {
2977 * It is highly recommended to call constructor when list of tabs is already
2978 * populated, this way you ensure that selected and inactive tabs are located
2979 * and attribute level is set correctly.
2981 * @param array $tabs array of tabs, each of them may have it's own ->subtree
2982 * @param string|null $selected which tab to mark as selected, all parent tabs will
2983 * automatically be marked as activated
2984 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
2985 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
2987 public function __construct($tabs, $selected = null, $inactive = null) {
2988 $this->subtree = $tabs;
2989 if ($selected !== null) {
2990 $this->set_selected($selected);
2992 if ($inactive !== null) {
2993 if (is_array($inactive)) {
2994 foreach ($inactive as $id) {
2995 if ($tab = $this->find($id)) {
2996 $tab->inactive = true;
2999 } else if ($tab = $this->find($inactive)) {
3000 $tab->inactive = true;
3003 $this->set_level(0);