3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Classes representing HTML elements, used by $OUTPUT methods
21 * 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
31 * Interface marking other classes as suitable for renderer_base::render()
32 * @author 2010 Petr Skoda (skodak) info@skodak.org
34 interface renderable {
35 // intentionally empty
40 * Data structure representing a user picture.
42 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
43 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
46 class user_picture implements renderable {
48 * List of mandatory fields in user record here.
51 const FIELDS = 'id,picture,firstname,lastname,imagealt';
54 * @var object $user A user object with at least fields id, picture, imagealt, firstname and lastname set.
58 * @var int $courseid The course id. Used when constructing the link to the user's profile,
59 * page course id used if not specified.
63 * @var bool $link add course profile link to image
67 * @var int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility
71 * @var boolean $alttext add non-blank alt-text to the image.
72 * Default true, set to false when image alt just duplicates text in screenreaders.
74 public $alttext = true;
76 * @var boolean $popup Whether or not to open the link in a popup window.
78 public $popup = false;
80 * @var string Image class attribute
82 public $class = 'userpicture';
85 * User picture constructor.
87 * @param object $user user record with at least id, picture, imagealt, firstname and lastname set.
88 * @param array $options such as link, size, link, ...
90 public function __construct(stdClass $user) {
93 static $fields = null;
94 if (is_null($fields)) {
95 $fields = explode(',', self::FIELDS);
98 if (empty($user->id)) {
99 throw new coding_exception('User id is required when printing user avatar image.');
102 // only touch the DB if we are missing data and complain loudly...
104 foreach ($fields as $field) {
105 if (!array_key_exists($field, $user)) {
107 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
108 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
114 $this->user = $DB->get_record('user', array('id'=>$user->id), self::FIELDS, MUST_EXIST);
116 $this->user = clone($user);
121 * Returns a list of required user fields, usefull when fetching required user info from db.
123 * In some cases we have to fetch the user data together with some other information,
124 * the idalias is useful there because the id would otherwise override the main
125 * id of the result record. Please note it has to be converted back to id before rendering.
127 * @param string $tableprefix name of database table prefix in query
128 * @param string $idalias alias of id field
131 public static function fields($tableprefix = '', $idalias = '') {
132 if ($tableprefix === '' and $idalias === '') {
135 $fields = explode(',', self::FIELDS);
136 foreach ($fields as $key=>$field) {
137 if ($field === 'id' and $idalias !== '') {
138 $field = "$field AS $idalias";
140 $fields[$key] = "$tableprefix.$field";
142 return implode(',', $fields);
148 * Data structure representing a help icon.
150 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
151 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
154 class old_help_icon implements renderable {
156 * @var string $helpidentifier lang pack identifier
158 public $helpidentifier;
160 * @var string $title A descriptive text for title tooltip
162 public $title = null;
164 * @var string $component Component name, the same as in get_string()
166 public $component = 'moodle';
168 * @var string $linktext Extra descriptive text next to the icon
170 public $linktext = null;
173 * Constructor: sets up the other components in case they are needed
174 * @param string $helpidentifier The keyword that defines a help page
175 * @param string $title A descriptive text for accesibility only
176 * @param string $component
177 * @param bool $linktext add extra text to icon
180 public function __construct($helpidentifier, $title, $component = 'moodle') {
182 throw new coding_exception('A help_icon object requires a $text parameter');
184 if (empty($helpidentifier)) {
185 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
188 $this->helpidentifier = $helpidentifier;
189 $this->title = $title;
190 $this->component = $component;
195 * Data structure representing a help icon.
197 * @copyright 2010 Petr Skoda (info@skodak.org)
198 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
201 class help_icon implements renderable {
203 * @var string $identifier lang pack identifier (without the "_hlp" suffix),
204 * both get_string($identifier, $component) and get_string($identifier.'_hlp', $component)
209 * @var string $component Component name, the same as in get_string()
213 * @var string $linktext Extra descriptive text next to the icon
215 public $linktext = null;
219 * @param string $identifier string for help page title,
220 * string with _hlp suffix is used for the actual help text.
221 * @param string $component
223 public function __construct($pidentifier, $component) {
224 $this->identifier = $helpidentifier;
225 $this->component = $component;
231 * Data structure representing an icon.
233 * @copyright 2010 Petr Skoda
234 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
237 class pix_icon implements renderable {
240 var $attributes = array();
244 * @param string $pix short icon name
245 * @param string $component component name
246 * @param array $attributes html attributes
248 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
250 $this->component = $component;
251 $this->attributes = (array)$attributes;
253 $this->attributes['alt'] = $alt;
254 if (empty($this->attributes['class'])) {
255 $this->attributes['class'] = 'smallicon';
257 if (!isset($this->attributes['title'])) {
258 $this->attributes['title'] = $this->attributes['alt'];
265 * Data structure representing a simple form with only one button.
267 * @copyright 2009 Petr Skoda
268 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
271 class single_button implements renderable {
284 * @var string post or get
286 var $method = 'post';
291 var $class = 'singlebutton';
293 * True if button disabled, false if normal
296 var $disabled = false;
308 * List of attached actions
309 * @var array of component_action
311 var $actions = array();
315 * @param string|moodle_url $url
316 * @param string $label button text
317 * @param string $method get or post submit method
319 public function __construct(moodle_url $url, $label, $method='post') {
320 $this->url = clone($url);
321 $this->label = $label;
322 $this->method = $method;
326 * Shortcut for adding a JS confirm dialog when the button is clicked.
327 * The message must be a yes/no question.
328 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
331 public function add_confirm_action($confirmmessage) {
332 $this->add_action(new component_action('click', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
336 * Add action to the button.
337 * @param component_action $action
340 public function add_action(component_action $action) {
341 $this->actions[] = $action;
347 * Simple form with just one select field that gets submitted automatically.
348 * If JS not enabled small go button is printed too.
350 * @copyright 2009 Petr Skoda
351 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
354 class single_select implements renderable {
356 * Target url - includes hidden fields
361 * Name of the select element.
366 * @var array $options associative array value=>label ex.:
367 * array(1=>'One, 2=>Two)
368 * it is also possible to specify optgroup as complex label array ex.:
369 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
370 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
384 * Extra select field attributes
387 var $attributes = array();
395 * @var string post or get
402 var $class = 'singleselect';
404 * True if button disabled, false if normal
407 var $disabled = false;
419 * List of attached actions
420 * @var array of component_action
422 var $helpicon = null;
425 * @param moodle_url $url form action target, includes hidden fields
426 * @param string $name name of selection field - the changing parameter in url
427 * @param array $options list of options
428 * @param string $selected selected element
429 * @param array $nothing
430 * @param string $formid
432 public function __construct(moodle_url $url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
435 $this->options = $options;
436 $this->selected = $selected;
437 $this->nothing = $nothing;
438 $this->formid = $formid;
442 * Shortcut for adding a JS confirm dialog when the button is clicked.
443 * The message must be a yes/no question.
444 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
447 public function add_confirm_action($confirmmessage) {
448 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
452 * Add action to the button.
453 * @param component_action $action
456 public function add_action(component_action $action) {
457 $this->actions[] = $action;
461 * Constructor: sets up the other components in case they are needed
462 * @param string $page The keyword that defines a help page
463 * @param string $title A descriptive text for accesibility only
464 * @param string $component
465 * @param bool $linktext add extra text to icon
468 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
469 $this->helpicon = new old_help_icon($helppage, $title, $component);
474 * @param string $label
477 public function set_label($label) {
478 $this->label = $label;
484 * Simple URL selection widget description.
485 * @copyright 2009 Petr Skoda
486 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
489 class url_select implements renderable {
491 * @var array $urls associative array value=>label ex.:
492 * array(1=>'One, 2=>Two)
493 * it is also possible to specify optgroup as complex label array ex.:
494 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
495 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
509 * Extra select field attributes
512 var $attributes = array();
522 var $class = 'urlselect';
524 * True if button disabled, false if normal
527 var $disabled = false;
539 * List of attached actions
540 * @var array of component_action
542 var $helpicon = null;
545 * @param array $urls list of options
546 * @param string $selected selected element
547 * @param array $nothing
548 * @param string $formid
550 public function __construct(array $urls, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
552 $this->selected = $selected;
553 $this->nothing = $nothing;
554 $this->formid = $formid;
558 * Constructor: sets up the other components in case they are needed
559 * @param string $page The keyword that defines a help page
560 * @param string $title A descriptive text for accesibility only
561 * @param string $component
562 * @param bool $linktext add extra text to icon
565 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
566 $this->helpicon = new old_help_icon($helppage, $title, $component);
571 * @param string $label
574 public function set_label($label) {
575 $this->label = $label;
581 * Data structure describing html link with special action attached.
582 * @copyright 2010 Petr Skoda
583 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
586 class action_link implements renderable {
594 * @var string HTML fragment
603 * List of actions attached to link
604 * @var array of component_action
610 * @param string|moodle_url $url
611 * @param string $text HTML fragment
612 * @param component_action $action
613 * @param array $attributes associative array of html link attributes + disabled
615 public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null) {
616 $this->url = clone($url);
618 $this->attributes = (array)$attributes;
620 $this->add_action($action);
625 * Add action to the link.
626 * @param component_action $action
629 public function add_action(component_action $action) {
630 $this->actions[] = $action;
633 public function add_class($class) {
634 if (empty($this->attributes['class'])) {
635 $this->attributes['class'] = $class;
637 $this->attributes['class'] .= ' ' . $class;
642 // ==== HTML writer and helper classes, will be probably moved elsewhere ======
645 * Simple html output class
646 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
650 * Outputs a tag with attributes and contents
651 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
652 * @param string $contents What goes between the opening and closing tags
653 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
654 * @return string HTML fragment
656 public static function tag($tagname, $contents, array $attributes = null) {
657 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
661 * Outputs an opening tag with attributes
662 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
663 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
664 * @return string HTML fragment
666 public static function start_tag($tagname, array $attributes = null) {
667 return '<' . $tagname . self::attributes($attributes) . '>';
671 * Outputs a closing tag
672 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
673 * @return string HTML fragment
675 public static function end_tag($tagname) {
676 return '</' . $tagname . '>';
680 * Outputs an empty tag with attributes
681 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
682 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
683 * @return string HTML fragment
685 public static function empty_tag($tagname, array $attributes = null) {
686 return '<' . $tagname . self::attributes($attributes) . ' />';
690 * Outputs a HTML attribute and value
691 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
692 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
693 * @return string HTML fragment
695 public static function attribute($name, $value) {
696 if (is_array($value)) {
697 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
699 if ($value instanceof moodle_url) {
700 return ' ' . $name . '="' . $value->out() . '"';
703 // special case, we do not want these in output
704 if ($value === null) {
708 // no sloppy trimming here!
709 return ' ' . $name . '="' . s($value) . '"';
713 * Outputs a list of HTML attributes and values
714 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
715 * The values will be escaped with {@link s()}
716 * @return string HTML fragment
718 public static function attributes(array $attributes = null) {
719 $attributes = (array)$attributes;
721 foreach ($attributes as $name => $value) {
722 $output .= self::attribute($name, $value);
728 * Generates random html element id.
729 * @param string $base
732 public static function random_id($base='random') {
733 return uniqid($base);
737 * Generates a simple html link
738 * @param string|moodle_url $url
739 * @param string $text link txt
740 * @param array $attributes extra html attributes
741 * @return string HTML fragment
743 public static function link($url, $text, array $attributes = null) {
744 $attributes = (array)$attributes;
745 $attributes['href'] = $url;
746 return self::tag('a', $text, $attributes);
750 * generates a simple checkbox with optional label
751 * @param string $name
752 * @param string $value
753 * @param bool $checked
754 * @param string $label
755 * @param array $attributes
756 * @return string html fragment
758 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
759 $attributes = (array)$attributes;
762 if ($label !== '' and !is_null($label)) {
763 if (empty($attributes['id'])) {
764 $attributes['id'] = self::random_id('checkbox_');
767 $attributes['type'] = 'checkbox';
768 $attributes['value'] = $value;
769 $attributes['name'] = $name;
770 $attributes['checked'] = $checked ? 'selected' : null;
772 $output .= self::empty_tag('input', $attributes);
774 if ($label !== '' and !is_null($label)) {
775 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
782 * Generates a simple select yes/no form field
783 * @param string $name name of select element
784 * @param bool $selected
785 * @param array $attributes - html select element attributes
786 * @return string HRML fragment
788 public static function select_yes_no($name, $selected=true, array $attributes = null) {
789 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
790 return self::select($options, $name, $selected, null, $attributes);
794 * Generates a simple select form field
795 * @param array $options associative array value=>label ex.:
796 * array(1=>'One, 2=>Two)
797 * it is also possible to specify optgroup as complex label array ex.:
798 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
799 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
800 * @param string $name name of select element
801 * @param string|array $selected value or arary of values depending on multiple attribute
802 * @param array|bool $nothing, add nothing selected option, or false of not added
803 * @param array $attributes - html select element attributes
804 * @return string HTML fragment
806 public static function select(array $options, $name, $selected = '', $nothing = array(''=>'choosedots'), array $attributes = null) {
807 $attributes = (array)$attributes;
808 if (is_array($nothing)) {
809 foreach ($nothing as $k=>$v) {
810 if ($v === 'choose' or $v === 'choosedots') {
811 $nothing[$k] = get_string('choosedots');
814 $options = $nothing + $options; // keep keys, do not override
816 } else if (is_string($nothing) and $nothing !== '') {
818 $options = array(''=>$nothing) + $options;
821 // we may accept more values if multiple attribute specified
822 $selected = (array)$selected;
823 foreach ($selected as $k=>$v) {
824 $selected[$k] = (string)$v;
827 if (!isset($attributes['id'])) {
829 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
830 $id = str_replace('[', '', $id);
831 $id = str_replace(']', '', $id);
832 $attributes['id'] = $id;
835 if (!isset($attributes['class'])) {
836 $class = 'menu'.$name;
837 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
838 $class = str_replace('[', '', $class);
839 $class = str_replace(']', '', $class);
840 $attributes['class'] = $class;
842 $attributes['class'] = 'select ' . $attributes['class']; /// Add 'select' selector always
844 $attributes['name'] = $name;
847 foreach ($options as $value=>$label) {
848 if (is_array($label)) {
849 // ignore key, it just has to be unique
850 $output .= self::select_optgroup(key($label), current($label), $selected);
852 $output .= self::select_option($label, $value, $selected);
855 return self::tag('select', $output, $attributes);
858 private static function select_option($label, $value, array $selected) {
859 $attributes = array();
860 $value = (string)$value;
861 if (in_array($value, $selected, true)) {
862 $attributes['selected'] = 'selected';
864 $attributes['value'] = $value;
865 return self::tag('option', $label, $attributes);
868 private static function select_optgroup($groupname, $options, array $selected) {
869 if (empty($options)) {
872 $attributes = array('label'=>$groupname);
874 foreach ($options as $value=>$label) {
875 $output .= self::select_option($label, $value, $selected);
877 return self::tag('optgroup', $output, $attributes);
881 * This is a shortcut for making an hour selector menu.
882 * @param string $type The type of selector (years, months, days, hours, minutes)
883 * @param string $name fieldname
884 * @param int $currenttime A default timestamp in GMT
885 * @param int $step minute spacing
886 * @param array $attributes - html select element attributes
887 * @return HTML fragment
889 public static function select_time($type, $name, $currenttime=0, $step=5, array $attributes=null) {
891 $currenttime = time();
893 $currentdate = usergetdate($currenttime);
894 $userdatetype = $type;
895 $timeunits = array();
899 for ($i=1970; $i<=2020; $i++) {
902 $userdatetype = 'year';
905 for ($i=1; $i<=12; $i++) {
906 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
908 $userdatetype = 'month';
909 $currentdate['month'] = $currentdate['mon'];
912 for ($i=1; $i<=31; $i++) {
915 $userdatetype = 'mday';
918 for ($i=0; $i<=23; $i++) {
919 $timeunits[$i] = sprintf("%02d",$i);
924 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
927 for ($i=0; $i<=59; $i+=$step) {
928 $timeunits[$i] = sprintf("%02d",$i);
932 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
935 if (empty($attributes['id'])) {
936 $attributes['id'] = self::random_id('ts_');
938 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
939 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
941 return $label.$timerselector;
945 * Shortcut for quick making of lists
946 * @param array $items
947 * @param string $tag ul or ol
948 * @param array $attributes
951 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
952 //note: 'list' is a reserved keyword ;-)
956 foreach ($items as $item) {
957 $output .= html_writer::start_tag('li') . "\n";
958 $output .= $item . "\n";
959 $output .= html_writer::end_tag('li') . "\n";
962 return html_writer::tag($tag, $output, $attributes);
966 * Returns hidden input fields created from url parameters.
967 * @param moodle_url $url
968 * @param array $exclude list of excluded parameters
969 * @return string HTML fragment
971 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
972 $exclude = (array)$exclude;
973 $params = $url->params();
974 foreach ($exclude as $key) {
975 unset($params[$key]);
979 foreach ($params as $key => $value) {
980 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
981 $output .= self::empty_tag('input', $attributes)."\n";
987 * Generate a script tag containing the the specified code.
989 * @param string $js the JavaScript code
990 * @param moodle_url|string optional url of the external script, $code ignored if specified
991 * @return string HTML, the code wrapped in <script> tags.
993 public static function script($jscode, $url=null) {
995 $attributes = array('type'=>'text/javascript');
996 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
999 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1000 return self::tag('script', '', $attributes) . "\n";
1008 * Renders HTML table
1010 * This method may modify the passed instance by adding some default properties if they are not set yet.
1011 * If this is not what you want, you should make a full clone of your data before passing them to this
1012 * method. In most cases this is not an issue at all so we do not clone by default for performance
1013 * and memory consumption reasons.
1015 * @param html_table $table data to be rendered
1016 * @return string HTML code
1018 public static function table(html_table $table) {
1019 // prepare table data and populate missing properties with reasonable defaults
1020 if (!empty($table->align)) {
1021 foreach ($table->align as $key => $aa) {
1023 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1025 $table->align[$key] = null;
1029 if (!empty($table->size)) {
1030 foreach ($table->size as $key => $ss) {
1032 $table->size[$key] = 'width:'. $ss .';';
1034 $table->size[$key] = null;
1038 if (!empty($table->wrap)) {
1039 foreach ($table->wrap as $key => $ww) {
1041 $table->wrap[$key] = 'white-space:nowrap;';
1043 $table->wrap[$key] = '';
1047 if (!empty($table->head)) {
1048 foreach ($table->head as $key => $val) {
1049 if (!isset($table->align[$key])) {
1050 $table->align[$key] = null;
1052 if (!isset($table->size[$key])) {
1053 $table->size[$key] = null;
1055 if (!isset($table->wrap[$key])) {
1056 $table->wrap[$key] = null;
1061 if (empty($table->attributes['class'])) {
1062 $table->attributes['class'] = 'generaltable';
1064 if (!empty($table->tablealign)) {
1065 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1068 // explicitly assigned properties override those defined via $table->attributes
1069 $table->attributes['class'] = trim($table->attributes['class']);
1070 $attributes = array_merge($table->attributes, array(
1072 'width' => $table->width,
1073 'summary' => $table->summary,
1074 'cellpadding' => $table->cellpadding,
1075 'cellspacing' => $table->cellspacing,
1077 $output = html_writer::start_tag('table', $attributes) . "\n";
1081 if (!empty($table->head)) {
1082 $countcols = count($table->head);
1083 $output .= html_writer::start_tag('thead', array()) . "\n";
1084 $output .= html_writer::start_tag('tr', array()) . "\n";
1085 $keys = array_keys($table->head);
1086 $lastkey = end($keys);
1088 foreach ($table->head as $key => $heading) {
1089 // Convert plain string headings into html_table_cell objects
1090 if (!($heading instanceof html_table_cell)) {
1091 $headingtext = $heading;
1092 $heading = new html_table_cell();
1093 $heading->text = $headingtext;
1094 $heading->header = true;
1097 if ($heading->header !== false) {
1098 $heading->header = true;
1101 if ($heading->header && empty($heading->scope)) {
1102 $heading->scope = 'col';
1105 $heading->attributes['class'] .= ' header c' . $key;
1106 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1107 $heading->colspan = $table->headspan[$key];
1108 $countcols += $table->headspan[$key] - 1;
1111 if ($key == $lastkey) {
1112 $heading->attributes['class'] .= ' lastcol';
1114 if (isset($table->colclasses[$key])) {
1115 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1117 $heading->attributes['class'] = trim($heading->attributes['class']);
1118 $attributes = array_merge($heading->attributes, array(
1119 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1120 'scope' => $heading->scope,
1121 'colspan' => $heading->colspan,
1125 if ($heading->header === true) {
1128 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1130 $output .= html_writer::end_tag('tr') . "\n";
1131 $output .= html_writer::end_tag('thead') . "\n";
1133 if (empty($table->data)) {
1134 // For valid XHTML strict every table must contain either a valid tr
1135 // or a valid tbody... both of which must contain a valid td
1136 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1137 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1138 $output .= html_writer::end_tag('tbody');
1142 if (!empty($table->data)) {
1144 $keys = array_keys($table->data);
1145 $lastrowkey = end($keys);
1146 $output .= html_writer::start_tag('tbody', array());
1148 foreach ($table->data as $key => $row) {
1149 if (($row === 'hr') && ($countcols)) {
1150 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1152 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1153 if (!($row instanceof html_table_row)) {
1154 $newrow = new html_table_row();
1156 foreach ($row as $item) {
1157 $cell = new html_table_cell();
1158 $cell->text = $item;
1159 $newrow->cells[] = $cell;
1164 $oddeven = $oddeven ? 0 : 1;
1165 if (isset($table->rowclasses[$key])) {
1166 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1169 $row->attributes['class'] .= ' r' . $oddeven;
1170 if ($key == $lastrowkey) {
1171 $row->attributes['class'] .= ' lastrow';
1174 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1175 $keys2 = array_keys($row->cells);
1176 $lastkey = end($keys2);
1178 foreach ($row->cells as $key => $cell) {
1179 if (!($cell instanceof html_table_cell)) {
1180 $mycell = new html_table_cell();
1181 $mycell->text = $cell;
1185 if (($cell->header === true) && empty($cell->scope)) {
1186 $cell->scope = 'row';
1189 if (isset($table->colclasses[$key])) {
1190 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1193 $cell->attributes['class'] .= ' cell c' . $key;
1194 if ($key == $lastkey) {
1195 $cell->attributes['class'] .= ' lastcol';
1198 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1199 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1200 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1201 $cell->attributes['class'] = trim($cell->attributes['class']);
1202 $tdattributes = array_merge($cell->attributes, array(
1203 'style' => $tdstyle . $cell->style,
1204 'colspan' => $cell->colspan,
1205 'rowspan' => $cell->rowspan,
1207 'abbr' => $cell->abbr,
1208 'scope' => $cell->scope,
1211 if ($cell->header === true) {
1214 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1217 $output .= html_writer::end_tag('tr') . "\n";
1219 $output .= html_writer::end_tag('tbody') . "\n";
1221 $output .= html_writer::end_tag('table') . "\n";
1228 // ==== JS writer and helper classes, will be probably moved elsewhere ======
1231 * Simple javascript output class
1232 * @copyright 2010 Petr Skoda
1236 * Returns javascript code calling the function
1237 * @param string $function function name, can be complex lin Y.Event.purgeElement
1238 * @param array $arguments parameters
1239 * @param int $delay execution delay in seconds
1240 * @return string JS code fragment
1242 public function function_call($function, array $arguments = null, $delay=0) {
1244 $arguments = array_map('json_encode', $arguments);
1245 $arguments = implode(', ', $arguments);
1249 $js = "$function($arguments);";
1252 $delay = $delay * 1000; // in miliseconds
1253 $js = "setTimeout(function() { $js }, $delay);";
1259 * Special function which adds Y as first argument of fucntion call.
1260 * @param string $function
1261 * @param array $extraarguments
1264 public function function_call_with_Y($function, array $extraarguments = null) {
1265 if ($extraarguments) {
1266 $extraarguments = array_map('json_encode', $extraarguments);
1267 $arguments = 'Y, ' . implode(', ', $extraarguments);
1271 return "$function($arguments);\n";
1275 * Returns JavaScript code to initialise a new object
1276 * @param string|null $var If it is null then no var is assigned the new object
1277 * @param string $class
1278 * @param array $arguments
1279 * @param array $requirements
1283 public function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1284 if (is_array($arguments)) {
1285 $arguments = array_map('json_encode', $arguments);
1286 $arguments = implode(', ', $arguments);
1289 if ($var === null) {
1290 $js = "new $class(Y, $arguments);";
1291 } else if (strpos($var, '.')!==false) {
1292 $js = "$var = new $class(Y, $arguments);";
1294 $js = "var $var = new $class(Y, $arguments);";
1298 $delay = $delay * 1000; // in miliseconds
1299 $js = "setTimeout(function() { $js }, $delay);";
1302 if (count($requirements) > 0) {
1303 $requirements = implode("', '", $requirements);
1304 $js = "Y.use('$requirements', function(Y){ $js });";
1310 * Returns code setting value to variable
1311 * @param string $name
1312 * @param mixed $value json serialised value
1313 * @param bool $usevar add var definition, ignored for nested properties
1314 * @return string JS code fragment
1316 public function set_variable($name, $value, $usevar=true) {
1320 if (strpos($name, '.')) {
1327 $output .= "$name = ".json_encode($value).";";
1333 * Writes event handler attaching code
1334 * @param mixed $selector standard YUI selector for elemnts, may be array or string, element id is in the form "#idvalue"
1335 * @param string $event A valid DOM event (click, mousedown, change etc.)
1336 * @param string $function The name of the function to call
1337 * @param array $arguments An optional array of argument parameters to pass to the function
1338 * @return string JS code fragment
1340 public function event_handler($selector, $event, $function, array $arguments = null) {
1341 $selector = json_encode($selector);
1342 $output = "Y.on('$event', $function, $selector, null";
1343 if (!empty($arguments)) {
1344 $output .= ', ' . json_encode($arguments);
1346 return $output . ");\n";
1351 * Holds all the information required to render a <table> by {@see core_renderer::table()}
1354 * $t = new html_table();
1355 * ... // set various properties of the object $t as described below
1356 * echo html_writer::table($t);
1358 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1359 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1364 * @var string value to use for the id attribute of the table
1368 * @var array attributes of HTML attributes for the <table> element
1370 public $attributes = array();
1372 * For more control over the rendering of the headers, an array of html_table_cell objects
1373 * can be passed instead of an array of strings.
1374 * @var array of headings. The n-th array item is used as a heading of the n-th column.
1377 * $t->head = array('Student', 'Grade');
1381 * @var array can be used to make a heading span multiple columns
1384 * $t->headspan = array(2,1);
1386 * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
1387 * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
1391 * @var array of column alignments. The value is used as CSS 'text-align' property. Therefore, possible
1392 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1393 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1395 * Examples of usage:
1396 * $t->align = array(null, 'right');
1398 * $t->align[1] = 'right';
1403 * @var array of column sizes. The value is used as CSS 'size' property.
1405 * Examples of usage:
1406 * $t->size = array('50%', '50%');
1408 * $t->size[1] = '120px';
1412 * @var array of wrapping information. The only possible value is 'nowrap' that sets the
1413 * CSS property 'white-space' to the value 'nowrap' in the given column.
1416 * $t->wrap = array(null, 'nowrap');
1420 * @var array of arrays or html_table_row objects containing the data. Alternatively, if you have
1421 * $head specified, the string 'hr' (for horizontal ruler) can be used
1422 * instead of an array of cells data resulting in a divider rendered.
1424 * Example of usage with array of arrays:
1425 * $row1 = array('Harry Potter', '76 %');
1426 * $row2 = array('Hermione Granger', '100 %');
1427 * $t->data = array($row1, $row2);
1429 * Example with array of html_table_row objects: (used for more fine-grained control)
1430 * $cell1 = new html_table_cell();
1431 * $cell1->text = 'Harry Potter';
1432 * $cell1->colspan = 2;
1433 * $row1 = new html_table_row();
1434 * $row1->cells[] = $cell1;
1435 * $cell2 = new html_table_cell();
1436 * $cell2->text = 'Hermione Granger';
1437 * $cell3 = new html_table_cell();
1438 * $cell3->text = '100 %';
1439 * $row2 = new html_table_row();
1440 * $row2->cells = array($cell2, $cell3);
1441 * $t->data = array($row1, $row2);
1445 * @var string width of the table, percentage of the page preferred. Defaults to 80%
1446 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1448 public $width = null;
1450 * @var string alignment the whole table. Can be 'right', 'left' or 'center' (default).
1451 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1453 public $tablealign = null;
1455 * @var int padding on each cell, in pixels
1456 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1458 public $cellpadding = null;
1460 * @var int spacing between cells, in pixels
1461 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1463 public $cellspacing = null;
1465 * @var array classes to add to particular rows, space-separated string.
1466 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1467 * respectively. Class 'lastrow' is added automatically for the last row
1471 * $t->rowclasses[9] = 'tenth'
1475 * @var array classes to add to every cell in a particular column,
1476 * space-separated string. Class 'cell' is added automatically by the renderer.
1477 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1478 * respectively. Class 'lastcol' is added automatically for all last cells
1482 * $t->colclasses = array(null, 'grade');
1486 * @var string description of the contents for screen readers.
1493 public function __construct() {
1494 $this->attributes['class'] = '';
1500 * Component representing a table row.
1502 * @copyright 2009 Nicolas Connault
1503 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1506 class html_table_row {
1508 * @var string value to use for the id attribute of the row
1512 * @var array $cells Array of html_table_cell objects
1514 public $cells = array();
1516 * @var string $style value to use for the style attribute of the table row
1518 public $style = null;
1520 * @var array attributes of additional HTML attributes for the <tr> element
1522 public $attributes = array();
1526 * @param array $cells
1528 public function __construct(array $cells=null) {
1529 $this->attributes['class'] = '';
1530 $cells = (array)$cells;
1531 foreach ($cells as $cell) {
1532 if ($cell instanceof html_table_cell) {
1533 $this->cells[] = $cell;
1535 $this->cells[] = new html_table_cell($cell);
1543 * Component representing a table cell.
1545 * @copyright 2009 Nicolas Connault
1546 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1549 class html_table_cell {
1551 * @var string value to use for the id attribute of the cell
1555 * @var string $text The contents of the cell
1559 * @var string $abbr Abbreviated version of the contents of the cell
1561 public $abbr = null;
1563 * @var int $colspan Number of columns this cell should span
1565 public $colspan = null;
1567 * @var int $rowspan Number of rows this cell should span
1569 public $rowspan = null;
1571 * @var string $scope Defines a way to associate header cells and data cells in a table
1573 public $scope = null;
1575 * @var boolean $header Whether or not this cell is a header cell
1577 public $header = null;
1579 * @var string $style value to use for the style attribute of the table cell
1581 public $style = null;
1583 * @var array attributes of additional HTML attributes for the <tr> element
1585 public $attributes = array();
1587 public function __construct($text = null) {
1588 $this->text = $text;
1589 $this->attributes['class'] = '';
1594 /// Complex components aggregating simpler components
1598 * Component representing a paging bar.
1600 * @copyright 2009 Nicolas Connault
1601 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1604 class paging_bar implements renderable {
1606 * @var int $maxdisplay The maximum number of pagelinks to display
1608 public $maxdisplay = 18;
1610 * @var int $totalcount post or get
1614 * @var int $page The page you are currently viewing
1618 * @var int $perpage The number of entries that should be shown per page
1622 * @var string $baseurl If this is a string then it is the url which will be appended with $pagevar, an equals sign and the page number.
1623 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
1627 * @var string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
1631 * @var string $previouslink A HTML link representing the "previous" page
1633 public $previouslink = null;
1635 * @var tring $nextlink A HTML link representing the "next" page
1637 public $nextlink = null;
1639 * @var tring $firstlink A HTML link representing the first page
1641 public $firstlink = null;
1643 * @var tring $lastlink A HTML link representing the last page
1645 public $lastlink = null;
1647 * @var array $pagelinks An array of strings. One of them is just a string: the current page
1649 public $pagelinks = array();
1652 * Constructor paging_bar with only the required params.
1654 * @param int $totalcount Thetotal number of entries available to be paged through
1655 * @param int $page The page you are currently viewing
1656 * @param int $perpage The number of entries that should be shown per page
1657 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
1658 * @param string $pagevar name of page parameter that holds the page number
1660 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
1661 $this->totalcount = $totalcount;
1662 $this->page = $page;
1663 $this->perpage = $perpage;
1664 $this->baseurl = $baseurl;
1665 $this->pagevar = $pagevar;
1671 public function prepare(renderer_base $output, moodle_page $page, $target) {
1672 if (!isset($this->totalcount) || is_null($this->totalcount)) {
1673 throw new coding_exception('paging_bar requires a totalcount value.');
1675 if (!isset($this->page) || is_null($this->page)) {
1676 throw new coding_exception('paging_bar requires a page value.');
1678 if (empty($this->perpage)) {
1679 throw new coding_exception('paging_bar requires a perpage value.');
1681 if (empty($this->baseurl)) {
1682 throw new coding_exception('paging_bar requires a baseurl value.');
1685 if ($this->totalcount > $this->perpage) {
1686 $pagenum = $this->page - 1;
1688 if ($this->page > 0) {
1689 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
1692 if ($this->perpage > 0) {
1693 $lastpage = ceil($this->totalcount / $this->perpage);
1698 if ($this->page > 15) {
1699 $startpage = $this->page - 10;
1701 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
1706 $currpage = $startpage;
1707 $displaycount = $displaypage = 0;
1709 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
1710 $displaypage = $currpage + 1;
1712 if ($this->page == $currpage) {
1713 $this->pagelinks[] = $displaypage;
1715 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
1716 $this->pagelinks[] = $pagelink;
1723 if ($currpage < $lastpage) {
1724 $lastpageactual = $lastpage - 1;
1725 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
1728 $pagenum = $this->page + 1;
1730 if ($pagenum != $displaypage) {
1731 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
1739 * This class represents how a block appears on a page.
1741 * During output, each block instance is asked to return a block_contents object,
1742 * those are then passed to the $OUTPUT->block function for display.
1744 * {@link $contents} should probably be generated using a moodle_block_..._renderer.
1746 * Other block-like things that need to appear on the page, for example the
1747 * add new block UI, are also represented as block_contents objects.
1749 * @copyright 2009 Tim Hunt
1750 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1753 class block_contents {
1754 /** @var int used to set $skipid. */
1755 protected static $idcounter = 1;
1757 const NOT_HIDEABLE = 0;
1762 * @var integer $skipid All the blocks (or things that look like blocks)
1763 * printed on a page are given a unique number that can be used to construct
1764 * id="" attributes. This is set automatically be the {@link prepare()} method.
1765 * Do not try to set it manually.
1770 * @var integer If this is the contents of a real block, this should be set to
1771 * the block_instance.id. Otherwise this should be set to 0.
1773 public $blockinstanceid = 0;
1776 * @var integer if this is a real block instance, and there is a corresponding
1777 * block_position.id for the block on this page, this should be set to that id.
1778 * Otherwise it should be 0.
1780 public $blockpositionid = 0;
1783 * @param array $attributes an array of attribute => value pairs that are put on the
1784 * outer div of this block. {@link $id} and {@link $classes} attributes should be set separately.
1789 * @param string $title The title of this block. If this came from user input,
1790 * it should already have had format_string() processing done on it. This will
1791 * be output inside <h2> tags. Please do not cause invalid XHTML.
1796 * @param string $content HTML for the content
1798 public $content = '';
1801 * @param array $list an alternative to $content, it you want a list of things with optional icons.
1803 public $footer = '';
1806 * Any small print that should appear under the block to explain to the
1807 * teacher about the block, for example 'This is a sticky block that was
1808 * added in the system context.'
1811 public $annotation = '';
1814 * @var integer one of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
1815 * the user can toggle whether this block is visible.
1817 public $collapsible = self::NOT_HIDEABLE;
1820 * A (possibly empty) array of editing controls. Each element of this array
1821 * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
1822 * $icon is the icon name. Fed to $OUTPUT->pix_url.
1825 public $controls = array();
1829 * Create new instance of block content
1830 * @param array $attributes
1832 public function __construct(array $attributes=null) {
1833 $this->skipid = self::$idcounter;
1834 self::$idcounter += 1;
1838 $this->attributes = $attributes;
1840 // simple "fake" blocks used in some modules and "Add new block" block
1841 $this->attributes = array('class'=>'sideblock');
1846 * Add html class to block
1847 * @param string $class
1850 public function add_class($class) {
1851 $this->attributes['class'] .= ' '.$class;
1857 * This class represents a target for where a block can go when it is being moved.
1859 * This needs to be rendered as a form with the given hidden from fields, and
1860 * clicking anywhere in the form should submit it. The form action should be
1863 * @copyright 2009 Tim Hunt
1864 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1867 class block_move_target {
1881 * @param string $text
1882 * @param moodle_url $url
1884 public function __construct($text, moodle_url $url) {
1885 $this->text = $text;