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';
514 if (empty($this->attributes['title'])) {
515 // Remove the title attribute if empty, we probably want to use the parent node's title
516 // and some browsers might overwrite it with an empty title.
517 unset($this->attributes['title']);
523 * Data structure representing an emoticon image
525 * @copyright 2010 David Mudrak
526 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
531 class pix_emoticon extends pix_icon implements renderable {
535 * @param string $pix short icon name
536 * @param string $alt alternative text
537 * @param string $component emoticon image provider
538 * @param array $attributes explicit HTML attributes
540 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
541 if (empty($attributes['class'])) {
542 $attributes['class'] = 'emoticon';
544 parent::__construct($pix, $alt, $component, $attributes);
549 * Data structure representing a simple form with only one button.
551 * @copyright 2009 Petr Skoda
552 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
557 class single_button implements renderable {
560 * @var moodle_url Target url
565 * @var string Button label
570 * @var string Form submit method post or get
572 var $method = 'post';
575 * @var string Wrapping div class
577 var $class = 'singlebutton';
580 * @var bool True if button disabled, false if normal
582 var $disabled = false;
585 * @var string Button tooltip
590 * @var string Form id
595 * @var array List of attached actions
597 var $actions = array();
601 * @param moodle_url $url
602 * @param string $label button text
603 * @param string $method get or post submit method
605 public function __construct(moodle_url $url, $label, $method='post') {
606 $this->url = clone($url);
607 $this->label = $label;
608 $this->method = $method;
612 * Shortcut for adding a JS confirm dialog when the button is clicked.
613 * The message must be a yes/no question.
615 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
617 public function add_confirm_action($confirmmessage) {
618 $this->add_action(new confirm_action($confirmmessage));
622 * Add action to the button.
623 * @param component_action $action
625 public function add_action(component_action $action) {
626 $this->actions[] = $action;
632 * Simple form with just one select field that gets submitted automatically.
634 * If JS not enabled small go button is printed too.
636 * @copyright 2009 Petr Skoda
637 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
642 class single_select implements renderable {
645 * @var moodle_url Target url - includes hidden fields
650 * @var string Name of the select element.
655 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
656 * it is also possible to specify optgroup as complex label array ex.:
657 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
658 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
663 * @var string Selected option
668 * @var array Nothing selected
673 * @var array Extra select field attributes
675 var $attributes = array();
678 * @var string Button label
683 * @var array Button label's attributes
685 var $labelattributes = array();
688 * @var string Form submit method post or get
693 * @var string Wrapping div class
695 var $class = 'singleselect';
698 * @var bool True if button disabled, false if normal
700 var $disabled = false;
703 * @var string Button tooltip
708 * @var string Form id
713 * @var array List of attached actions
715 var $helpicon = null;
719 * @param moodle_url $url form action target, includes hidden fields
720 * @param string $name name of selection field - the changing parameter in url
721 * @param array $options list of options
722 * @param string $selected selected element
723 * @param array $nothing
724 * @param string $formid
726 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
729 $this->options = $options;
730 $this->selected = $selected;
731 $this->nothing = $nothing;
732 $this->formid = $formid;
736 * Shortcut for adding a JS confirm dialog when the button is clicked.
737 * The message must be a yes/no question.
739 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
741 public function add_confirm_action($confirmmessage) {
742 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
746 * Add action to the button.
748 * @param component_action $action
750 public function add_action(component_action $action) {
751 $this->actions[] = $action;
757 * @deprecated since Moodle 2.0
759 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
760 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
766 * @param string $identifier The keyword that defines a help page
767 * @param string $component
769 public function set_help_icon($identifier, $component = 'moodle') {
770 $this->helpicon = new help_icon($identifier, $component);
774 * Sets select's label
776 * @param string $label
777 * @param array $attributes (optional)
779 public function set_label($label, $attributes = array()) {
780 $this->label = $label;
781 $this->labelattributes = $attributes;
787 * Simple URL selection widget description.
789 * @copyright 2009 Petr Skoda
790 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
795 class url_select implements renderable {
797 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
798 * it is also possible to specify optgroup as complex label array ex.:
799 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
800 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
805 * @var string Selected option
810 * @var array Nothing selected
815 * @var array Extra select field attributes
817 var $attributes = array();
820 * @var string Button label
825 * @var array Button label's attributes
827 var $labelattributes = array();
830 * @var string Wrapping div class
832 var $class = 'urlselect';
835 * @var bool True if button disabled, false if normal
837 var $disabled = false;
840 * @var string Button tooltip
845 * @var string Form id
850 * @var array List of attached actions
852 var $helpicon = null;
855 * @var string If set, makes button visible with given name for button
857 var $showbutton = null;
861 * @param array $urls list of options
862 * @param string $selected selected element
863 * @param array $nothing
864 * @param string $formid
865 * @param string $showbutton Set to text of button if it should be visible
866 * or null if it should be hidden (hidden version always has text 'go')
868 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
870 $this->selected = $selected;
871 $this->nothing = $nothing;
872 $this->formid = $formid;
873 $this->showbutton = $showbutton;
879 * @deprecated since Moodle 2.0
881 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
882 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
888 * @param string $identifier The keyword that defines a help page
889 * @param string $component
891 public function set_help_icon($identifier, $component = 'moodle') {
892 $this->helpicon = new help_icon($identifier, $component);
896 * Sets select's label
898 * @param string $label
899 * @param array $attributes (optional)
901 public function set_label($label, $attributes = array()) {
902 $this->label = $label;
903 $this->labelattributes = $attributes;
908 * Data structure describing html link with special action attached.
910 * @copyright 2010 Petr Skoda
911 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
916 class action_link implements renderable {
919 * @var moodle_url Href url
924 * @var string Link text HTML fragment
929 * @var array HTML attributes
934 * @var array List of actions attached to link
939 * @var pix_icon Optional pix icon to render with the link
945 * @param moodle_url $url
946 * @param string $text HTML fragment
947 * @param component_action $action
948 * @param array $attributes associative array of html link attributes + disabled
949 * @param pix_icon $icon optional pix_icon to render with the link text
951 public function __construct(moodle_url $url,
953 component_action $action=null,
954 array $attributes=null,
955 pix_icon $icon=null) {
956 $this->url = clone($url);
958 $this->attributes = (array)$attributes;
960 $this->add_action($action);
966 * Add action to the link.
968 * @param component_action $action
970 public function add_action(component_action $action) {
971 $this->actions[] = $action;
975 * Adds a CSS class to this action link object
976 * @param string $class
978 public function add_class($class) {
979 if (empty($this->attributes['class'])) {
980 $this->attributes['class'] = $class;
982 $this->attributes['class'] .= ' ' . $class;
987 * Returns true if the specified class has been added to this link.
988 * @param string $class
991 public function has_class($class) {
992 return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
997 * Simple html output class
999 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1000 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1008 * Outputs a tag with attributes and contents
1010 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1011 * @param string $contents What goes between the opening and closing tags
1012 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1013 * @return string HTML fragment
1015 public static function tag($tagname, $contents, array $attributes = null) {
1016 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1020 * Outputs an opening tag with attributes
1022 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1023 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1024 * @return string HTML fragment
1026 public static function start_tag($tagname, array $attributes = null) {
1027 return '<' . $tagname . self::attributes($attributes) . '>';
1031 * Outputs a closing tag
1033 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1034 * @return string HTML fragment
1036 public static function end_tag($tagname) {
1037 return '</' . $tagname . '>';
1041 * Outputs an empty tag with attributes
1043 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1044 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1045 * @return string HTML fragment
1047 public static function empty_tag($tagname, array $attributes = null) {
1048 return '<' . $tagname . self::attributes($attributes) . ' />';
1052 * Outputs a tag, but only if the contents are not empty
1054 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1055 * @param string $contents What goes between the opening and closing tags
1056 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1057 * @return string HTML fragment
1059 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1060 if ($contents === '' || is_null($contents)) {
1063 return self::tag($tagname, $contents, $attributes);
1067 * Outputs a HTML attribute and value
1069 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1070 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1071 * @return string HTML fragment
1073 public static function attribute($name, $value) {
1074 if ($value instanceof moodle_url) {
1075 return ' ' . $name . '="' . $value->out() . '"';
1078 // special case, we do not want these in output
1079 if ($value === null) {
1083 // no sloppy trimming here!
1084 return ' ' . $name . '="' . s($value) . '"';
1088 * Outputs a list of HTML attributes and values
1090 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1091 * The values will be escaped with {@link s()}
1092 * @return string HTML fragment
1094 public static function attributes(array $attributes = null) {
1095 $attributes = (array)$attributes;
1097 foreach ($attributes as $name => $value) {
1098 $output .= self::attribute($name, $value);
1104 * Generates a simple image tag with attributes.
1106 * @param string $src The source of image
1107 * @param string $alt The alternate text for image
1108 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1109 * @return string HTML fragment
1111 public static function img($src, $alt, array $attributes = null) {
1112 $attributes = (array)$attributes;
1113 $attributes['src'] = $src;
1114 $attributes['alt'] = $alt;
1116 return self::empty_tag('img', $attributes);
1120 * Generates random html element id.
1122 * @staticvar int $counter
1123 * @staticvar type $uniq
1124 * @param string $base A string fragment that will be included in the random ID.
1125 * @return string A unique ID
1127 public static function random_id($base='random') {
1128 static $counter = 0;
1131 if (!isset($uniq)) {
1136 return $base.$uniq.$counter;
1140 * Generates a simple html link
1142 * @param string|moodle_url $url The URL
1143 * @param string $text The text
1144 * @param array $attributes HTML attributes
1145 * @return string HTML fragment
1147 public static function link($url, $text, array $attributes = null) {
1148 $attributes = (array)$attributes;
1149 $attributes['href'] = $url;
1150 return self::tag('a', $text, $attributes);
1154 * Generates a simple checkbox with optional label
1156 * @param string $name The name of the checkbox
1157 * @param string $value The value of the checkbox
1158 * @param bool $checked Whether the checkbox is checked
1159 * @param string $label The label for the checkbox
1160 * @param array $attributes Any attributes to apply to the checkbox
1161 * @return string html fragment
1163 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1164 $attributes = (array)$attributes;
1167 if ($label !== '' and !is_null($label)) {
1168 if (empty($attributes['id'])) {
1169 $attributes['id'] = self::random_id('checkbox_');
1172 $attributes['type'] = 'checkbox';
1173 $attributes['value'] = $value;
1174 $attributes['name'] = $name;
1175 $attributes['checked'] = $checked ? 'checked' : null;
1177 $output .= self::empty_tag('input', $attributes);
1179 if ($label !== '' and !is_null($label)) {
1180 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1187 * Generates a simple select yes/no form field
1189 * @param string $name name of select element
1190 * @param bool $selected
1191 * @param array $attributes - html select element attributes
1192 * @return string HTML fragment
1194 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1195 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1196 return self::select($options, $name, $selected, null, $attributes);
1200 * Generates a simple select form field
1202 * @param array $options associative array value=>label ex.:
1203 * array(1=>'One, 2=>Two)
1204 * it is also possible to specify optgroup as complex label array ex.:
1205 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1206 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1207 * @param string $name name of select element
1208 * @param string|array $selected value or array of values depending on multiple attribute
1209 * @param array|bool $nothing add nothing selected option, or false of not added
1210 * @param array $attributes html select element attributes
1211 * @return string HTML fragment
1213 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1214 $attributes = (array)$attributes;
1215 if (is_array($nothing)) {
1216 foreach ($nothing as $k=>$v) {
1217 if ($v === 'choose' or $v === 'choosedots') {
1218 $nothing[$k] = get_string('choosedots');
1221 $options = $nothing + $options; // keep keys, do not override
1223 } else if (is_string($nothing) and $nothing !== '') {
1225 $options = array(''=>$nothing) + $options;
1228 // we may accept more values if multiple attribute specified
1229 $selected = (array)$selected;
1230 foreach ($selected as $k=>$v) {
1231 $selected[$k] = (string)$v;
1234 if (!isset($attributes['id'])) {
1236 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1237 $id = str_replace('[', '', $id);
1238 $id = str_replace(']', '', $id);
1239 $attributes['id'] = $id;
1242 if (!isset($attributes['class'])) {
1243 $class = 'menu'.$name;
1244 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1245 $class = str_replace('[', '', $class);
1246 $class = str_replace(']', '', $class);
1247 $attributes['class'] = $class;
1249 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
1251 $attributes['name'] = $name;
1253 if (!empty($attributes['disabled'])) {
1254 $attributes['disabled'] = 'disabled';
1256 unset($attributes['disabled']);
1260 foreach ($options as $value=>$label) {
1261 if (is_array($label)) {
1262 // ignore key, it just has to be unique
1263 $output .= self::select_optgroup(key($label), current($label), $selected);
1265 $output .= self::select_option($label, $value, $selected);
1268 return self::tag('select', $output, $attributes);
1272 * Returns HTML to display a select box option.
1274 * @param string $label The label to display as the option.
1275 * @param string|int $value The value the option represents
1276 * @param array $selected An array of selected options
1277 * @return string HTML fragment
1279 private static function select_option($label, $value, array $selected) {
1280 $attributes = array();
1281 $value = (string)$value;
1282 if (in_array($value, $selected, true)) {
1283 $attributes['selected'] = 'selected';
1285 $attributes['value'] = $value;
1286 return self::tag('option', $label, $attributes);
1290 * Returns HTML to display a select box option group.
1292 * @param string $groupname The label to use for the group
1293 * @param array $options The options in the group
1294 * @param array $selected An array of selected values.
1295 * @return string HTML fragment.
1297 private static function select_optgroup($groupname, $options, array $selected) {
1298 if (empty($options)) {
1301 $attributes = array('label'=>$groupname);
1303 foreach ($options as $value=>$label) {
1304 $output .= self::select_option($label, $value, $selected);
1306 return self::tag('optgroup', $output, $attributes);
1310 * This is a shortcut for making an hour selector menu.
1312 * @param string $type The type of selector (years, months, days, hours, minutes)
1313 * @param string $name fieldname
1314 * @param int $currenttime A default timestamp in GMT
1315 * @param int $step minute spacing
1316 * @param array $attributes - html select element attributes
1317 * @return HTML fragment
1319 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1320 if (!$currenttime) {
1321 $currenttime = time();
1323 $currentdate = usergetdate($currenttime);
1324 $userdatetype = $type;
1325 $timeunits = array();
1329 for ($i=1970; $i<=2020; $i++) {
1330 $timeunits[$i] = $i;
1332 $userdatetype = 'year';
1335 for ($i=1; $i<=12; $i++) {
1336 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1338 $userdatetype = 'month';
1339 $currentdate['month'] = (int)$currentdate['mon'];
1342 for ($i=1; $i<=31; $i++) {
1343 $timeunits[$i] = $i;
1345 $userdatetype = 'mday';
1348 for ($i=0; $i<=23; $i++) {
1349 $timeunits[$i] = sprintf("%02d",$i);
1354 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1357 for ($i=0; $i<=59; $i+=$step) {
1358 $timeunits[$i] = sprintf("%02d",$i);
1362 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1365 if (empty($attributes['id'])) {
1366 $attributes['id'] = self::random_id('ts_');
1368 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, $attributes);
1369 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1371 return $label.$timerselector;
1375 * Shortcut for quick making of lists
1377 * Note: 'list' is a reserved keyword ;-)
1379 * @param array $items
1380 * @param array $attributes
1381 * @param string $tag ul or ol
1384 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1385 $output = html_writer::start_tag($tag, $attributes)."\n";
1386 foreach ($items as $item) {
1387 $output .= html_writer::tag('li', $item)."\n";
1389 $output .= html_writer::end_tag($tag);
1394 * Returns hidden input fields created from url parameters.
1396 * @param moodle_url $url
1397 * @param array $exclude list of excluded parameters
1398 * @return string HTML fragment
1400 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1401 $exclude = (array)$exclude;
1402 $params = $url->params();
1403 foreach ($exclude as $key) {
1404 unset($params[$key]);
1408 foreach ($params as $key => $value) {
1409 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1410 $output .= self::empty_tag('input', $attributes)."\n";
1416 * Generate a script tag containing the the specified code.
1418 * @param string $jscode the JavaScript code
1419 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
1420 * @return string HTML, the code wrapped in <script> tags.
1422 public static function script($jscode, $url=null) {
1424 $attributes = array('type'=>'text/javascript');
1425 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1428 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1429 return self::tag('script', '', $attributes) . "\n";
1437 * Renders HTML table
1439 * This method may modify the passed instance by adding some default properties if they are not set yet.
1440 * If this is not what you want, you should make a full clone of your data before passing them to this
1441 * method. In most cases this is not an issue at all so we do not clone by default for performance
1442 * and memory consumption reasons.
1444 * Please do not use .r0/.r1 for css, as they will be removed in Moodle 2.9.
1445 * @todo MDL-43902 , remove r0 and r1 from tr classes.
1447 * @param html_table $table data to be rendered
1448 * @return string HTML code
1450 public static function table(html_table $table) {
1451 // prepare table data and populate missing properties with reasonable defaults
1452 if (!empty($table->align)) {
1453 foreach ($table->align as $key => $aa) {
1455 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1457 $table->align[$key] = null;
1461 if (!empty($table->size)) {
1462 foreach ($table->size as $key => $ss) {
1464 $table->size[$key] = 'width:'. $ss .';';
1466 $table->size[$key] = null;
1470 if (!empty($table->wrap)) {
1471 foreach ($table->wrap as $key => $ww) {
1473 $table->wrap[$key] = 'white-space:nowrap;';
1475 $table->wrap[$key] = '';
1479 if (!empty($table->head)) {
1480 foreach ($table->head as $key => $val) {
1481 if (!isset($table->align[$key])) {
1482 $table->align[$key] = null;
1484 if (!isset($table->size[$key])) {
1485 $table->size[$key] = null;
1487 if (!isset($table->wrap[$key])) {
1488 $table->wrap[$key] = null;
1493 if (empty($table->attributes['class'])) {
1494 $table->attributes['class'] = 'generaltable';
1496 if (!empty($table->tablealign)) {
1497 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1500 // explicitly assigned properties override those defined via $table->attributes
1501 $table->attributes['class'] = trim($table->attributes['class']);
1502 $attributes = array_merge($table->attributes, array(
1504 'width' => $table->width,
1505 'summary' => $table->summary,
1506 'cellpadding' => $table->cellpadding,
1507 'cellspacing' => $table->cellspacing,
1509 $output = html_writer::start_tag('table', $attributes) . "\n";
1513 if (!empty($table->head)) {
1514 $countcols = count($table->head);
1516 $output .= html_writer::start_tag('thead', array()) . "\n";
1517 $output .= html_writer::start_tag('tr', array()) . "\n";
1518 $keys = array_keys($table->head);
1519 $lastkey = end($keys);
1521 foreach ($table->head as $key => $heading) {
1522 // Convert plain string headings into html_table_cell objects
1523 if (!($heading instanceof html_table_cell)) {
1524 $headingtext = $heading;
1525 $heading = new html_table_cell();
1526 $heading->text = $headingtext;
1527 $heading->header = true;
1530 if ($heading->header !== false) {
1531 $heading->header = true;
1534 if ($heading->header && empty($heading->scope)) {
1535 $heading->scope = 'col';
1538 $heading->attributes['class'] .= ' header c' . $key;
1539 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1540 $heading->colspan = $table->headspan[$key];
1541 $countcols += $table->headspan[$key] - 1;
1544 if ($key == $lastkey) {
1545 $heading->attributes['class'] .= ' lastcol';
1547 if (isset($table->colclasses[$key])) {
1548 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1550 $heading->attributes['class'] = trim($heading->attributes['class']);
1551 $attributes = array_merge($heading->attributes, array(
1552 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1553 'scope' => $heading->scope,
1554 'colspan' => $heading->colspan,
1558 if ($heading->header === true) {
1561 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1563 $output .= html_writer::end_tag('tr') . "\n";
1564 $output .= html_writer::end_tag('thead') . "\n";
1566 if (empty($table->data)) {
1567 // For valid XHTML strict every table must contain either a valid tr
1568 // or a valid tbody... both of which must contain a valid td
1569 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1570 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1571 $output .= html_writer::end_tag('tbody');
1575 if (!empty($table->data)) {
1577 $keys = array_keys($table->data);
1578 $lastrowkey = end($keys);
1579 $output .= html_writer::start_tag('tbody', array());
1581 foreach ($table->data as $key => $row) {
1582 if (($row === 'hr') && ($countcols)) {
1583 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1585 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1586 if (!($row instanceof html_table_row)) {
1587 $newrow = new html_table_row();
1589 foreach ($row as $cell) {
1590 if (!($cell instanceof html_table_cell)) {
1591 $cell = new html_table_cell($cell);
1593 $newrow->cells[] = $cell;
1598 $oddeven = $oddeven ? 0 : 1;
1599 if (isset($table->rowclasses[$key])) {
1600 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1603 $row->attributes['class'] .= ' r' . $oddeven;
1604 if ($key == $lastrowkey) {
1605 $row->attributes['class'] .= ' lastrow';
1608 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1609 $keys2 = array_keys($row->cells);
1610 $lastkey = end($keys2);
1612 $gotlastkey = false; //flag for sanity checking
1613 foreach ($row->cells as $key => $cell) {
1615 //This should never happen. Why do we have a cell after the last cell?
1616 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1619 if (!($cell instanceof html_table_cell)) {
1620 $mycell = new html_table_cell();
1621 $mycell->text = $cell;
1625 if (($cell->header === true) && empty($cell->scope)) {
1626 $cell->scope = 'row';
1629 if (isset($table->colclasses[$key])) {
1630 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1633 $cell->attributes['class'] .= ' cell c' . $key;
1634 if ($key == $lastkey) {
1635 $cell->attributes['class'] .= ' lastcol';
1639 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1640 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1641 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1642 $cell->attributes['class'] = trim($cell->attributes['class']);
1643 $tdattributes = array_merge($cell->attributes, array(
1644 'style' => $tdstyle . $cell->style,
1645 'colspan' => $cell->colspan,
1646 'rowspan' => $cell->rowspan,
1648 'abbr' => $cell->abbr,
1649 'scope' => $cell->scope,
1652 if ($cell->header === true) {
1655 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1658 $output .= html_writer::end_tag('tr') . "\n";
1660 $output .= html_writer::end_tag('tbody') . "\n";
1662 $output .= html_writer::end_tag('table') . "\n";
1668 * Renders form element label
1670 * By default, the label is suffixed with a label separator defined in the
1671 * current language pack (colon by default in the English lang pack).
1672 * Adding the colon can be explicitly disabled if needed. Label separators
1673 * are put outside the label tag itself so they are not read by
1674 * screenreaders (accessibility).
1676 * Parameter $for explicitly associates the label with a form control. When
1677 * set, the value of this attribute must be the same as the value of
1678 * the id attribute of the form control in the same document. When null,
1679 * the label being defined is associated with the control inside the label
1682 * @param string $text content of the label tag
1683 * @param string|null $for id of the element this label is associated with, null for no association
1684 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1685 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1686 * @return string HTML of the label element
1688 public static function label($text, $for, $colonize = true, array $attributes=array()) {
1689 if (!is_null($for)) {
1690 $attributes = array_merge($attributes, array('for' => $for));
1692 $text = trim($text);
1693 $label = self::tag('label', $text, $attributes);
1695 // TODO MDL-12192 $colonize disabled for now yet
1696 // if (!empty($text) and $colonize) {
1697 // // the $text may end with the colon already, though it is bad string definition style
1698 // $colon = get_string('labelsep', 'langconfig');
1699 // if (!empty($colon)) {
1700 // $trimmed = trim($colon);
1701 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1702 // //debugging('The label text should not end with colon or other label separator,
1703 // // please fix the string definition.', DEBUG_DEVELOPER);
1705 // $label .= $colon;
1714 * Combines a class parameter with other attributes. Aids in code reduction
1715 * because the class parameter is very frequently used.
1717 * If the class attribute is specified both in the attributes and in the
1718 * class parameter, the two values are combined with a space between.
1720 * @param string $class Optional CSS class (or classes as space-separated list)
1721 * @param array $attributes Optional other attributes as array
1722 * @return array Attributes (or null if still none)
1724 private static function add_class($class = '', array $attributes = null) {
1725 if ($class !== '') {
1726 $classattribute = array('class' => $class);
1728 if (array_key_exists('class', $attributes)) {
1729 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
1731 $attributes = $classattribute + $attributes;
1734 $attributes = $classattribute;
1741 * Creates a <div> tag. (Shortcut function.)
1743 * @param string $content HTML content of tag
1744 * @param string $class Optional CSS class (or classes as space-separated list)
1745 * @param array $attributes Optional other attributes as array
1746 * @return string HTML code for div
1748 public static function div($content, $class = '', array $attributes = null) {
1749 return self::tag('div', $content, self::add_class($class, $attributes));
1753 * Starts a <div> tag. (Shortcut function.)
1755 * @param string $class Optional CSS class (or classes as space-separated list)
1756 * @param array $attributes Optional other attributes as array
1757 * @return string HTML code for open div tag
1759 public static function start_div($class = '', array $attributes = null) {
1760 return self::start_tag('div', self::add_class($class, $attributes));
1764 * Ends a <div> tag. (Shortcut function.)
1766 * @return string HTML code for close div tag
1768 public static function end_div() {
1769 return self::end_tag('div');
1773 * Creates a <span> tag. (Shortcut function.)
1775 * @param string $content HTML content of tag
1776 * @param string $class Optional CSS class (or classes as space-separated list)
1777 * @param array $attributes Optional other attributes as array
1778 * @return string HTML code for span
1780 public static function span($content, $class = '', array $attributes = null) {
1781 return self::tag('span', $content, self::add_class($class, $attributes));
1785 * Starts a <span> tag. (Shortcut function.)
1787 * @param string $class Optional CSS class (or classes as space-separated list)
1788 * @param array $attributes Optional other attributes as array
1789 * @return string HTML code for open span tag
1791 public static function start_span($class = '', array $attributes = null) {
1792 return self::start_tag('span', self::add_class($class, $attributes));
1796 * Ends a <span> tag. (Shortcut function.)
1798 * @return string HTML code for close span tag
1800 public static function end_span() {
1801 return self::end_tag('span');
1806 * Simple javascript output class
1808 * @copyright 2010 Petr Skoda
1809 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1817 * Returns javascript code calling the function
1819 * @param string $function function name, can be complex like Y.Event.purgeElement
1820 * @param array $arguments parameters
1821 * @param int $delay execution delay in seconds
1822 * @return string JS code fragment
1824 public static function function_call($function, array $arguments = null, $delay=0) {
1826 $arguments = array_map('json_encode', convert_to_array($arguments));
1827 $arguments = implode(', ', $arguments);
1831 $js = "$function($arguments);";
1834 $delay = $delay * 1000; // in miliseconds
1835 $js = "setTimeout(function() { $js }, $delay);";
1841 * Special function which adds Y as first argument of function call.
1843 * @param string $function The function to call
1844 * @param array $extraarguments Any arguments to pass to it
1845 * @return string Some JS code
1847 public static function function_call_with_Y($function, array $extraarguments = null) {
1848 if ($extraarguments) {
1849 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1850 $arguments = 'Y, ' . implode(', ', $extraarguments);
1854 return "$function($arguments);\n";
1858 * Returns JavaScript code to initialise a new object
1860 * @param string $var If it is null then no var is assigned the new object.
1861 * @param string $class The class to initialise an object for.
1862 * @param array $arguments An array of args to pass to the init method.
1863 * @param array $requirements Any modules required for this class.
1864 * @param int $delay The delay before initialisation. 0 = no delay.
1865 * @return string Some JS code
1867 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1868 if (is_array($arguments)) {
1869 $arguments = array_map('json_encode', convert_to_array($arguments));
1870 $arguments = implode(', ', $arguments);
1873 if ($var === null) {
1874 $js = "new $class(Y, $arguments);";
1875 } else if (strpos($var, '.')!==false) {
1876 $js = "$var = new $class(Y, $arguments);";
1878 $js = "var $var = new $class(Y, $arguments);";
1882 $delay = $delay * 1000; // in miliseconds
1883 $js = "setTimeout(function() { $js }, $delay);";
1886 if (count($requirements) > 0) {
1887 $requirements = implode("', '", $requirements);
1888 $js = "Y.use('$requirements', function(Y){ $js });";
1894 * Returns code setting value to variable
1896 * @param string $name
1897 * @param mixed $value json serialised value
1898 * @param bool $usevar add var definition, ignored for nested properties
1899 * @return string JS code fragment
1901 public static function set_variable($name, $value, $usevar = true) {
1905 if (strpos($name, '.')) {
1912 $output .= "$name = ".json_encode($value).";";
1918 * Writes event handler attaching code
1920 * @param array|string $selector standard YUI selector for elements, may be
1921 * array or string, element id is in the form "#idvalue"
1922 * @param string $event A valid DOM event (click, mousedown, change etc.)
1923 * @param string $function The name of the function to call
1924 * @param array $arguments An optional array of argument parameters to pass to the function
1925 * @return string JS code fragment
1927 public static function event_handler($selector, $event, $function, array $arguments = null) {
1928 $selector = json_encode($selector);
1929 $output = "Y.on('$event', $function, $selector, null";
1930 if (!empty($arguments)) {
1931 $output .= ', ' . json_encode($arguments);
1933 return $output . ");\n";
1938 * Holds all the information required to render a <table> by {@link core_renderer::table()}
1941 * $t = new html_table();
1942 * ... // set various properties of the object $t as described below
1943 * echo html_writer::table($t);
1945 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1946 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1954 * @var string Value to use for the id attribute of the table
1959 * @var array Attributes of HTML attributes for the <table> element
1961 public $attributes = array();
1964 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
1965 * For more control over the rendering of the headers, an array of html_table_cell objects
1966 * can be passed instead of an array of strings.
1969 * $t->head = array('Student', 'Grade');
1974 * @var array An array that can be used to make a heading span multiple columns.
1975 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1976 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
1979 * $t->headspan = array(2,1);
1984 * @var array An array of column alignments.
1985 * The value is used as CSS 'text-align' property. Therefore, possible
1986 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1987 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1989 * Examples of usage:
1990 * $t->align = array(null, 'right');
1992 * $t->align[1] = 'right';
1997 * @var array The value is used as CSS 'size' property.
1999 * Examples of usage:
2000 * $t->size = array('50%', '50%');
2002 * $t->size[1] = '120px';
2007 * @var array An array of wrapping information.
2008 * The only possible value is 'nowrap' that sets the
2009 * CSS property 'white-space' to the value 'nowrap' in the given column.
2012 * $t->wrap = array(null, 'nowrap');
2017 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2018 * $head specified, the string 'hr' (for horizontal ruler) can be used
2019 * instead of an array of cells data resulting in a divider rendered.
2021 * Example of usage with array of arrays:
2022 * $row1 = array('Harry Potter', '76 %');
2023 * $row2 = array('Hermione Granger', '100 %');
2024 * $t->data = array($row1, $row2);
2026 * Example with array of html_table_row objects: (used for more fine-grained control)
2027 * $cell1 = new html_table_cell();
2028 * $cell1->text = 'Harry Potter';
2029 * $cell1->colspan = 2;
2030 * $row1 = new html_table_row();
2031 * $row1->cells[] = $cell1;
2032 * $cell2 = new html_table_cell();
2033 * $cell2->text = 'Hermione Granger';
2034 * $cell3 = new html_table_cell();
2035 * $cell3->text = '100 %';
2036 * $row2 = new html_table_row();
2037 * $row2->cells = array($cell2, $cell3);
2038 * $t->data = array($row1, $row2);
2043 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2044 * @var string Width of the table, percentage of the page preferred.
2046 public $width = null;
2049 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2050 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2052 public $tablealign = null;
2055 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2056 * @var int Padding on each cell, in pixels
2058 public $cellpadding = null;
2061 * @var int Spacing between cells, in pixels
2062 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2064 public $cellspacing = null;
2067 * @var array Array of classes to add to particular rows, space-separated string.
2068 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
2069 * respectively. Class 'lastrow' is added automatically for the last row
2073 * $t->rowclasses[9] = 'tenth'
2078 * @var array An array of classes to add to every cell in a particular column,
2079 * space-separated string. Class 'cell' is added automatically by the renderer.
2080 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2081 * respectively. Class 'lastcol' is added automatically for all last cells
2085 * $t->colclasses = array(null, 'grade');
2090 * @var string Description of the contents for screen readers.
2097 public function __construct() {
2098 $this->attributes['class'] = '';
2103 * Component representing a table row.
2105 * @copyright 2009 Nicolas Connault
2106 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2111 class html_table_row {
2114 * @var string Value to use for the id attribute of the row.
2119 * @var array Array of html_table_cell objects
2121 public $cells = array();
2124 * @var string Value to use for the style attribute of the table row
2126 public $style = null;
2129 * @var array Attributes of additional HTML attributes for the <tr> element
2131 public $attributes = array();
2135 * @param array $cells
2137 public function __construct(array $cells=null) {
2138 $this->attributes['class'] = '';
2139 $cells = (array)$cells;
2140 foreach ($cells as $cell) {
2141 if ($cell instanceof html_table_cell) {
2142 $this->cells[] = $cell;
2144 $this->cells[] = new html_table_cell($cell);
2151 * Component representing a table cell.
2153 * @copyright 2009 Nicolas Connault
2154 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2159 class html_table_cell {
2162 * @var string Value to use for the id attribute of the cell.
2167 * @var string The contents of the cell.
2172 * @var string Abbreviated version of the contents of the cell.
2174 public $abbr = null;
2177 * @var int Number of columns this cell should span.
2179 public $colspan = null;
2182 * @var int Number of rows this cell should span.
2184 public $rowspan = null;
2187 * @var string Defines a way to associate header cells and data cells in a table.
2189 public $scope = null;
2192 * @var bool Whether or not this cell is a header cell.
2194 public $header = null;
2197 * @var string Value to use for the style attribute of the table cell
2199 public $style = null;
2202 * @var array Attributes of additional HTML attributes for the <td> element
2204 public $attributes = array();
2207 * Constructs a table cell
2209 * @param string $text
2211 public function __construct($text = null) {
2212 $this->text = $text;
2213 $this->attributes['class'] = '';
2218 * Component representing a paging bar.
2220 * @copyright 2009 Nicolas Connault
2221 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2226 class paging_bar implements renderable {
2229 * @var int The maximum number of pagelinks to display.
2231 public $maxdisplay = 18;
2234 * @var int The total number of entries to be pages through..
2239 * @var int The page you are currently viewing.
2244 * @var int The number of entries that should be shown per page.
2249 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2250 * an equals sign and the page number.
2251 * If this is a moodle_url object then the pagevar param will be replaced by
2252 * the page no, for each page.
2257 * @var string This is the variable name that you use for the pagenumber in your
2258 * code (ie. 'tablepage', 'blogpage', etc)
2263 * @var string A HTML link representing the "previous" page.
2265 public $previouslink = null;
2268 * @var string A HTML link representing the "next" page.
2270 public $nextlink = null;
2273 * @var string A HTML link representing the first page.
2275 public $firstlink = null;
2278 * @var string A HTML link representing the last page.
2280 public $lastlink = null;
2283 * @var array An array of strings. One of them is just a string: the current page
2285 public $pagelinks = array();
2288 * Constructor paging_bar with only the required params.
2290 * @param int $totalcount The total number of entries available to be paged through
2291 * @param int $page The page you are currently viewing
2292 * @param int $perpage The number of entries that should be shown per page
2293 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2294 * @param string $pagevar name of page parameter that holds the page number
2296 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2297 $this->totalcount = $totalcount;
2298 $this->page = $page;
2299 $this->perpage = $perpage;
2300 $this->baseurl = $baseurl;
2301 $this->pagevar = $pagevar;
2305 * Prepares the paging bar for output.
2307 * This method validates the arguments set up for the paging bar and then
2308 * produces fragments of HTML to assist display later on.
2310 * @param renderer_base $output
2311 * @param moodle_page $page
2312 * @param string $target
2313 * @throws coding_exception
2315 public function prepare(renderer_base $output, moodle_page $page, $target) {
2316 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2317 throw new coding_exception('paging_bar requires a totalcount value.');
2319 if (!isset($this->page) || is_null($this->page)) {
2320 throw new coding_exception('paging_bar requires a page value.');
2322 if (empty($this->perpage)) {
2323 throw new coding_exception('paging_bar requires a perpage value.');
2325 if (empty($this->baseurl)) {
2326 throw new coding_exception('paging_bar requires a baseurl value.');
2329 if ($this->totalcount > $this->perpage) {
2330 $pagenum = $this->page - 1;
2332 if ($this->page > 0) {
2333 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2336 if ($this->perpage > 0) {
2337 $lastpage = ceil($this->totalcount / $this->perpage);
2342 if ($this->page > round(($this->maxdisplay/3)*2)) {
2343 $currpage = $this->page - round($this->maxdisplay/3);
2345 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2350 $displaycount = $displaypage = 0;
2352 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2353 $displaypage = $currpage + 1;
2355 if ($this->page == $currpage) {
2356 $this->pagelinks[] = $displaypage;
2358 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2359 $this->pagelinks[] = $pagelink;
2366 if ($currpage < $lastpage) {
2367 $lastpageactual = $lastpage - 1;
2368 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2371 $pagenum = $this->page + 1;
2373 if ($pagenum != $displaypage) {
2374 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2381 * This class represents how a block appears on a page.
2383 * During output, each block instance is asked to return a block_contents object,
2384 * those are then passed to the $OUTPUT->block function for display.
2386 * contents should probably be generated using a moodle_block_..._renderer.
2388 * Other block-like things that need to appear on the page, for example the
2389 * add new block UI, are also represented as block_contents objects.
2391 * @copyright 2009 Tim Hunt
2392 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2397 class block_contents {
2399 /** Used when the block cannot be collapsed **/
2400 const NOT_HIDEABLE = 0;
2402 /** Used when the block can be collapsed but currently is not **/
2405 /** Used when the block has been collapsed **/
2409 * @var int Used to set $skipid.
2411 protected static $idcounter = 1;
2414 * @var int All the blocks (or things that look like blocks) printed on
2415 * a page are given a unique number that can be used to construct id="" attributes.
2416 * This is set automatically be the {@link prepare()} method.
2417 * Do not try to set it manually.
2422 * @var int If this is the contents of a real block, this should be set
2423 * to the block_instance.id. Otherwise this should be set to 0.
2425 public $blockinstanceid = 0;
2428 * @var int If this is a real block instance, and there is a corresponding
2429 * block_position.id for the block on this page, this should be set to that id.
2430 * Otherwise it should be 0.
2432 public $blockpositionid = 0;
2435 * @var array An array of attribute => value pairs that are put on the outer div of this
2436 * block. {@link $id} and {@link $classes} attributes should be set separately.
2441 * @var string The title of this block. If this came from user input, it should already
2442 * have had format_string() processing done on it. This will be output inside
2443 * <h2> tags. Please do not cause invalid XHTML.
2448 * @var string The label to use when the block does not, or will not have a visible title.
2449 * You should never set this as well as title... it will just be ignored.
2451 public $arialabel = '';
2454 * @var string HTML for the content
2456 public $content = '';
2459 * @var array An alternative to $content, it you want a list of things with optional icons.
2461 public $footer = '';
2464 * @var string Any small print that should appear under the block to explain
2465 * to the teacher about the block, for example 'This is a sticky block that was
2466 * added in the system context.'
2468 public $annotation = '';
2471 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2472 * the user can toggle whether this block is visible.
2474 public $collapsible = self::NOT_HIDEABLE;
2477 * Set this to true if the block is dockable.
2480 public $dockable = false;
2483 * @var array A (possibly empty) array of editing controls. Each element of
2484 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2485 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2487 public $controls = array();
2491 * Create new instance of block content
2492 * @param array $attributes
2494 public function __construct(array $attributes = null) {
2495 $this->skipid = self::$idcounter;
2496 self::$idcounter += 1;
2500 $this->attributes = $attributes;
2502 // simple "fake" blocks used in some modules and "Add new block" block
2503 $this->attributes = array('class'=>'block');
2508 * Add html class to block
2510 * @param string $class
2512 public function add_class($class) {
2513 $this->attributes['class'] .= ' '.$class;
2519 * This class represents a target for where a block can go when it is being moved.
2521 * This needs to be rendered as a form with the given hidden from fields, and
2522 * clicking anywhere in the form should submit it. The form action should be
2525 * @copyright 2009 Tim Hunt
2526 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2531 class block_move_target {
2534 * @var moodle_url Move url
2540 * @param moodle_url $url
2542 public function __construct(moodle_url $url) {
2550 * This class is used to represent one item within a custom menu that may or may
2551 * not have children.
2553 * @copyright 2010 Sam Hemelryk
2554 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2559 class custom_menu_item implements renderable {
2562 * @var string The text to show for the item
2567 * @var moodle_url The link to give the icon if it has no children
2572 * @var string A title to apply to the item. By default the text
2577 * @var int A sort order for the item, not necessary if you order things in
2583 * @var custom_menu_item A reference to the parent for this item or NULL if
2584 * it is a top level item
2589 * @var array A array in which to store children this item has.
2591 protected $children = array();
2594 * @var int A reference to the sort var of the last child that was added
2596 protected $lastsort = 0;
2599 * Constructs the new custom menu item
2601 * @param string $text
2602 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2603 * @param string $title A title to apply to this item [Optional]
2604 * @param int $sort A sort or to use if we need to sort differently [Optional]
2605 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2606 * belongs to, only if the child has a parent. [Optional]
2608 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
2609 $this->text = $text;
2611 $this->title = $title;
2612 $this->sort = (int)$sort;
2613 $this->parent = $parent;
2617 * Adds a custom menu item as a child of this node given its properties.
2619 * @param string $text
2620 * @param moodle_url $url
2621 * @param string $title
2623 * @return custom_menu_item
2625 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
2626 $key = count($this->children);
2628 $sort = $this->lastsort + 1;
2630 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2631 $this->lastsort = (int)$sort;
2632 return $this->children[$key];
2636 * Returns the text for this item
2639 public function get_text() {
2644 * Returns the url for this item
2645 * @return moodle_url
2647 public function get_url() {
2652 * Returns the title for this item
2655 public function get_title() {
2656 return $this->title;
2660 * Sorts and returns the children for this item
2663 public function get_children() {
2665 return $this->children;
2669 * Gets the sort order for this child
2672 public function get_sort_order() {
2677 * Gets the parent this child belong to
2678 * @return custom_menu_item
2680 public function get_parent() {
2681 return $this->parent;
2685 * Sorts the children this item has
2687 public function sort() {
2688 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2692 * Returns true if this item has any children
2695 public function has_children() {
2696 return (count($this->children) > 0);
2700 * Sets the text for the node
2701 * @param string $text
2703 public function set_text($text) {
2704 $this->text = (string)$text;
2708 * Sets the title for the node
2709 * @param string $title
2711 public function set_title($title) {
2712 $this->title = (string)$title;
2716 * Sets the url for the node
2717 * @param moodle_url $url
2719 public function set_url(moodle_url $url) {
2727 * This class is used to operate a custom menu that can be rendered for the page.
2728 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2729 * of custom_menu_item nodes that can be rendered by the core renderer.
2731 * To configure the custom menu:
2732 * Settings: Administration > Appearance > Themes > Theme settings
2734 * @copyright 2010 Sam Hemelryk
2735 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2740 class custom_menu extends custom_menu_item {
2743 * @var string The language we should render for, null disables multilang support.
2745 protected $currentlanguage = null;
2748 * Creates the custom menu
2750 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2751 * @param string $currentlanguage the current language code, null disables multilang support
2753 public function __construct($definition = '', $currentlanguage = null) {
2754 $this->currentlanguage = $currentlanguage;
2755 parent::__construct('root'); // create virtual root element of the menu
2756 if (!empty($definition)) {
2757 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2762 * Overrides the children of this custom menu. Useful when getting children
2763 * from $CFG->custommenuitems
2765 * @param array $children
2767 public function override_children(array $children) {
2768 $this->children = array();
2769 foreach ($children as $child) {
2770 if ($child instanceof custom_menu_item) {
2771 $this->children[] = $child;
2777 * Converts a string into a structured array of custom_menu_items which can
2778 * then be added to a custom menu.
2781 * text|url|title|langs
2782 * The number of hyphens at the start determines the depth of the item. The
2783 * languages are optional, comma separated list of languages the line is for.
2785 * Example structure:
2786 * First level first item|http://www.moodle.com/
2787 * -Second level first item|http://www.moodle.com/partners/
2788 * -Second level second item|http://www.moodle.com/hq/
2789 * --Third level first item|http://www.moodle.com/jobs/
2790 * -Second level third item|http://www.moodle.com/development/
2791 * First level second item|http://www.moodle.com/feedback/
2792 * First level third item
2793 * English only|http://moodle.com|English only item|en
2794 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2798 * @param string $text the menu items definition
2799 * @param string $language the language code, null disables multilang support
2802 public static function convert_text_to_menu_nodes($text, $language = null) {
2803 $lines = explode("\n", $text);
2804 $children = array();
2808 foreach ($lines as $line) {
2809 $line = trim($line);
2810 $bits = explode('|', $line, 4); // name|url|title|langs
2811 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2812 // Every item must have a name to be valid
2815 $bits[0] = ltrim($bits[0],'-');
2817 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2818 // Set the url to null
2821 // Make sure the url is a moodle url
2822 $bits[1] = new moodle_url(trim($bits[1]));
2824 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2825 // Set the title to null seeing as there isn't one
2826 $bits[2] = $bits[0];
2828 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2829 // The item is valid for all languages
2832 $itemlangs = array_map('trim', explode(',', $bits[3]));
2834 if (!empty($language) and !empty($itemlangs)) {
2835 // check that the item is intended for the current language
2836 if (!in_array($language, $itemlangs)) {
2840 // Set an incremental sort order to keep it simple.
2842 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2843 $depth = strlen($match[1]);
2844 if ($depth < $lastdepth) {
2845 $difference = $lastdepth - $depth;
2846 if ($lastdepth > 1 && $lastdepth != $difference) {
2847 $tempchild = $lastchild->get_parent();
2848 for ($i =0; $i < $difference; $i++) {
2849 $tempchild = $tempchild->get_parent();
2851 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2854 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2855 $children[] = $lastchild;
2857 } else if ($depth > $lastdepth) {
2858 $depth = $lastdepth + 1;
2859 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2862 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2863 $children[] = $lastchild;
2865 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2870 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2871 $children[] = $lastchild;
2873 $lastdepth = $depth;
2879 * Sorts two custom menu items
2881 * This function is designed to be used with the usort method
2882 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2885 * @param custom_menu_item $itema
2886 * @param custom_menu_item $itemb
2889 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2890 $itema = $itema->get_sort_order();
2891 $itemb = $itemb->get_sort_order();
2892 if ($itema == $itemb) {
2895 return ($itema > $itemb) ? +1 : -1;
2902 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2905 class tabobject implements renderable {
2906 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
2908 /** @var moodle_url|string link */
2910 /** @var string text on the tab */
2912 /** @var string title under the link, by defaul equals to text */
2914 /** @var bool whether to display a link under the tab name when it's selected */
2915 var $linkedwhenselected = false;
2916 /** @var bool whether the tab is inactive */
2917 var $inactive = false;
2918 /** @var bool indicates that this tab's child is selected */
2919 var $activated = false;
2920 /** @var bool indicates that this tab is selected */
2921 var $selected = false;
2922 /** @var array stores children tabobjects */
2923 var $subtree = array();
2924 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
2930 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
2931 * @param string|moodle_url $link
2932 * @param string $text text on the tab
2933 * @param string $title title under the link, by defaul equals to text
2934 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
2936 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
2938 $this->link = $link;
2939 $this->text = $text;
2940 $this->title = $title ? $title : $text;
2941 $this->linkedwhenselected = $linkedwhenselected;
2945 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
2947 * @param string $selected the id of the selected tab (whatever row it's on),
2948 * if null marks all tabs as unselected
2949 * @return bool whether this tab is selected or contains selected tab in its subtree
2951 protected function set_selected($selected) {
2952 if ((string)$selected === (string)$this->id) {
2953 $this->selected = true;
2954 // This tab is selected. No need to travel through subtree.
2957 foreach ($this->subtree as $subitem) {
2958 if ($subitem->set_selected($selected)) {
2959 // This tab has child that is selected. Mark it as activated. No need to check other children.
2960 $this->activated = true;
2968 * Travels through tree and finds a tab with specified id
2971 * @return tabtree|null
2973 public function find($id) {
2974 if ((string)$this->id === (string)$id) {
2977 foreach ($this->subtree as $tab) {
2978 if ($obj = $tab->find($id)) {
2986 * Allows to mark each tab's level in the tree before rendering.
2990 protected function set_level($level) {
2991 $this->level = $level;
2992 foreach ($this->subtree as $tab) {
2993 $tab->set_level($level + 1);
3001 * Example how to print a single line tabs:
3003 * new tabobject(...),
3004 * new tabobject(...)
3006 * echo $OUTPUT->tabtree($rows, $selectedid);
3008 * Multiple row tabs may not look good on some devices but if you want to use them
3009 * you can specify ->subtree for the active tabobject.
3011 * @copyright 2013 Marina Glancy
3012 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3017 class tabtree extends tabobject {
3021 * It is highly recommended to call constructor when list of tabs is already
3022 * populated, this way you ensure that selected and inactive tabs are located
3023 * and attribute level is set correctly.
3025 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3026 * @param string|null $selected which tab to mark as selected, all parent tabs will
3027 * automatically be marked as activated
3028 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3029 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3031 public function __construct($tabs, $selected = null, $inactive = null) {
3032 $this->subtree = $tabs;
3033 if ($selected !== null) {
3034 $this->set_selected($selected);
3036 if ($inactive !== null) {
3037 if (is_array($inactive)) {
3038 foreach ($inactive as $id) {
3039 if ($tab = $this->find($id)) {
3040 $tab->inactive = true;
3043 } else if ($tab = $this->find($inactive)) {
3044 $tab->inactive = true;
3047 $this->set_level(0);
3054 * This action menu component takes a series of primary and secondary actions.
3055 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
3060 * @copyright 2013 Sam Hemelryk
3061 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3063 class action_menu implements renderable {
3066 * Top right alignment.
3071 * Top right alignment.
3076 * Top right alignment.
3081 * Top right alignment.
3086 * The instance number. This is unique to this instance of the action menu.
3089 protected $instance = 0;
3092 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
3095 protected $primaryactions = array();
3098 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
3101 protected $secondaryactions = array();
3104 * An array of attributes added to the container of the action menu.
3105 * Initialised with defaults during construction.
3108 public $attributes = array();
3110 * An array of attributes added to the container of the primary actions.
3111 * Initialised with defaults during construction.
3114 public $attributesprimary = array();
3116 * An array of attributes added to the container of the secondary actions.
3117 * Initialised with defaults during construction.
3120 public $attributessecondary = array();
3123 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
3126 public $actiontext = null;
3129 * An icon to use for the toggling the secondary menu (dropdown).
3135 * Any text to use for the toggling the secondary menu (dropdown).
3138 public $menutrigger = '';
3141 * Place the action menu before all other actions.
3144 public $prioritise = false;
3147 * Constructs the action menu with the given items.
3149 * @param array $actions An array of actions.
3151 public function __construct(array $actions = array()) {
3152 static $initialised = 0;
3153 $this->instance = $initialised;
3156 $this->attributes = array(
3157 'id' => 'action-menu-'.$this->instance,
3158 'class' => 'moodle-actionmenu',
3159 'data-enhance' => 'moodle-core-actionmenu'
3161 $this->attributesprimary = array(
3162 'id' => 'action-menu-'.$this->instance.'-menubar',
3163 'class' => 'menubar',
3166 $this->attributessecondary = array(
3167 'id' => 'action-menu-'.$this->instance.'-menu',
3169 'data-rel' => 'menu-content',
3170 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
3173 $this->set_alignment(self::TR, self::BR);
3174 foreach ($actions as $action) {
3175 $this->add($action);
3179 public function set_menu_trigger($trigger) {
3180 $this->menutrigger = $trigger;
3184 * Initialises JS required fore the action menu.
3185 * The JS is only required once as it manages all action menu's on the page.
3187 * @param moodle_page $page
3189 public function initialise_js(moodle_page $page) {
3190 static $initialised = false;
3191 if (!$initialised) {
3192 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
3193 $initialised = true;
3198 * Adds an action to this action menu.
3200 * @param action_menu_link|pix_icon|string $action
3202 public function add($action) {
3203 if ($action instanceof action_link) {
3204 if ($action->primary) {
3205 $this->add_primary_action($action);
3207 $this->add_secondary_action($action);
3209 } else if ($action instanceof pix_icon) {
3210 $this->add_primary_action($action);
3212 $this->add_secondary_action($action);
3217 * Adds a primary action to the action menu.
3219 * @param action_menu_link|action_link|pix_icon|string $action
3221 public function add_primary_action($action) {
3222 if ($action instanceof action_link || $action instanceof pix_icon) {
3223 $action->attributes['role'] = 'menuitem';
3224 if ($action instanceof action_menu_link) {
3225 $action->actionmenu = $this;
3228 $this->primaryactions[] = $action;
3232 * Adds a secondary action to the action menu.
3234 * @param action_link|pix_icon|string $action
3236 public function add_secondary_action($action) {
3237 if ($action instanceof action_link || $action instanceof pix_icon) {
3238 $action->attributes['role'] = 'menuitem';
3239 if ($action instanceof action_menu_link) {
3240 $action->actionmenu = $this;
3243 $this->secondaryactions[] = $action;
3247 * Returns the primary actions ready to be rendered.
3249 * @param core_renderer $output The renderer to use for getting icons.
3252 public function get_primary_actions(core_renderer $output = null) {
3254 if ($output === null) {
3257 $pixicon = $this->actionicon;
3258 $linkclasses = array('toggle-display');
3261 if (!empty($this->menutrigger)) {
3262 $pixicon = '<b class="caret"></b>';
3263 $linkclasses[] = 'textmenu';
3265 $title = new lang_string('actions', 'moodle');
3266 $this->actionicon = new pix_icon(
3270 array('class' => 'iconsmall actionmenu', 'title' => '')
3272 $pixicon = $this->actionicon;
3274 if ($pixicon instanceof renderable) {
3275 $pixicon = $output->render($pixicon);
3276 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
3277 $title = $pixicon->attributes['alt'];
3281 if ($this->actiontext) {
3282 $string = $this->actiontext;
3284 $actions = $this->primaryactions;
3285 $attributes = array(
3286 'class' => implode(' ', $linkclasses),
3288 'id' => 'action-menu-toggle-'.$this->instance,
3289 'role' => 'menuitem'
3291 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
3292 if ($this->prioritise) {
3293 array_unshift($actions, $link);
3301 * Returns the secondary actions ready to be rendered.
3304 public function get_secondary_actions() {
3305 return $this->secondaryactions;
3309 * Sets the selector that should be used to find the owning node of this menu.
3310 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
3312 public function set_owner_selector($selector) {
3313 $this->attributes['data-owner'] = $selector;
3317 * Sets the alignment of the dialogue in relation to button used to toggle it.
3319 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3320 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3322 public function set_alignment($dialogue, $button) {
3323 if (isset($this->attributessecondary['data-align'])) {
3324 // We've already got one set, lets remove the old class so as to avoid troubles.
3325 $class = $this->attributessecondary['class'];
3326 $search = 'align-'.$this->attributessecondary['data-align'];
3327 $this->attributessecondary['class'] = str_replace($search, '', $class);
3329 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
3330 $this->attributessecondary['data-align'] = $align;
3331 $this->attributessecondary['class'] .= ' align-'.$align;
3335 * Returns a string to describe the alignment.
3337 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3340 protected function get_align_string($align) {
3356 * Sets a constraint for the dialogue.
3358 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
3359 * element the constraint identifies.
3361 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
3363 public function set_constraint($ancestorselector) {
3364 $this->attributessecondary['data-constraint'] = $ancestorselector;
3368 * If you call this method the action menu will be displayed but will not be enhanced.
3370 * By not displaying the menu enhanced all items will be displayed in a single row.
3372 public function do_not_enhance() {
3373 unset($this->attributes['data-enhance']);
3377 * Returns true if this action menu will be enhanced.
3381 public function will_be_enhanced() {
3382 return isset($this->attributes['data-enhance']);
3387 * An action menu filler
3391 * @copyright 2013 Andrew Nicols
3392 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3394 class action_menu_filler extends action_link implements renderable {
3397 * True if this is a primary action. False if not.
3400 public $primary = true;
3403 * Constructs the object.
3405 public function __construct() {
3410 * An action menu action
3414 * @copyright 2013 Sam Hemelryk
3415 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3417 class action_menu_link extends action_link implements renderable {
3420 * True if this is a primary action. False if not.
3423 public $primary = true;
3426 * The action menu this link has been added to.
3429 public $actionmenu = null;
3432 * Constructs the object.
3434 * @param moodle_url $url The URL for the action.
3435 * @param pix_icon $icon The icon to represent the action.
3436 * @param string $text The text to represent the action.
3437 * @param bool $primary Whether this is a primary action or not.
3438 * @param array $attributes Any attribtues associated with the action.
3440 public function __construct(moodle_url $url, pix_icon $icon = null, $text, $primary = true, array $attributes = array()) {
3441 parent::__construct($url, $text, null, $attributes, $icon);
3442 $this->primary = (bool)$primary;
3443 $this->add_class('menu-action');
3444 $this->attributes['role'] = 'menuitem';
3449 * A primary action menu action
3453 * @copyright 2013 Sam Hemelryk
3454 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3456 class action_menu_link_primary extends action_menu_link {
3458 * Constructs the object.
3460 * @param moodle_url $url
3461 * @param pix_icon $icon
3462 * @param string $text
3463 * @param array $attributes
3465 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
3466 parent::__construct($url, $icon, $text, true, $attributes);
3471 * A secondary action menu action
3475 * @copyright 2013 Sam Hemelryk
3476 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3478 class action_menu_link_secondary extends action_menu_link {
3480 * Constructs the object.
3482 * @param moodle_url $url
3483 * @param pix_icon $icon
3484 * @param string $text
3485 * @param array $attributes
3487 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
3488 parent::__construct($url, $icon, $text, false, $attributes);