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', 'imagealt', 'email');
137 * @var stdClass A user object with at least fields all columns specified
138 * in $fields array constant set.
143 * @var int The course id. Used when constructing the link to the user's
144 * profile, page course id used if not specified.
149 * @var bool Add course profile link to image
154 * @var int Size in pixels. Special values are (true/1 = 100px) and
156 * for backward compatibility.
161 * @var bool Add non-blank alt-text to the image.
162 * Default true, set to false when image alt just duplicates text in screenreaders.
164 public $alttext = true;
167 * @var bool Whether or not to open the link in a popup window.
169 public $popup = false;
172 * @var string Image class attribute
174 public $class = 'userpicture';
177 * User picture constructor.
179 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
180 * It is recommended to add also contextid of the user for performance reasons.
182 public function __construct(stdClass $user) {
185 if (empty($user->id)) {
186 throw new coding_exception('User id is required when printing user avatar image.');
189 // only touch the DB if we are missing data and complain loudly...
191 foreach (self::$fields as $field) {
192 if (!array_key_exists($field, $user)) {
194 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
195 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
201 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
203 $this->user = clone($user);
208 * Returns a list of required user fields, useful when fetching required user info from db.
210 * In some cases we have to fetch the user data together with some other information,
211 * the idalias is useful there because the id would otherwise override the main
212 * id of the result record. Please note it has to be converted back to id before rendering.
214 * @param string $tableprefix name of database table prefix in query
215 * @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)
216 * @param string $idalias alias of id field
217 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
220 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
221 if (!$tableprefix and !$extrafields and !$idalias) {
222 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.
387 // If the currently requested page is https then we'll return an
388 // https gravatar page.
389 if (strpos($CFG->httpswwwroot, 'https:') === 0) {
390 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $defaulturl->out(false)));
392 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $defaulturl->out(false)));
401 * Data structure representing a help icon.
403 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
404 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
409 class old_help_icon implements renderable {
412 * @var string Lang pack identifier
414 public $helpidentifier;
417 * @var string A descriptive text for title tooltip
419 public $title = null;
422 * @var string Component name, the same as in get_string()
424 public $component = 'moodle';
427 * @var string Extra descriptive text next to the icon
429 public $linktext = null;
432 * Constructor: sets up the other components in case they are needed
434 * @param string $helpidentifier The keyword that defines a help page
435 * @param string $title A descriptive text for accessibility only
436 * @param string $component
438 public function __construct($helpidentifier, $title, $component = 'moodle') {
440 throw new coding_exception('A help_icon object requires a $text parameter');
442 if (empty($helpidentifier)) {
443 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
446 $this->helpidentifier = $helpidentifier;
447 $this->title = $title;
448 $this->component = $component;
453 * Data structure representing a help icon.
455 * @copyright 2010 Petr Skoda (info@skodak.org)
456 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
461 class help_icon implements renderable {
464 * @var string lang pack identifier (without the "_help" suffix),
465 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
471 * @var string Component name, the same as in get_string()
476 * @var string Extra descriptive text next to the icon
478 public $linktext = null;
483 * @param string $identifier string for help page title,
484 * string with _help suffix is used for the actual help text.
485 * string with _link suffix is used to create a link to further info (if it exists)
486 * @param string $component
488 public function __construct($identifier, $component) {
489 $this->identifier = $identifier;
490 $this->component = $component;
494 * Verifies that both help strings exists, shows debug warnings if not
496 public function diag_strings() {
497 $sm = get_string_manager();
498 if (!$sm->string_exists($this->identifier, $this->component)) {
499 debugging("Help title string does not exist: [$this->identifier, $this->component]");
501 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
502 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
509 * Data structure representing an icon.
511 * @copyright 2010 Petr Skoda
512 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
517 class pix_icon implements renderable {
520 * @var string The icon name
525 * @var string The component the icon belongs to.
530 * @var array An array of attributes to use on the icon
532 var $attributes = array();
537 * @param string $pix short icon name
538 * @param string $alt The alt text to use for the icon
539 * @param string $component component name
540 * @param array $attributes html attributes
542 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
544 $this->component = $component;
545 $this->attributes = (array)$attributes;
547 $this->attributes['alt'] = $alt;
548 if (empty($this->attributes['class'])) {
549 $this->attributes['class'] = 'smallicon';
551 if (!isset($this->attributes['title'])) {
552 $this->attributes['title'] = $this->attributes['alt'];
553 } else if (empty($this->attributes['title'])) {
554 // Remove the title attribute if empty, we probably want to use the parent node's title
555 // and some browsers might overwrite it with an empty title.
556 unset($this->attributes['title']);
562 * Data structure representing an emoticon image
564 * @copyright 2010 David Mudrak
565 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
570 class pix_emoticon extends pix_icon implements renderable {
574 * @param string $pix short icon name
575 * @param string $alt alternative text
576 * @param string $component emoticon image provider
577 * @param array $attributes explicit HTML attributes
579 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
580 if (empty($attributes['class'])) {
581 $attributes['class'] = 'emoticon';
583 parent::__construct($pix, $alt, $component, $attributes);
588 * Data structure representing a simple form with only one button.
590 * @copyright 2009 Petr Skoda
591 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
596 class single_button implements renderable {
599 * @var moodle_url Target url
604 * @var string Button label
609 * @var string Form submit method post or get
611 var $method = 'post';
614 * @var string Wrapping div class
616 var $class = 'singlebutton';
619 * @var bool True if button disabled, false if normal
621 var $disabled = false;
624 * @var string Button tooltip
629 * @var string Form id
634 * @var array List of attached actions
636 var $actions = array();
640 * @param moodle_url $url
641 * @param string $label button text
642 * @param string $method get or post submit method
644 public function __construct(moodle_url $url, $label, $method='post') {
645 $this->url = clone($url);
646 $this->label = $label;
647 $this->method = $method;
651 * Shortcut for adding a JS confirm dialog when the button is clicked.
652 * The message must be a yes/no question.
654 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
656 public function add_confirm_action($confirmmessage) {
657 $this->add_action(new confirm_action($confirmmessage));
661 * Add action to the button.
662 * @param component_action $action
664 public function add_action(component_action $action) {
665 $this->actions[] = $action;
671 * Simple form with just one select field that gets submitted automatically.
673 * If JS not enabled small go button is printed too.
675 * @copyright 2009 Petr Skoda
676 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
681 class single_select implements renderable {
684 * @var moodle_url Target url - includes hidden fields
689 * @var string Name of the select element.
694 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
695 * it is also possible to specify optgroup as complex label array ex.:
696 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
697 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
702 * @var string Selected option
707 * @var array Nothing selected
712 * @var array Extra select field attributes
714 var $attributes = array();
717 * @var string Button label
722 * @var array Button label's attributes
724 var $labelattributes = array();
727 * @var string Form submit method post or get
732 * @var string Wrapping div class
734 var $class = 'singleselect';
737 * @var bool True if button disabled, false if normal
739 var $disabled = false;
742 * @var string Button tooltip
747 * @var string Form id
752 * @var array List of attached actions
754 var $helpicon = null;
758 * @param moodle_url $url form action target, includes hidden fields
759 * @param string $name name of selection field - the changing parameter in url
760 * @param array $options list of options
761 * @param string $selected selected element
762 * @param array $nothing
763 * @param string $formid
765 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
768 $this->options = $options;
769 $this->selected = $selected;
770 $this->nothing = $nothing;
771 $this->formid = $formid;
775 * Shortcut for adding a JS confirm dialog when the button is clicked.
776 * The message must be a yes/no question.
778 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
780 public function add_confirm_action($confirmmessage) {
781 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
785 * Add action to the button.
787 * @param component_action $action
789 public function add_action(component_action $action) {
790 $this->actions[] = $action;
796 * @param string $helppage The keyword that defines a help page
797 * @param string $title A descriptive text for accessibility only
798 * @param string $component
800 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
801 $this->helpicon = new old_help_icon($helppage, $title, $component);
807 * @param string $identifier The keyword that defines a help page
808 * @param string $component
810 public function set_help_icon($identifier, $component = 'moodle') {
811 $this->helpicon = new help_icon($identifier, $component);
815 * Sets select's label
817 * @param string $label
818 * @param array $attributes (optional)
820 public function set_label($label, $attributes = array()) {
821 $this->label = $label;
822 $this->labelattributes = $attributes;
828 * Simple URL selection widget description.
830 * @copyright 2009 Petr Skoda
831 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
836 class url_select implements renderable {
838 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
839 * it is also possible to specify optgroup as complex label array ex.:
840 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
841 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
846 * @var string Selected option
851 * @var array Nothing selected
856 * @var array Extra select field attributes
858 var $attributes = array();
861 * @var string Button label
866 * @var array Button label's attributes
868 var $labelattributes = array();
871 * @var string Wrapping div class
873 var $class = 'urlselect';
876 * @var bool True if button disabled, false if normal
878 var $disabled = false;
881 * @var string Button tooltip
886 * @var string Form id
891 * @var array List of attached actions
893 var $helpicon = null;
896 * @var string If set, makes button visible with given name for button
898 var $showbutton = null;
902 * @param array $urls list of options
903 * @param string $selected selected element
904 * @param array $nothing
905 * @param string $formid
906 * @param string $showbutton Set to text of button if it should be visible
907 * or null if it should be hidden (hidden version always has text 'go')
909 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
911 $this->selected = $selected;
912 $this->nothing = $nothing;
913 $this->formid = $formid;
914 $this->showbutton = $showbutton;
920 * @param string $helppage The keyword that defines a help page
921 * @param string $title A descriptive text for accessibility only
922 * @param string $component
924 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
925 $this->helpicon = new old_help_icon($helppage, $title, $component);
931 * @param string $identifier The keyword that defines a help page
932 * @param string $component
934 public function set_help_icon($identifier, $component = 'moodle') {
935 $this->helpicon = new help_icon($identifier, $component);
939 * Sets select's label
941 * @param string $label
942 * @param array $attributes (optional)
944 public function set_label($label, $attributes = array()) {
945 $this->label = $label;
946 $this->labelattributes = $attributes;
951 * Data structure describing html link with special action attached.
953 * @copyright 2010 Petr Skoda
954 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
959 class action_link implements renderable {
962 * @var moodle_url Href url
967 * @var string Link text HTML fragment
972 * @var array HTML attributes
977 * @var array List of actions attached to link
983 * @param moodle_url $url
984 * @param string $text HTML fragment
985 * @param component_action $action
986 * @param array $attributes associative array of html link attributes + disabled
988 public function __construct(moodle_url $url, $text, component_action $action = null, array $attributes = null) {
989 $this->url = clone($url);
991 $this->attributes = (array)$attributes;
993 $this->add_action($action);
998 * Add action to the link.
1000 * @param component_action $action
1002 public function add_action(component_action $action) {
1003 $this->actions[] = $action;
1007 * Adds a CSS class to this action link object
1008 * @param string $class
1010 public function add_class($class) {
1011 if (empty($this->attributes['class'])) {
1012 $this->attributes['class'] = $class;
1014 $this->attributes['class'] .= ' ' . $class;
1020 * Simple html output class
1022 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1023 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1031 * Outputs a tag with attributes and contents
1033 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1034 * @param string $contents What goes between the opening and closing tags
1035 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1036 * @return string HTML fragment
1038 public static function tag($tagname, $contents, array $attributes = null) {
1039 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1043 * Outputs an opening tag with attributes
1045 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1046 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1047 * @return string HTML fragment
1049 public static function start_tag($tagname, array $attributes = null) {
1050 return '<' . $tagname . self::attributes($attributes) . '>';
1054 * Outputs a closing tag
1056 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1057 * @return string HTML fragment
1059 public static function end_tag($tagname) {
1060 return '</' . $tagname . '>';
1064 * Outputs an empty tag with attributes
1066 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1067 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1068 * @return string HTML fragment
1070 public static function empty_tag($tagname, array $attributes = null) {
1071 return '<' . $tagname . self::attributes($attributes) . ' />';
1075 * Outputs a tag, but only if the contents are not empty
1077 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1078 * @param string $contents What goes between the opening and closing tags
1079 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1080 * @return string HTML fragment
1082 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1083 if ($contents === '' || is_null($contents)) {
1086 return self::tag($tagname, $contents, $attributes);
1090 * Outputs a HTML attribute and value
1092 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1093 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1094 * @return string HTML fragment
1096 public static function attribute($name, $value) {
1097 if (is_array($value)) {
1098 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
1100 if ($value instanceof moodle_url) {
1101 return ' ' . $name . '="' . $value->out() . '"';
1104 // special case, we do not want these in output
1105 if ($value === null) {
1109 // no sloppy trimming here!
1110 return ' ' . $name . '="' . s($value) . '"';
1114 * Outputs a list of HTML attributes and values
1116 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1117 * The values will be escaped with {@link s()}
1118 * @return string HTML fragment
1120 public static function attributes(array $attributes = null) {
1121 $attributes = (array)$attributes;
1123 foreach ($attributes as $name => $value) {
1124 $output .= self::attribute($name, $value);
1130 * Generates random html element id.
1132 * @staticvar int $counter
1133 * @staticvar type $uniq
1134 * @param string $base A string fragment that will be included in the random ID.
1135 * @return string A unique ID
1137 public static function random_id($base='random') {
1138 static $counter = 0;
1141 if (!isset($uniq)) {
1146 return $base.$uniq.$counter;
1150 * Generates a simple html link
1152 * @param string|moodle_url $url The URL
1153 * @param string $text The text
1154 * @param array $attributes HTML attributes
1155 * @return string HTML fragment
1157 public static function link($url, $text, array $attributes = null) {
1158 $attributes = (array)$attributes;
1159 $attributes['href'] = $url;
1160 return self::tag('a', $text, $attributes);
1164 * Generates a simple checkbox with optional label
1166 * @param string $name The name of the checkbox
1167 * @param string $value The value of the checkbox
1168 * @param bool $checked Whether the checkbox is checked
1169 * @param string $label The label for the checkbox
1170 * @param array $attributes Any attributes to apply to the checkbox
1171 * @return string html fragment
1173 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1174 $attributes = (array)$attributes;
1177 if ($label !== '' and !is_null($label)) {
1178 if (empty($attributes['id'])) {
1179 $attributes['id'] = self::random_id('checkbox_');
1182 $attributes['type'] = 'checkbox';
1183 $attributes['value'] = $value;
1184 $attributes['name'] = $name;
1185 $attributes['checked'] = $checked ? 'checked' : null;
1187 $output .= self::empty_tag('input', $attributes);
1189 if ($label !== '' and !is_null($label)) {
1190 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1197 * Generates a simple select yes/no form field
1199 * @param string $name name of select element
1200 * @param bool $selected
1201 * @param array $attributes - html select element attributes
1202 * @return string HTML fragment
1204 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1205 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1206 return self::select($options, $name, $selected, null, $attributes);
1210 * Generates a simple select form field
1212 * @param array $options associative array value=>label ex.:
1213 * array(1=>'One, 2=>Two)
1214 * it is also possible to specify optgroup as complex label array ex.:
1215 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1216 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1217 * @param string $name name of select element
1218 * @param string|array $selected value or array of values depending on multiple attribute
1219 * @param array|bool $nothing add nothing selected option, or false of not added
1220 * @param array $attributes html select element attributes
1221 * @return string HTML fragment
1223 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1224 $attributes = (array)$attributes;
1225 if (is_array($nothing)) {
1226 foreach ($nothing as $k=>$v) {
1227 if ($v === 'choose' or $v === 'choosedots') {
1228 $nothing[$k] = get_string('choosedots');
1231 $options = $nothing + $options; // keep keys, do not override
1233 } else if (is_string($nothing) and $nothing !== '') {
1235 $options = array(''=>$nothing) + $options;
1238 // we may accept more values if multiple attribute specified
1239 $selected = (array)$selected;
1240 foreach ($selected as $k=>$v) {
1241 $selected[$k] = (string)$v;
1244 if (!isset($attributes['id'])) {
1246 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1247 $id = str_replace('[', '', $id);
1248 $id = str_replace(']', '', $id);
1249 $attributes['id'] = $id;
1252 if (!isset($attributes['class'])) {
1253 $class = 'menu'.$name;
1254 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1255 $class = str_replace('[', '', $class);
1256 $class = str_replace(']', '', $class);
1257 $attributes['class'] = $class;
1259 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
1261 $attributes['name'] = $name;
1263 if (!empty($attributes['disabled'])) {
1264 $attributes['disabled'] = 'disabled';
1266 unset($attributes['disabled']);
1270 foreach ($options as $value=>$label) {
1271 if (is_array($label)) {
1272 // ignore key, it just has to be unique
1273 $output .= self::select_optgroup(key($label), current($label), $selected);
1275 $output .= self::select_option($label, $value, $selected);
1278 return self::tag('select', $output, $attributes);
1282 * Returns HTML to display a select box option.
1284 * @param string $label The label to display as the option.
1285 * @param string|int $value The value the option represents
1286 * @param array $selected An array of selected options
1287 * @return string HTML fragment
1289 private static function select_option($label, $value, array $selected) {
1290 $attributes = array();
1291 $value = (string)$value;
1292 if (in_array($value, $selected, true)) {
1293 $attributes['selected'] = 'selected';
1295 $attributes['value'] = $value;
1296 return self::tag('option', $label, $attributes);
1300 * Returns HTML to display a select box option group.
1302 * @param string $groupname The label to use for the group
1303 * @param array $options The options in the group
1304 * @param array $selected An array of selected values.
1305 * @return string HTML fragment.
1307 private static function select_optgroup($groupname, $options, array $selected) {
1308 if (empty($options)) {
1311 $attributes = array('label'=>$groupname);
1313 foreach ($options as $value=>$label) {
1314 $output .= self::select_option($label, $value, $selected);
1316 return self::tag('optgroup', $output, $attributes);
1320 * This is a shortcut for making an hour selector menu.
1322 * @param string $type The type of selector (years, months, days, hours, minutes)
1323 * @param string $name fieldname
1324 * @param int $currenttime A default timestamp in GMT
1325 * @param int $step minute spacing
1326 * @param array $attributes - html select element attributes
1327 * @return HTML fragment
1329 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1330 if (!$currenttime) {
1331 $currenttime = time();
1333 $currentdate = usergetdate($currenttime);
1334 $userdatetype = $type;
1335 $timeunits = array();
1339 for ($i=1970; $i<=2020; $i++) {
1340 $timeunits[$i] = $i;
1342 $userdatetype = 'year';
1345 for ($i=1; $i<=12; $i++) {
1346 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1348 $userdatetype = 'month';
1349 $currentdate['month'] = (int)$currentdate['mon'];
1352 for ($i=1; $i<=31; $i++) {
1353 $timeunits[$i] = $i;
1355 $userdatetype = 'mday';
1358 for ($i=0; $i<=23; $i++) {
1359 $timeunits[$i] = sprintf("%02d",$i);
1364 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1367 for ($i=0; $i<=59; $i+=$step) {
1368 $timeunits[$i] = sprintf("%02d",$i);
1372 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1375 if (empty($attributes['id'])) {
1376 $attributes['id'] = self::random_id('ts_');
1378 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1379 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1381 return $label.$timerselector;
1385 * Shortcut for quick making of lists
1387 * Note: 'list' is a reserved keyword ;-)
1389 * @param array $items
1390 * @param array $attributes
1391 * @param string $tag ul or ol
1394 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1397 foreach ($items as $item) {
1398 $output .= html_writer::start_tag('li') . "\n";
1399 $output .= $item . "\n";
1400 $output .= html_writer::end_tag('li') . "\n";
1403 return html_writer::tag($tag, $output, $attributes);
1407 * Returns hidden input fields created from url parameters.
1409 * @param moodle_url $url
1410 * @param array $exclude list of excluded parameters
1411 * @return string HTML fragment
1413 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1414 $exclude = (array)$exclude;
1415 $params = $url->params();
1416 foreach ($exclude as $key) {
1417 unset($params[$key]);
1421 foreach ($params as $key => $value) {
1422 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1423 $output .= self::empty_tag('input', $attributes)."\n";
1429 * Generate a script tag containing the the specified code.
1431 * @param string $jscode the JavaScript code
1432 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
1433 * @return string HTML, the code wrapped in <script> tags.
1435 public static function script($jscode, $url=null) {
1437 $attributes = array('type'=>'text/javascript');
1438 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1441 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1442 return self::tag('script', '', $attributes) . "\n";
1450 * Renders HTML table
1452 * This method may modify the passed instance by adding some default properties if they are not set yet.
1453 * If this is not what you want, you should make a full clone of your data before passing them to this
1454 * method. In most cases this is not an issue at all so we do not clone by default for performance
1455 * and memory consumption reasons.
1457 * @param html_table $table data to be rendered
1458 * @return string HTML code
1460 public static function table(html_table $table) {
1461 // prepare table data and populate missing properties with reasonable defaults
1462 if (!empty($table->align)) {
1463 foreach ($table->align as $key => $aa) {
1465 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1467 $table->align[$key] = null;
1471 if (!empty($table->size)) {
1472 foreach ($table->size as $key => $ss) {
1474 $table->size[$key] = 'width:'. $ss .';';
1476 $table->size[$key] = null;
1480 if (!empty($table->wrap)) {
1481 foreach ($table->wrap as $key => $ww) {
1483 $table->wrap[$key] = 'white-space:nowrap;';
1485 $table->wrap[$key] = '';
1489 if (!empty($table->head)) {
1490 foreach ($table->head as $key => $val) {
1491 if (!isset($table->align[$key])) {
1492 $table->align[$key] = null;
1494 if (!isset($table->size[$key])) {
1495 $table->size[$key] = null;
1497 if (!isset($table->wrap[$key])) {
1498 $table->wrap[$key] = null;
1503 if (empty($table->attributes['class'])) {
1504 $table->attributes['class'] = 'generaltable';
1506 if (!empty($table->tablealign)) {
1507 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1510 // explicitly assigned properties override those defined via $table->attributes
1511 $table->attributes['class'] = trim($table->attributes['class']);
1512 $attributes = array_merge($table->attributes, array(
1514 'width' => $table->width,
1515 'summary' => $table->summary,
1516 'cellpadding' => $table->cellpadding,
1517 'cellspacing' => $table->cellspacing,
1519 $output = html_writer::start_tag('table', $attributes) . "\n";
1523 if (!empty($table->head)) {
1524 $countcols = count($table->head);
1526 $output .= html_writer::start_tag('thead', array()) . "\n";
1527 $output .= html_writer::start_tag('tr', array()) . "\n";
1528 $keys = array_keys($table->head);
1529 $lastkey = end($keys);
1531 foreach ($table->head as $key => $heading) {
1532 // Convert plain string headings into html_table_cell objects
1533 if (!($heading instanceof html_table_cell)) {
1534 $headingtext = $heading;
1535 $heading = new html_table_cell();
1536 $heading->text = $headingtext;
1537 $heading->header = true;
1540 if ($heading->header !== false) {
1541 $heading->header = true;
1544 if ($heading->header && empty($heading->scope)) {
1545 $heading->scope = 'col';
1548 $heading->attributes['class'] .= ' header c' . $key;
1549 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1550 $heading->colspan = $table->headspan[$key];
1551 $countcols += $table->headspan[$key] - 1;
1554 if ($key == $lastkey) {
1555 $heading->attributes['class'] .= ' lastcol';
1557 if (isset($table->colclasses[$key])) {
1558 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1560 $heading->attributes['class'] = trim($heading->attributes['class']);
1561 $attributes = array_merge($heading->attributes, array(
1562 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1563 'scope' => $heading->scope,
1564 'colspan' => $heading->colspan,
1568 if ($heading->header === true) {
1571 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1573 $output .= html_writer::end_tag('tr') . "\n";
1574 $output .= html_writer::end_tag('thead') . "\n";
1576 if (empty($table->data)) {
1577 // For valid XHTML strict every table must contain either a valid tr
1578 // or a valid tbody... both of which must contain a valid td
1579 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1580 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1581 $output .= html_writer::end_tag('tbody');
1585 if (!empty($table->data)) {
1587 $keys = array_keys($table->data);
1588 $lastrowkey = end($keys);
1589 $output .= html_writer::start_tag('tbody', array());
1591 foreach ($table->data as $key => $row) {
1592 if (($row === 'hr') && ($countcols)) {
1593 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1595 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1596 if (!($row instanceof html_table_row)) {
1597 $newrow = new html_table_row();
1599 foreach ($row as $cell) {
1600 if (!($cell instanceof html_table_cell)) {
1601 $cell = new html_table_cell($cell);
1603 $newrow->cells[] = $cell;
1608 $oddeven = $oddeven ? 0 : 1;
1609 if (isset($table->rowclasses[$key])) {
1610 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1613 $row->attributes['class'] .= ' r' . $oddeven;
1614 if ($key == $lastrowkey) {
1615 $row->attributes['class'] .= ' lastrow';
1618 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1619 $keys2 = array_keys($row->cells);
1620 $lastkey = end($keys2);
1622 $gotlastkey = false; //flag for sanity checking
1623 foreach ($row->cells as $key => $cell) {
1625 //This should never happen. Why do we have a cell after the last cell?
1626 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1629 if (!($cell instanceof html_table_cell)) {
1630 $mycell = new html_table_cell();
1631 $mycell->text = $cell;
1635 if (($cell->header === true) && empty($cell->scope)) {
1636 $cell->scope = 'row';
1639 if (isset($table->colclasses[$key])) {
1640 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1643 $cell->attributes['class'] .= ' cell c' . $key;
1644 if ($key == $lastkey) {
1645 $cell->attributes['class'] .= ' lastcol';
1649 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1650 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1651 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1652 $cell->attributes['class'] = trim($cell->attributes['class']);
1653 $tdattributes = array_merge($cell->attributes, array(
1654 'style' => $tdstyle . $cell->style,
1655 'colspan' => $cell->colspan,
1656 'rowspan' => $cell->rowspan,
1658 'abbr' => $cell->abbr,
1659 'scope' => $cell->scope,
1662 if ($cell->header === true) {
1665 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1668 $output .= html_writer::end_tag('tr') . "\n";
1670 $output .= html_writer::end_tag('tbody') . "\n";
1672 $output .= html_writer::end_tag('table') . "\n";
1678 * Renders form element label
1680 * By default, the label is suffixed with a label separator defined in the
1681 * current language pack (colon by default in the English lang pack).
1682 * Adding the colon can be explicitly disabled if needed. Label separators
1683 * are put outside the label tag itself so they are not read by
1684 * screenreaders (accessibility).
1686 * Parameter $for explicitly associates the label with a form control. When
1687 * set, the value of this attribute must be the same as the value of
1688 * the id attribute of the form control in the same document. When null,
1689 * the label being defined is associated with the control inside the label
1692 * @param string $text content of the label tag
1693 * @param string|null $for id of the element this label is associated with, null for no association
1694 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1695 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1696 * @return string HTML of the label element
1698 public static function label($text, $for, $colonize = true, array $attributes=array()) {
1699 if (!is_null($for)) {
1700 $attributes = array_merge($attributes, array('for' => $for));
1702 $text = trim($text);
1703 $label = self::tag('label', $text, $attributes);
1705 // TODO MDL-12192 $colonize disabled for now yet
1706 // if (!empty($text) and $colonize) {
1707 // // the $text may end with the colon already, though it is bad string definition style
1708 // $colon = get_string('labelsep', 'langconfig');
1709 // if (!empty($colon)) {
1710 // $trimmed = trim($colon);
1711 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1712 // //debugging('The label text should not end with colon or other label separator,
1713 // // please fix the string definition.', DEBUG_DEVELOPER);
1715 // $label .= $colon;
1725 * Simple javascript output class
1727 * @copyright 2010 Petr Skoda
1728 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1736 * Returns javascript code calling the function
1738 * @param string $function function name, can be complex like Y.Event.purgeElement
1739 * @param array $arguments parameters
1740 * @param int $delay execution delay in seconds
1741 * @return string JS code fragment
1743 public static function function_call($function, array $arguments = null, $delay=0) {
1745 $arguments = array_map('json_encode', convert_to_array($arguments));
1746 $arguments = implode(', ', $arguments);
1750 $js = "$function($arguments);";
1753 $delay = $delay * 1000; // in miliseconds
1754 $js = "setTimeout(function() { $js }, $delay);";
1760 * Special function which adds Y as first argument of function call.
1762 * @param string $function The function to call
1763 * @param array $extraarguments Any arguments to pass to it
1764 * @return string Some JS code
1766 public static function function_call_with_Y($function, array $extraarguments = null) {
1767 if ($extraarguments) {
1768 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1769 $arguments = 'Y, ' . implode(', ', $extraarguments);
1773 return "$function($arguments);\n";
1777 * Returns JavaScript code to initialise a new object
1779 * @param string $var If it is null then no var is assigned the new object.
1780 * @param string $class The class to initialise an object for.
1781 * @param array $arguments An array of args to pass to the init method.
1782 * @param array $requirements Any modules required for this class.
1783 * @param int $delay The delay before initialisation. 0 = no delay.
1784 * @return string Some JS code
1786 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1787 if (is_array($arguments)) {
1788 $arguments = array_map('json_encode', convert_to_array($arguments));
1789 $arguments = implode(', ', $arguments);
1792 if ($var === null) {
1793 $js = "new $class(Y, $arguments);";
1794 } else if (strpos($var, '.')!==false) {
1795 $js = "$var = new $class(Y, $arguments);";
1797 $js = "var $var = new $class(Y, $arguments);";
1801 $delay = $delay * 1000; // in miliseconds
1802 $js = "setTimeout(function() { $js }, $delay);";
1805 if (count($requirements) > 0) {
1806 $requirements = implode("', '", $requirements);
1807 $js = "Y.use('$requirements', function(Y){ $js });";
1813 * Returns code setting value to variable
1815 * @param string $name
1816 * @param mixed $value json serialised value
1817 * @param bool $usevar add var definition, ignored for nested properties
1818 * @return string JS code fragment
1820 public static function set_variable($name, $value, $usevar = true) {
1824 if (strpos($name, '.')) {
1831 $output .= "$name = ".json_encode($value).";";
1837 * Writes event handler attaching code
1839 * @param array|string $selector standard YUI selector for elements, may be
1840 * array or string, element id is in the form "#idvalue"
1841 * @param string $event A valid DOM event (click, mousedown, change etc.)
1842 * @param string $function The name of the function to call
1843 * @param array $arguments An optional array of argument parameters to pass to the function
1844 * @return string JS code fragment
1846 public static function event_handler($selector, $event, $function, array $arguments = null) {
1847 $selector = json_encode($selector);
1848 $output = "Y.on('$event', $function, $selector, null";
1849 if (!empty($arguments)) {
1850 $output .= ', ' . json_encode($arguments);
1852 return $output . ");\n";
1857 * Holds all the information required to render a <table> by {@link core_renderer::table()}
1860 * $t = new html_table();
1861 * ... // set various properties of the object $t as described below
1862 * echo html_writer::table($t);
1864 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1865 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1873 * @var string Value to use for the id attribute of the table
1878 * @var array Attributes of HTML attributes for the <table> element
1880 public $attributes = array();
1883 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
1884 * For more control over the rendering of the headers, an array of html_table_cell objects
1885 * can be passed instead of an array of strings.
1888 * $t->head = array('Student', 'Grade');
1893 * @var array An array that can be used to make a heading span multiple columns.
1894 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1895 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
1898 * $t->headspan = array(2,1);
1903 * @var array An array of column alignments.
1904 * The value is used as CSS 'text-align' property. Therefore, possible
1905 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1906 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1908 * Examples of usage:
1909 * $t->align = array(null, 'right');
1911 * $t->align[1] = 'right';
1916 * @var array The value is used as CSS 'size' property.
1918 * Examples of usage:
1919 * $t->size = array('50%', '50%');
1921 * $t->size[1] = '120px';
1926 * @var array An array of wrapping information.
1927 * The only possible value is 'nowrap' that sets the
1928 * CSS property 'white-space' to the value 'nowrap' in the given column.
1931 * $t->wrap = array(null, 'nowrap');
1936 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
1937 * $head specified, the string 'hr' (for horizontal ruler) can be used
1938 * instead of an array of cells data resulting in a divider rendered.
1940 * Example of usage with array of arrays:
1941 * $row1 = array('Harry Potter', '76 %');
1942 * $row2 = array('Hermione Granger', '100 %');
1943 * $t->data = array($row1, $row2);
1945 * Example with array of html_table_row objects: (used for more fine-grained control)
1946 * $cell1 = new html_table_cell();
1947 * $cell1->text = 'Harry Potter';
1948 * $cell1->colspan = 2;
1949 * $row1 = new html_table_row();
1950 * $row1->cells[] = $cell1;
1951 * $cell2 = new html_table_cell();
1952 * $cell2->text = 'Hermione Granger';
1953 * $cell3 = new html_table_cell();
1954 * $cell3->text = '100 %';
1955 * $row2 = new html_table_row();
1956 * $row2->cells = array($cell2, $cell3);
1957 * $t->data = array($row1, $row2);
1962 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1963 * @var string Width of the table, percentage of the page preferred.
1965 public $width = null;
1968 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1969 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
1971 public $tablealign = null;
1974 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1975 * @var int Padding on each cell, in pixels
1977 public $cellpadding = null;
1980 * @var int Spacing between cells, in pixels
1981 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1983 public $cellspacing = null;
1986 * @var array Array of classes to add to particular rows, space-separated string.
1987 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1988 * respectively. Class 'lastrow' is added automatically for the last row
1992 * $t->rowclasses[9] = 'tenth'
1997 * @var array An array of classes to add to every cell in a particular column,
1998 * space-separated string. Class 'cell' is added automatically by the renderer.
1999 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2000 * respectively. Class 'lastcol' is added automatically for all last cells
2004 * $t->colclasses = array(null, 'grade');
2009 * @var string Description of the contents for screen readers.
2016 public function __construct() {
2017 $this->attributes['class'] = '';
2022 * Component representing a table row.
2024 * @copyright 2009 Nicolas Connault
2025 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2030 class html_table_row {
2033 * @var string Value to use for the id attribute of the row.
2038 * @var array Array of html_table_cell objects
2040 public $cells = array();
2043 * @var string Value to use for the style attribute of the table row
2045 public $style = null;
2048 * @var array Attributes of additional HTML attributes for the <tr> element
2050 public $attributes = array();
2054 * @param array $cells
2056 public function __construct(array $cells=null) {
2057 $this->attributes['class'] = '';
2058 $cells = (array)$cells;
2059 foreach ($cells as $cell) {
2060 if ($cell instanceof html_table_cell) {
2061 $this->cells[] = $cell;
2063 $this->cells[] = new html_table_cell($cell);
2070 * Component representing a table cell.
2072 * @copyright 2009 Nicolas Connault
2073 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2078 class html_table_cell {
2081 * @var string Value to use for the id attribute of the cell.
2086 * @var string The contents of the cell.
2091 * @var string Abbreviated version of the contents of the cell.
2093 public $abbr = null;
2096 * @var int Number of columns this cell should span.
2098 public $colspan = null;
2101 * @var int Number of rows this cell should span.
2103 public $rowspan = null;
2106 * @var string Defines a way to associate header cells and data cells in a table.
2108 public $scope = null;
2111 * @var bool Whether or not this cell is a header cell.
2113 public $header = null;
2116 * @var string Value to use for the style attribute of the table cell
2118 public $style = null;
2121 * @var array Attributes of additional HTML attributes for the <td> element
2123 public $attributes = array();
2126 * Constructs a table cell
2128 * @param string $text
2130 public function __construct($text = null) {
2131 $this->text = $text;
2132 $this->attributes['class'] = '';
2137 * Component representing a paging bar.
2139 * @copyright 2009 Nicolas Connault
2140 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2145 class paging_bar implements renderable {
2148 * @var int The maximum number of pagelinks to display.
2150 public $maxdisplay = 18;
2153 * @var int The total number of entries to be pages through..
2158 * @var int The page you are currently viewing.
2163 * @var int The number of entries that should be shown per page.
2168 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2169 * an equals sign and the page number.
2170 * If this is a moodle_url object then the pagevar param will be replaced by
2171 * the page no, for each page.
2176 * @var string This is the variable name that you use for the pagenumber in your
2177 * code (ie. 'tablepage', 'blogpage', etc)
2182 * @var string A HTML link representing the "previous" page.
2184 public $previouslink = null;
2187 * @var string A HTML link representing the "next" page.
2189 public $nextlink = null;
2192 * @var string A HTML link representing the first page.
2194 public $firstlink = null;
2197 * @var string A HTML link representing the last page.
2199 public $lastlink = null;
2202 * @var array An array of strings. One of them is just a string: the current page
2204 public $pagelinks = array();
2207 * Constructor paging_bar with only the required params.
2209 * @param int $totalcount The total number of entries available to be paged through
2210 * @param int $page The page you are currently viewing
2211 * @param int $perpage The number of entries that should be shown per page
2212 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2213 * @param string $pagevar name of page parameter that holds the page number
2215 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2216 $this->totalcount = $totalcount;
2217 $this->page = $page;
2218 $this->perpage = $perpage;
2219 $this->baseurl = $baseurl;
2220 $this->pagevar = $pagevar;
2224 * Prepares the paging bar for output.
2226 * This method validates the arguments set up for the paging bar and then
2227 * produces fragments of HTML to assist display later on.
2229 * @param renderer_base $output
2230 * @param moodle_page $page
2231 * @param string $target
2232 * @throws coding_exception
2234 public function prepare(renderer_base $output, moodle_page $page, $target) {
2235 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2236 throw new coding_exception('paging_bar requires a totalcount value.');
2238 if (!isset($this->page) || is_null($this->page)) {
2239 throw new coding_exception('paging_bar requires a page value.');
2241 if (empty($this->perpage)) {
2242 throw new coding_exception('paging_bar requires a perpage value.');
2244 if (empty($this->baseurl)) {
2245 throw new coding_exception('paging_bar requires a baseurl value.');
2248 if ($this->totalcount > $this->perpage) {
2249 $pagenum = $this->page - 1;
2251 if ($this->page > 0) {
2252 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2255 if ($this->perpage > 0) {
2256 $lastpage = ceil($this->totalcount / $this->perpage);
2261 if ($this->page > 15) {
2262 $startpage = $this->page - 10;
2264 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2269 $currpage = $startpage;
2270 $displaycount = $displaypage = 0;
2272 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2273 $displaypage = $currpage + 1;
2275 if ($this->page == $currpage) {
2276 $this->pagelinks[] = $displaypage;
2278 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2279 $this->pagelinks[] = $pagelink;
2286 if ($currpage < $lastpage) {
2287 $lastpageactual = $lastpage - 1;
2288 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2291 $pagenum = $this->page + 1;
2293 if ($pagenum != $displaypage) {
2294 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2301 * This class represents how a block appears on a page.
2303 * During output, each block instance is asked to return a block_contents object,
2304 * those are then passed to the $OUTPUT->block function for display.
2306 * contents should probably be generated using a moodle_block_..._renderer.
2308 * Other block-like things that need to appear on the page, for example the
2309 * add new block UI, are also represented as block_contents objects.
2311 * @copyright 2009 Tim Hunt
2312 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2317 class block_contents {
2319 /** Used when the block cannot be collapsed **/
2320 const NOT_HIDEABLE = 0;
2322 /** Used when the block can be collapsed but currently is not **/
2325 /** Used when the block has been collapsed **/
2329 * @var int Used to set $skipid.
2331 protected static $idcounter = 1;
2334 * @var int All the blocks (or things that look like blocks) printed on
2335 * a page are given a unique number that can be used to construct id="" attributes.
2336 * This is set automatically be the {@link prepare()} method.
2337 * Do not try to set it manually.
2342 * @var int If this is the contents of a real block, this should be set
2343 * to the block_instance.id. Otherwise this should be set to 0.
2345 public $blockinstanceid = 0;
2348 * @var int If this is a real block instance, and there is a corresponding
2349 * block_position.id for the block on this page, this should be set to that id.
2350 * Otherwise it should be 0.
2352 public $blockpositionid = 0;
2355 * @var array An array of attribute => value pairs that are put on the outer div of this
2356 * block. {@link $id} and {@link $classes} attributes should be set separately.
2361 * @var string The title of this block. If this came from user input, it should already
2362 * have had format_string() processing done on it. This will be output inside
2363 * <h2> tags. Please do not cause invalid XHTML.
2368 * @var string HTML for the content
2370 public $content = '';
2373 * @var array An alternative to $content, it you want a list of things with optional icons.
2375 public $footer = '';
2378 * @var string Any small print that should appear under the block to explain
2379 * to the teacher about the block, for example 'This is a sticky block that was
2380 * added in the system context.'
2382 public $annotation = '';
2385 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2386 * the user can toggle whether this block is visible.
2388 public $collapsible = self::NOT_HIDEABLE;
2391 * @var array A (possibly empty) array of editing controls. Each element of
2392 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2393 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2395 public $controls = array();
2399 * Create new instance of block content
2400 * @param array $attributes
2402 public function __construct(array $attributes = null) {
2403 $this->skipid = self::$idcounter;
2404 self::$idcounter += 1;
2408 $this->attributes = $attributes;
2410 // simple "fake" blocks used in some modules and "Add new block" block
2411 $this->attributes = array('class'=>'block');
2416 * Add html class to block
2418 * @param string $class
2420 public function add_class($class) {
2421 $this->attributes['class'] .= ' '.$class;
2427 * This class represents a target for where a block can go when it is being moved.
2429 * This needs to be rendered as a form with the given hidden from fields, and
2430 * clicking anywhere in the form should submit it. The form action should be
2433 * @copyright 2009 Tim Hunt
2434 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2439 class block_move_target {
2442 * @var moodle_url Move url
2453 * @param string $text
2454 * @param moodle_url $url
2456 public function __construct($text, moodle_url $url) {
2457 $this->text = $text;
2465 * This class is used to represent one item within a custom menu that may or may
2466 * not have children.
2468 * @copyright 2010 Sam Hemelryk
2469 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2474 class custom_menu_item implements renderable {
2477 * @var string The text to show for the item
2482 * @var moodle_url The link to give the icon if it has no children
2487 * @var string A title to apply to the item. By default the text
2492 * @var int A sort order for the item, not necessary if you order things in
2498 * @var custom_menu_item A reference to the parent for this item or NULL if
2499 * it is a top level item
2504 * @var array A array in which to store children this item has.
2506 protected $children = array();
2509 * @var int A reference to the sort var of the last child that was added
2511 protected $lastsort = 0;
2514 * Constructs the new custom menu item
2516 * @param string $text
2517 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2518 * @param string $title A title to apply to this item [Optional]
2519 * @param int $sort A sort or to use if we need to sort differently [Optional]
2520 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2521 * belongs to, only if the child has a parent. [Optional]
2523 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
2524 $this->text = $text;
2526 $this->title = $title;
2527 $this->sort = (int)$sort;
2528 $this->parent = $parent;
2532 * Adds a custom menu item as a child of this node given its properties.
2534 * @param string $text
2535 * @param moodle_url $url
2536 * @param string $title
2538 * @return custom_menu_item
2540 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
2541 $key = count($this->children);
2543 $sort = $this->lastsort + 1;
2545 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2546 $this->lastsort = (int)$sort;
2547 return $this->children[$key];
2551 * Returns the text for this item
2554 public function get_text() {
2559 * Returns the url for this item
2560 * @return moodle_url
2562 public function get_url() {
2567 * Returns the title for this item
2570 public function get_title() {
2571 return $this->title;
2575 * Sorts and returns the children for this item
2578 public function get_children() {
2580 return $this->children;
2584 * Gets the sort order for this child
2587 public function get_sort_order() {
2592 * Gets the parent this child belong to
2593 * @return custom_menu_item
2595 public function get_parent() {
2596 return $this->parent;
2600 * Sorts the children this item has
2602 public function sort() {
2603 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2607 * Returns true if this item has any children
2610 public function has_children() {
2611 return (count($this->children) > 0);
2615 * Sets the text for the node
2616 * @param string $text
2618 public function set_text($text) {
2619 $this->text = (string)$text;
2623 * Sets the title for the node
2624 * @param string $title
2626 public function set_title($title) {
2627 $this->title = (string)$title;
2631 * Sets the url for the node
2632 * @param moodle_url $url
2634 public function set_url(moodle_url $url) {
2642 * This class is used to operate a custom menu that can be rendered for the page.
2643 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2644 * of custom_menu_item nodes that can be rendered by the core renderer.
2646 * To configure the custom menu:
2647 * Settings: Administration > Appearance > Themes > Theme settings
2649 * @copyright 2010 Sam Hemelryk
2650 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2655 class custom_menu extends custom_menu_item {
2658 * @var string The language we should render for, null disables multilang support.
2660 protected $currentlanguage = null;
2663 * Creates the custom menu
2665 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2666 * @param string $currentlanguage the current language code, null disables multilang support
2668 public function __construct($definition = '', $currentlanguage = null) {
2669 $this->currentlanguage = $currentlanguage;
2670 parent::__construct('root'); // create virtual root element of the menu
2671 if (!empty($definition)) {
2672 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2677 * Overrides the children of this custom menu. Useful when getting children
2678 * from $CFG->custommenuitems
2680 * @param array $children
2682 public function override_children(array $children) {
2683 $this->children = array();
2684 foreach ($children as $child) {
2685 if ($child instanceof custom_menu_item) {
2686 $this->children[] = $child;
2692 * Converts a string into a structured array of custom_menu_items which can
2693 * then be added to a custom menu.
2696 * text|url|title|langs
2697 * The number of hyphens at the start determines the depth of the item. The
2698 * languages are optional, comma separated list of languages the line is for.
2700 * Example structure:
2701 * First level first item|http://www.moodle.com/
2702 * -Second level first item|http://www.moodle.com/partners/
2703 * -Second level second item|http://www.moodle.com/hq/
2704 * --Third level first item|http://www.moodle.com/jobs/
2705 * -Second level third item|http://www.moodle.com/development/
2706 * First level second item|http://www.moodle.com/feedback/
2707 * First level third item
2708 * English only|http://moodle.com|English only item|en
2709 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2713 * @param string $text the menu items definition
2714 * @param string $language the language code, null disables multilang support
2717 public static function convert_text_to_menu_nodes($text, $language = null) {
2718 $lines = explode("\n", $text);
2719 $children = array();
2723 foreach ($lines as $line) {
2724 $line = trim($line);
2725 $bits = explode('|', $line, 4); // name|url|title|langs
2726 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2727 // Every item must have a name to be valid
2730 $bits[0] = ltrim($bits[0],'-');
2732 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2733 // Set the url to null
2736 // Make sure the url is a moodle url
2737 $bits[1] = new moodle_url(trim($bits[1]));
2739 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2740 // Set the title to null seeing as there isn't one
2741 $bits[2] = $bits[0];
2743 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2744 // The item is valid for all languages
2747 $itemlangs = array_map('trim', explode(',', $bits[3]));
2749 if (!empty($language) and !empty($itemlangs)) {
2750 // check that the item is intended for the current language
2751 if (!in_array($language, $itemlangs)) {
2755 // Set an incremental sort order to keep it simple.
2757 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2758 $depth = strlen($match[1]);
2759 if ($depth < $lastdepth) {
2760 $difference = $lastdepth - $depth;
2761 if ($lastdepth > 1 && $lastdepth != $difference) {
2762 $tempchild = $lastchild->get_parent();
2763 for ($i =0; $i < $difference; $i++) {
2764 $tempchild = $tempchild->get_parent();
2766 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2769 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2770 $children[] = $lastchild;
2772 } else if ($depth > $lastdepth) {
2773 $depth = $lastdepth + 1;
2774 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2777 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2778 $children[] = $lastchild;
2780 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2785 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2786 $children[] = $lastchild;
2788 $lastdepth = $depth;
2794 * Sorts two custom menu items
2796 * This function is designed to be used with the usort method
2797 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2800 * @param custom_menu_item $itema
2801 * @param custom_menu_item $itemb
2804 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2805 $itema = $itema->get_sort_order();
2806 $itemb = $itemb->get_sort_order();
2807 if ($itema == $itemb) {
2810 return ($itema > $itemb) ? +1 : -1;