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'];
558 * Data structure representing an emoticon image
560 * @copyright 2010 David Mudrak
561 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
566 class pix_emoticon
extends pix_icon
implements renderable
{
570 * @param string $pix short icon name
571 * @param string $alt alternative text
572 * @param string $component emoticon image provider
573 * @param array $attributes explicit HTML attributes
575 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
576 if (empty($attributes['class'])) {
577 $attributes['class'] = 'emoticon';
579 parent
::__construct($pix, $alt, $component, $attributes);
584 * Data structure representing a simple form with only one button.
586 * @copyright 2009 Petr Skoda
587 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
592 class single_button
implements renderable
{
595 * @var moodle_url Target url
600 * @var string Button label
605 * @var string Form submit method post or get
607 var $method = 'post';
610 * @var string Wrapping div class
612 var $class = 'singlebutton';
615 * @var bool True if button disabled, false if normal
617 var $disabled = false;
620 * @var string Button tooltip
625 * @var string Form id
630 * @var array List of attached actions
632 var $actions = array();
636 * @param moodle_url $url
637 * @param string $label button text
638 * @param string $method get or post submit method
640 public function __construct(moodle_url
$url, $label, $method='post') {
641 $this->url
= clone($url);
642 $this->label
= $label;
643 $this->method
= $method;
647 * Shortcut for adding a JS confirm dialog when the button is clicked.
648 * The message must be a yes/no question.
650 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
652 public function add_confirm_action($confirmmessage) {
653 $this->add_action(new confirm_action($confirmmessage));
657 * Add action to the button.
658 * @param component_action $action
660 public function add_action(component_action
$action) {
661 $this->actions
[] = $action;
667 * Simple form with just one select field that gets submitted automatically.
669 * If JS not enabled small go button is printed too.
671 * @copyright 2009 Petr Skoda
672 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
677 class single_select
implements renderable
{
680 * @var moodle_url Target url - includes hidden fields
685 * @var string Name of the select element.
690 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
691 * it is also possible to specify optgroup as complex label array ex.:
692 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
693 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
698 * @var string Selected option
703 * @var array Nothing selected
708 * @var array Extra select field attributes
710 var $attributes = array();
713 * @var string Button label
718 * @var array Button label's attributes
720 var $labelattributes = array();
723 * @var string Form submit method post or get
728 * @var string Wrapping div class
730 var $class = 'singleselect';
733 * @var bool True if button disabled, false if normal
735 var $disabled = false;
738 * @var string Button tooltip
743 * @var string Form id
748 * @var array List of attached actions
750 var $helpicon = null;
754 * @param moodle_url $url form action target, includes hidden fields
755 * @param string $name name of selection field - the changing parameter in url
756 * @param array $options list of options
757 * @param string $selected selected element
758 * @param array $nothing
759 * @param string $formid
761 public function __construct(moodle_url
$url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
764 $this->options
= $options;
765 $this->selected
= $selected;
766 $this->nothing
= $nothing;
767 $this->formid
= $formid;
771 * Shortcut for adding a JS confirm dialog when the button is clicked.
772 * The message must be a yes/no question.
774 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
776 public function add_confirm_action($confirmmessage) {
777 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
781 * Add action to the button.
783 * @param component_action $action
785 public function add_action(component_action
$action) {
786 $this->actions
[] = $action;
792 * @param string $helppage The keyword that defines a help page
793 * @param string $title A descriptive text for accessibility only
794 * @param string $component
796 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
797 $this->helpicon
= new old_help_icon($helppage, $title, $component);
803 * @param string $identifier The keyword that defines a help page
804 * @param string $component
806 public function set_help_icon($identifier, $component = 'moodle') {
807 $this->helpicon
= new help_icon($identifier, $component);
811 * Sets select's label
813 * @param string $label
814 * @param array $attributes (optional)
816 public function set_label($label, $attributes = array()) {
817 $this->label
= $label;
818 $this->labelattributes
= $attributes;
824 * Simple URL selection widget description.
826 * @copyright 2009 Petr Skoda
827 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
832 class url_select
implements renderable
{
834 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
835 * it is also possible to specify optgroup as complex label array ex.:
836 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
837 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
842 * @var string Selected option
847 * @var array Nothing selected
852 * @var array Extra select field attributes
854 var $attributes = array();
857 * @var string Button label
862 * @var array Button label's attributes
864 var $labelattributes = array();
867 * @var string Wrapping div class
869 var $class = 'urlselect';
872 * @var bool True if button disabled, false if normal
874 var $disabled = false;
877 * @var string Button tooltip
882 * @var string Form id
887 * @var array List of attached actions
889 var $helpicon = null;
892 * @var string If set, makes button visible with given name for button
894 var $showbutton = null;
898 * @param array $urls list of options
899 * @param string $selected selected element
900 * @param array $nothing
901 * @param string $formid
902 * @param string $showbutton Set to text of button if it should be visible
903 * or null if it should be hidden (hidden version always has text 'go')
905 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
907 $this->selected
= $selected;
908 $this->nothing
= $nothing;
909 $this->formid
= $formid;
910 $this->showbutton
= $showbutton;
916 * @param string $helppage The keyword that defines a help page
917 * @param string $title A descriptive text for accessibility only
918 * @param string $component
920 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
921 $this->helpicon
= new old_help_icon($helppage, $title, $component);
927 * @param string $identifier The keyword that defines a help page
928 * @param string $component
930 public function set_help_icon($identifier, $component = 'moodle') {
931 $this->helpicon
= new help_icon($identifier, $component);
935 * Sets select's label
937 * @param string $label
938 * @param array $attributes (optional)
940 public function set_label($label, $attributes = array()) {
941 $this->label
= $label;
942 $this->labelattributes
= $attributes;
947 * Data structure describing html link with special action attached.
949 * @copyright 2010 Petr Skoda
950 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
955 class action_link
implements renderable
{
958 * @var moodle_url Href url
963 * @var string Link text HTML fragment
968 * @var array HTML attributes
973 * @var array List of actions attached to link
979 * @param moodle_url $url
980 * @param string $text HTML fragment
981 * @param component_action $action
982 * @param array $attributes associative array of html link attributes + disabled
984 public function __construct(moodle_url
$url, $text, component_action
$action = null, array $attributes = null) {
985 $this->url
= clone($url);
987 $this->attributes
= (array)$attributes;
989 $this->add_action($action);
994 * Add action to the link.
996 * @param component_action $action
998 public function add_action(component_action
$action) {
999 $this->actions
[] = $action;
1003 * Adds a CSS class to this action link object
1004 * @param string $class
1006 public function add_class($class) {
1007 if (empty($this->attributes
['class'])) {
1008 $this->attributes
['class'] = $class;
1010 $this->attributes
['class'] .= ' ' . $class;
1016 * Simple html output class
1018 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1019 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1027 * Outputs a tag with attributes and contents
1029 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1030 * @param string $contents What goes between the opening and closing tags
1031 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1032 * @return string HTML fragment
1034 public static function tag($tagname, $contents, array $attributes = null) {
1035 return self
::start_tag($tagname, $attributes) . $contents . self
::end_tag($tagname);
1039 * Outputs an opening tag with attributes
1041 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1042 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1043 * @return string HTML fragment
1045 public static function start_tag($tagname, array $attributes = null) {
1046 return '<' . $tagname . self
::attributes($attributes) . '>';
1050 * Outputs a closing tag
1052 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1053 * @return string HTML fragment
1055 public static function end_tag($tagname) {
1056 return '</' . $tagname . '>';
1060 * Outputs an empty tag with attributes
1062 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1063 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1064 * @return string HTML fragment
1066 public static function empty_tag($tagname, array $attributes = null) {
1067 return '<' . $tagname . self
::attributes($attributes) . ' />';
1071 * Outputs a tag, but only if the contents are not empty
1073 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1074 * @param string $contents What goes between the opening and closing tags
1075 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1076 * @return string HTML fragment
1078 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1079 if ($contents === '' ||
is_null($contents)) {
1082 return self
::tag($tagname, $contents, $attributes);
1086 * Outputs a HTML attribute and value
1088 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1089 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1090 * @return string HTML fragment
1092 public static function attribute($name, $value) {
1093 if (is_array($value)) {
1094 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER
);
1096 if ($value instanceof moodle_url
) {
1097 return ' ' . $name . '="' . $value->out() . '"';
1100 // special case, we do not want these in output
1101 if ($value === null) {
1105 // no sloppy trimming here!
1106 return ' ' . $name . '="' . s($value) . '"';
1110 * Outputs a list of HTML attributes and values
1112 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1113 * The values will be escaped with {@link s()}
1114 * @return string HTML fragment
1116 public static function attributes(array $attributes = null) {
1117 $attributes = (array)$attributes;
1119 foreach ($attributes as $name => $value) {
1120 $output .= self
::attribute($name, $value);
1126 * Generates random html element id.
1128 * @staticvar int $counter
1129 * @staticvar type $uniq
1130 * @param string $base A string fragment that will be included in the random ID.
1131 * @return string A unique ID
1133 public static function random_id($base='random') {
1134 static $counter = 0;
1137 if (!isset($uniq)) {
1142 return $base.$uniq.$counter;
1146 * Generates a simple html link
1148 * @param string|moodle_url $url The URL
1149 * @param string $text The text
1150 * @param array $attributes HTML attributes
1151 * @return string HTML fragment
1153 public static function link($url, $text, array $attributes = null) {
1154 $attributes = (array)$attributes;
1155 $attributes['href'] = $url;
1156 return self
::tag('a', $text, $attributes);
1160 * Generates a simple checkbox with optional label
1162 * @param string $name The name of the checkbox
1163 * @param string $value The value of the checkbox
1164 * @param bool $checked Whether the checkbox is checked
1165 * @param string $label The label for the checkbox
1166 * @param array $attributes Any attributes to apply to the checkbox
1167 * @return string html fragment
1169 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1170 $attributes = (array)$attributes;
1173 if ($label !== '' and !is_null($label)) {
1174 if (empty($attributes['id'])) {
1175 $attributes['id'] = self
::random_id('checkbox_');
1178 $attributes['type'] = 'checkbox';
1179 $attributes['value'] = $value;
1180 $attributes['name'] = $name;
1181 $attributes['checked'] = $checked ?
'checked' : null;
1183 $output .= self
::empty_tag('input', $attributes);
1185 if ($label !== '' and !is_null($label)) {
1186 $output .= self
::tag('label', $label, array('for'=>$attributes['id']));
1193 * Generates a simple select yes/no form field
1195 * @param string $name name of select element
1196 * @param bool $selected
1197 * @param array $attributes - html select element attributes
1198 * @return string HTML fragment
1200 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1201 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1202 return self
::select($options, $name, $selected, null, $attributes);
1206 * Generates a simple select form field
1208 * @param array $options associative array value=>label ex.:
1209 * array(1=>'One, 2=>Two)
1210 * it is also possible to specify optgroup as complex label array ex.:
1211 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1212 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1213 * @param string $name name of select element
1214 * @param string|array $selected value or array of values depending on multiple attribute
1215 * @param array|bool $nothing add nothing selected option, or false of not added
1216 * @param array $attributes html select element attributes
1217 * @return string HTML fragment
1219 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1220 $attributes = (array)$attributes;
1221 if (is_array($nothing)) {
1222 foreach ($nothing as $k=>$v) {
1223 if ($v === 'choose' or $v === 'choosedots') {
1224 $nothing[$k] = get_string('choosedots');
1227 $options = $nothing +
$options; // keep keys, do not override
1229 } else if (is_string($nothing) and $nothing !== '') {
1231 $options = array(''=>$nothing) +
$options;
1234 // we may accept more values if multiple attribute specified
1235 $selected = (array)$selected;
1236 foreach ($selected as $k=>$v) {
1237 $selected[$k] = (string)$v;
1240 if (!isset($attributes['id'])) {
1242 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1243 $id = str_replace('[', '', $id);
1244 $id = str_replace(']', '', $id);
1245 $attributes['id'] = $id;
1248 if (!isset($attributes['class'])) {
1249 $class = 'menu'.$name;
1250 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1251 $class = str_replace('[', '', $class);
1252 $class = str_replace(']', '', $class);
1253 $attributes['class'] = $class;
1255 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
1257 $attributes['name'] = $name;
1259 if (!empty($attributes['disabled'])) {
1260 $attributes['disabled'] = 'disabled';
1262 unset($attributes['disabled']);
1266 foreach ($options as $value=>$label) {
1267 if (is_array($label)) {
1268 // ignore key, it just has to be unique
1269 $output .= self
::select_optgroup(key($label), current($label), $selected);
1271 $output .= self
::select_option($label, $value, $selected);
1274 return self
::tag('select', $output, $attributes);
1278 * Returns HTML to display a select box option.
1280 * @param string $label The label to display as the option.
1281 * @param string|int $value The value the option represents
1282 * @param array $selected An array of selected options
1283 * @return string HTML fragment
1285 private static function select_option($label, $value, array $selected) {
1286 $attributes = array();
1287 $value = (string)$value;
1288 if (in_array($value, $selected, true)) {
1289 $attributes['selected'] = 'selected';
1291 $attributes['value'] = $value;
1292 return self
::tag('option', $label, $attributes);
1296 * Returns HTML to display a select box option group.
1298 * @param string $groupname The label to use for the group
1299 * @param array $options The options in the group
1300 * @param array $selected An array of selected values.
1301 * @return string HTML fragment.
1303 private static function select_optgroup($groupname, $options, array $selected) {
1304 if (empty($options)) {
1307 $attributes = array('label'=>$groupname);
1309 foreach ($options as $value=>$label) {
1310 $output .= self
::select_option($label, $value, $selected);
1312 return self
::tag('optgroup', $output, $attributes);
1316 * This is a shortcut for making an hour selector menu.
1318 * @param string $type The type of selector (years, months, days, hours, minutes)
1319 * @param string $name fieldname
1320 * @param int $currenttime A default timestamp in GMT
1321 * @param int $step minute spacing
1322 * @param array $attributes - html select element attributes
1323 * @return HTML fragment
1325 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1326 if (!$currenttime) {
1327 $currenttime = time();
1329 $currentdate = usergetdate($currenttime);
1330 $userdatetype = $type;
1331 $timeunits = array();
1335 for ($i=1970; $i<=2020; $i++
) {
1336 $timeunits[$i] = $i;
1338 $userdatetype = 'year';
1341 for ($i=1; $i<=12; $i++
) {
1342 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1344 $userdatetype = 'month';
1345 $currentdate['month'] = (int)$currentdate['mon'];
1348 for ($i=1; $i<=31; $i++
) {
1349 $timeunits[$i] = $i;
1351 $userdatetype = 'mday';
1354 for ($i=0; $i<=23; $i++
) {
1355 $timeunits[$i] = sprintf("%02d",$i);
1360 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1363 for ($i=0; $i<=59; $i+
=$step) {
1364 $timeunits[$i] = sprintf("%02d",$i);
1368 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1371 if (empty($attributes['id'])) {
1372 $attributes['id'] = self
::random_id('ts_');
1374 $timerselector = self
::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1375 $label = self
::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1377 return $label.$timerselector;
1381 * Shortcut for quick making of lists
1383 * Note: 'list' is a reserved keyword ;-)
1385 * @param array $items
1386 * @param array $attributes
1387 * @param string $tag ul or ol
1390 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1393 foreach ($items as $item) {
1394 $output .= html_writer
::start_tag('li') . "\n";
1395 $output .= $item . "\n";
1396 $output .= html_writer
::end_tag('li') . "\n";
1399 return html_writer
::tag($tag, $output, $attributes);
1403 * Returns hidden input fields created from url parameters.
1405 * @param moodle_url $url
1406 * @param array $exclude list of excluded parameters
1407 * @return string HTML fragment
1409 public static function input_hidden_params(moodle_url
$url, array $exclude = null) {
1410 $exclude = (array)$exclude;
1411 $params = $url->params();
1412 foreach ($exclude as $key) {
1413 unset($params[$key]);
1417 foreach ($params as $key => $value) {
1418 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1419 $output .= self
::empty_tag('input', $attributes)."\n";
1425 * Generate a script tag containing the the specified code.
1427 * @param string $jscode the JavaScript code
1428 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
1429 * @return string HTML, the code wrapped in <script> tags.
1431 public static function script($jscode, $url=null) {
1433 $attributes = array('type'=>'text/javascript');
1434 return self
::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1437 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1438 return self
::tag('script', '', $attributes) . "\n";
1446 * Renders HTML table
1448 * This method may modify the passed instance by adding some default properties if they are not set yet.
1449 * If this is not what you want, you should make a full clone of your data before passing them to this
1450 * method. In most cases this is not an issue at all so we do not clone by default for performance
1451 * and memory consumption reasons.
1453 * @param html_table $table data to be rendered
1454 * @return string HTML code
1456 public static function table(html_table
$table) {
1457 // prepare table data and populate missing properties with reasonable defaults
1458 if (!empty($table->align
)) {
1459 foreach ($table->align
as $key => $aa) {
1461 $table->align
[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1463 $table->align
[$key] = null;
1467 if (!empty($table->size
)) {
1468 foreach ($table->size
as $key => $ss) {
1470 $table->size
[$key] = 'width:'. $ss .';';
1472 $table->size
[$key] = null;
1476 if (!empty($table->wrap
)) {
1477 foreach ($table->wrap
as $key => $ww) {
1479 $table->wrap
[$key] = 'white-space:nowrap;';
1481 $table->wrap
[$key] = '';
1485 if (!empty($table->head
)) {
1486 foreach ($table->head
as $key => $val) {
1487 if (!isset($table->align
[$key])) {
1488 $table->align
[$key] = null;
1490 if (!isset($table->size
[$key])) {
1491 $table->size
[$key] = null;
1493 if (!isset($table->wrap
[$key])) {
1494 $table->wrap
[$key] = null;
1499 if (empty($table->attributes
['class'])) {
1500 $table->attributes
['class'] = 'generaltable';
1502 if (!empty($table->tablealign
)) {
1503 $table->attributes
['class'] .= ' boxalign' . $table->tablealign
;
1506 // explicitly assigned properties override those defined via $table->attributes
1507 $table->attributes
['class'] = trim($table->attributes
['class']);
1508 $attributes = array_merge($table->attributes
, array(
1510 'width' => $table->width
,
1511 'summary' => $table->summary
,
1512 'cellpadding' => $table->cellpadding
,
1513 'cellspacing' => $table->cellspacing
,
1515 $output = html_writer
::start_tag('table', $attributes) . "\n";
1519 if (!empty($table->head
)) {
1520 $countcols = count($table->head
);
1522 $output .= html_writer
::start_tag('thead', array()) . "\n";
1523 $output .= html_writer
::start_tag('tr', array()) . "\n";
1524 $keys = array_keys($table->head
);
1525 $lastkey = end($keys);
1527 foreach ($table->head
as $key => $heading) {
1528 // Convert plain string headings into html_table_cell objects
1529 if (!($heading instanceof html_table_cell
)) {
1530 $headingtext = $heading;
1531 $heading = new html_table_cell();
1532 $heading->text
= $headingtext;
1533 $heading->header
= true;
1536 if ($heading->header
!== false) {
1537 $heading->header
= true;
1540 if ($heading->header
&& empty($heading->scope
)) {
1541 $heading->scope
= 'col';
1544 $heading->attributes
['class'] .= ' header c' . $key;
1545 if (isset($table->headspan
[$key]) && $table->headspan
[$key] > 1) {
1546 $heading->colspan
= $table->headspan
[$key];
1547 $countcols +
= $table->headspan
[$key] - 1;
1550 if ($key == $lastkey) {
1551 $heading->attributes
['class'] .= ' lastcol';
1553 if (isset($table->colclasses
[$key])) {
1554 $heading->attributes
['class'] .= ' ' . $table->colclasses
[$key];
1556 $heading->attributes
['class'] = trim($heading->attributes
['class']);
1557 $attributes = array_merge($heading->attributes
, array(
1558 'style' => $table->align
[$key] . $table->size
[$key] . $heading->style
,
1559 'scope' => $heading->scope
,
1560 'colspan' => $heading->colspan
,
1564 if ($heading->header
=== true) {
1567 $output .= html_writer
::tag($tagtype, $heading->text
, $attributes) . "\n";
1569 $output .= html_writer
::end_tag('tr') . "\n";
1570 $output .= html_writer
::end_tag('thead') . "\n";
1572 if (empty($table->data
)) {
1573 // For valid XHTML strict every table must contain either a valid tr
1574 // or a valid tbody... both of which must contain a valid td
1575 $output .= html_writer
::start_tag('tbody', array('class' => 'empty'));
1576 $output .= html_writer
::tag('tr', html_writer
::tag('td', '', array('colspan'=>count($table->head
))));
1577 $output .= html_writer
::end_tag('tbody');
1581 if (!empty($table->data
)) {
1583 $keys = array_keys($table->data
);
1584 $lastrowkey = end($keys);
1585 $output .= html_writer
::start_tag('tbody', array());
1587 foreach ($table->data
as $key => $row) {
1588 if (($row === 'hr') && ($countcols)) {
1589 $output .= html_writer
::tag('td', html_writer
::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1591 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1592 if (!($row instanceof html_table_row
)) {
1593 $newrow = new html_table_row();
1595 foreach ($row as $cell) {
1596 if (!($cell instanceof html_table_cell
)) {
1597 $cell = new html_table_cell($cell);
1599 $newrow->cells
[] = $cell;
1604 $oddeven = $oddeven ?
0 : 1;
1605 if (isset($table->rowclasses
[$key])) {
1606 $row->attributes
['class'] .= ' ' . $table->rowclasses
[$key];
1609 $row->attributes
['class'] .= ' r' . $oddeven;
1610 if ($key == $lastrowkey) {
1611 $row->attributes
['class'] .= ' lastrow';
1614 $output .= html_writer
::start_tag('tr', array('class' => trim($row->attributes
['class']), 'style' => $row->style
, 'id' => $row->id
)) . "\n";
1615 $keys2 = array_keys($row->cells
);
1616 $lastkey = end($keys2);
1618 $gotlastkey = false; //flag for sanity checking
1619 foreach ($row->cells
as $key => $cell) {
1621 //This should never happen. Why do we have a cell after the last cell?
1622 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1625 if (!($cell instanceof html_table_cell
)) {
1626 $mycell = new html_table_cell();
1627 $mycell->text
= $cell;
1631 if (($cell->header
=== true) && empty($cell->scope
)) {
1632 $cell->scope
= 'row';
1635 if (isset($table->colclasses
[$key])) {
1636 $cell->attributes
['class'] .= ' ' . $table->colclasses
[$key];
1639 $cell->attributes
['class'] .= ' cell c' . $key;
1640 if ($key == $lastkey) {
1641 $cell->attributes
['class'] .= ' lastcol';
1645 $tdstyle .= isset($table->align
[$key]) ?
$table->align
[$key] : '';
1646 $tdstyle .= isset($table->size
[$key]) ?
$table->size
[$key] : '';
1647 $tdstyle .= isset($table->wrap
[$key]) ?
$table->wrap
[$key] : '';
1648 $cell->attributes
['class'] = trim($cell->attributes
['class']);
1649 $tdattributes = array_merge($cell->attributes
, array(
1650 'style' => $tdstyle . $cell->style
,
1651 'colspan' => $cell->colspan
,
1652 'rowspan' => $cell->rowspan
,
1654 'abbr' => $cell->abbr
,
1655 'scope' => $cell->scope
,
1658 if ($cell->header
=== true) {
1661 $output .= html_writer
::tag($tagtype, $cell->text
, $tdattributes) . "\n";
1664 $output .= html_writer
::end_tag('tr') . "\n";
1666 $output .= html_writer
::end_tag('tbody') . "\n";
1668 $output .= html_writer
::end_tag('table') . "\n";
1674 * Renders form element label
1676 * By default, the label is suffixed with a label separator defined in the
1677 * current language pack (colon by default in the English lang pack).
1678 * Adding the colon can be explicitly disabled if needed. Label separators
1679 * are put outside the label tag itself so they are not read by
1680 * screenreaders (accessibility).
1682 * Parameter $for explicitly associates the label with a form control. When
1683 * set, the value of this attribute must be the same as the value of
1684 * the id attribute of the form control in the same document. When null,
1685 * the label being defined is associated with the control inside the label
1688 * @param string $text content of the label tag
1689 * @param string|null $for id of the element this label is associated with, null for no association
1690 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1691 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1692 * @return string HTML of the label element
1694 public static function label($text, $for, $colonize = true, array $attributes=array()) {
1695 if (!is_null($for)) {
1696 $attributes = array_merge($attributes, array('for' => $for));
1698 $text = trim($text);
1699 $label = self
::tag('label', $text, $attributes);
1701 // TODO MDL-12192 $colonize disabled for now yet
1702 // if (!empty($text) and $colonize) {
1703 // // the $text may end with the colon already, though it is bad string definition style
1704 // $colon = get_string('labelsep', 'langconfig');
1705 // if (!empty($colon)) {
1706 // $trimmed = trim($colon);
1707 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1708 // //debugging('The label text should not end with colon or other label separator,
1709 // // please fix the string definition.', DEBUG_DEVELOPER);
1711 // $label .= $colon;
1721 * Simple javascript output class
1723 * @copyright 2010 Petr Skoda
1724 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1732 * Returns javascript code calling the function
1734 * @param string $function function name, can be complex like Y.Event.purgeElement
1735 * @param array $arguments parameters
1736 * @param int $delay execution delay in seconds
1737 * @return string JS code fragment
1739 public static function function_call($function, array $arguments = null, $delay=0) {
1741 $arguments = array_map('json_encode', convert_to_array($arguments));
1742 $arguments = implode(', ', $arguments);
1746 $js = "$function($arguments);";
1749 $delay = $delay * 1000; // in miliseconds
1750 $js = "setTimeout(function() { $js }, $delay);";
1756 * Special function which adds Y as first argument of function call.
1758 * @param string $function The function to call
1759 * @param array $extraarguments Any arguments to pass to it
1760 * @return string Some JS code
1762 public static function function_call_with_Y($function, array $extraarguments = null) {
1763 if ($extraarguments) {
1764 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1765 $arguments = 'Y, ' . implode(', ', $extraarguments);
1769 return "$function($arguments);\n";
1773 * Returns JavaScript code to initialise a new object
1775 * @param string $var If it is null then no var is assigned the new object.
1776 * @param string $class The class to initialise an object for.
1777 * @param array $arguments An array of args to pass to the init method.
1778 * @param array $requirements Any modules required for this class.
1779 * @param int $delay The delay before initialisation. 0 = no delay.
1780 * @return string Some JS code
1782 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1783 if (is_array($arguments)) {
1784 $arguments = array_map('json_encode', convert_to_array($arguments));
1785 $arguments = implode(', ', $arguments);
1788 if ($var === null) {
1789 $js = "new $class(Y, $arguments);";
1790 } else if (strpos($var, '.')!==false) {
1791 $js = "$var = new $class(Y, $arguments);";
1793 $js = "var $var = new $class(Y, $arguments);";
1797 $delay = $delay * 1000; // in miliseconds
1798 $js = "setTimeout(function() { $js }, $delay);";
1801 if (count($requirements) > 0) {
1802 $requirements = implode("', '", $requirements);
1803 $js = "Y.use('$requirements', function(Y){ $js });";
1809 * Returns code setting value to variable
1811 * @param string $name
1812 * @param mixed $value json serialised value
1813 * @param bool $usevar add var definition, ignored for nested properties
1814 * @return string JS code fragment
1816 public static function set_variable($name, $value, $usevar = true) {
1820 if (strpos($name, '.')) {
1827 $output .= "$name = ".json_encode($value).";";
1833 * Writes event handler attaching code
1835 * @param array|string $selector standard YUI selector for elements, may be
1836 * array or string, element id is in the form "#idvalue"
1837 * @param string $event A valid DOM event (click, mousedown, change etc.)
1838 * @param string $function The name of the function to call
1839 * @param array $arguments An optional array of argument parameters to pass to the function
1840 * @return string JS code fragment
1842 public static function event_handler($selector, $event, $function, array $arguments = null) {
1843 $selector = json_encode($selector);
1844 $output = "Y.on('$event', $function, $selector, null";
1845 if (!empty($arguments)) {
1846 $output .= ', ' . json_encode($arguments);
1848 return $output . ");\n";
1853 * Holds all the information required to render a <table> by {@link core_renderer::table()}
1856 * $t = new html_table();
1857 * ... // set various properties of the object $t as described below
1858 * echo html_writer::table($t);
1860 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1861 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1869 * @var string Value to use for the id attribute of the table
1874 * @var array Attributes of HTML attributes for the <table> element
1876 public $attributes = array();
1879 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
1880 * For more control over the rendering of the headers, an array of html_table_cell objects
1881 * can be passed instead of an array of strings.
1884 * $t->head = array('Student', 'Grade');
1889 * @var array An array that can be used to make a heading span multiple columns.
1890 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1891 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
1894 * $t->headspan = array(2,1);
1899 * @var array An array of column alignments.
1900 * The value is used as CSS 'text-align' property. Therefore, possible
1901 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1902 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1904 * Examples of usage:
1905 * $t->align = array(null, 'right');
1907 * $t->align[1] = 'right';
1912 * @var array The value is used as CSS 'size' property.
1914 * Examples of usage:
1915 * $t->size = array('50%', '50%');
1917 * $t->size[1] = '120px';
1922 * @var array An array of wrapping information.
1923 * The only possible value is 'nowrap' that sets the
1924 * CSS property 'white-space' to the value 'nowrap' in the given column.
1927 * $t->wrap = array(null, 'nowrap');
1932 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
1933 * $head specified, the string 'hr' (for horizontal ruler) can be used
1934 * instead of an array of cells data resulting in a divider rendered.
1936 * Example of usage with array of arrays:
1937 * $row1 = array('Harry Potter', '76 %');
1938 * $row2 = array('Hermione Granger', '100 %');
1939 * $t->data = array($row1, $row2);
1941 * Example with array of html_table_row objects: (used for more fine-grained control)
1942 * $cell1 = new html_table_cell();
1943 * $cell1->text = 'Harry Potter';
1944 * $cell1->colspan = 2;
1945 * $row1 = new html_table_row();
1946 * $row1->cells[] = $cell1;
1947 * $cell2 = new html_table_cell();
1948 * $cell2->text = 'Hermione Granger';
1949 * $cell3 = new html_table_cell();
1950 * $cell3->text = '100 %';
1951 * $row2 = new html_table_row();
1952 * $row2->cells = array($cell2, $cell3);
1953 * $t->data = array($row1, $row2);
1958 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1959 * @var string Width of the table, percentage of the page preferred.
1961 public $width = null;
1964 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1965 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
1967 public $tablealign = null;
1970 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1971 * @var int Padding on each cell, in pixels
1973 public $cellpadding = null;
1976 * @var int Spacing between cells, in pixels
1977 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1979 public $cellspacing = null;
1982 * @var array Array of classes to add to particular rows, space-separated string.
1983 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1984 * respectively. Class 'lastrow' is added automatically for the last row
1988 * $t->rowclasses[9] = 'tenth'
1993 * @var array An array of classes to add to every cell in a particular column,
1994 * space-separated string. Class 'cell' is added automatically by the renderer.
1995 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1996 * respectively. Class 'lastcol' is added automatically for all last cells
2000 * $t->colclasses = array(null, 'grade');
2005 * @var string Description of the contents for screen readers.
2012 public function __construct() {
2013 $this->attributes
['class'] = '';
2018 * Component representing a table row.
2020 * @copyright 2009 Nicolas Connault
2021 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2026 class html_table_row
{
2029 * @var string Value to use for the id attribute of the row.
2034 * @var array Array of html_table_cell objects
2036 public $cells = array();
2039 * @var string Value to use for the style attribute of the table row
2041 public $style = null;
2044 * @var array Attributes of additional HTML attributes for the <tr> element
2046 public $attributes = array();
2050 * @param array $cells
2052 public function __construct(array $cells=null) {
2053 $this->attributes
['class'] = '';
2054 $cells = (array)$cells;
2055 foreach ($cells as $cell) {
2056 if ($cell instanceof html_table_cell
) {
2057 $this->cells
[] = $cell;
2059 $this->cells
[] = new html_table_cell($cell);
2066 * Component representing a table cell.
2068 * @copyright 2009 Nicolas Connault
2069 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2074 class html_table_cell
{
2077 * @var string Value to use for the id attribute of the cell.
2082 * @var string The contents of the cell.
2087 * @var string Abbreviated version of the contents of the cell.
2089 public $abbr = null;
2092 * @var int Number of columns this cell should span.
2094 public $colspan = null;
2097 * @var int Number of rows this cell should span.
2099 public $rowspan = null;
2102 * @var string Defines a way to associate header cells and data cells in a table.
2104 public $scope = null;
2107 * @var bool Whether or not this cell is a header cell.
2109 public $header = null;
2112 * @var string Value to use for the style attribute of the table cell
2114 public $style = null;
2117 * @var array Attributes of additional HTML attributes for the <td> element
2119 public $attributes = array();
2122 * Constructs a table cell
2124 * @param string $text
2126 public function __construct($text = null) {
2127 $this->text
= $text;
2128 $this->attributes
['class'] = '';
2133 * Component representing a paging bar.
2135 * @copyright 2009 Nicolas Connault
2136 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2141 class paging_bar
implements renderable
{
2144 * @var int The maximum number of pagelinks to display.
2146 public $maxdisplay = 18;
2149 * @var int The total number of entries to be pages through..
2154 * @var int The page you are currently viewing.
2159 * @var int The number of entries that should be shown per page.
2164 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2165 * an equals sign and the page number.
2166 * If this is a moodle_url object then the pagevar param will be replaced by
2167 * the page no, for each page.
2172 * @var string This is the variable name that you use for the pagenumber in your
2173 * code (ie. 'tablepage', 'blogpage', etc)
2178 * @var string A HTML link representing the "previous" page.
2180 public $previouslink = null;
2183 * @var string A HTML link representing the "next" page.
2185 public $nextlink = null;
2188 * @var string A HTML link representing the first page.
2190 public $firstlink = null;
2193 * @var string A HTML link representing the last page.
2195 public $lastlink = null;
2198 * @var array An array of strings. One of them is just a string: the current page
2200 public $pagelinks = array();
2203 * Constructor paging_bar with only the required params.
2205 * @param int $totalcount The total number of entries available to be paged through
2206 * @param int $page The page you are currently viewing
2207 * @param int $perpage The number of entries that should be shown per page
2208 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2209 * @param string $pagevar name of page parameter that holds the page number
2211 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2212 $this->totalcount
= $totalcount;
2213 $this->page
= $page;
2214 $this->perpage
= $perpage;
2215 $this->baseurl
= $baseurl;
2216 $this->pagevar
= $pagevar;
2220 * Prepares the paging bar for output.
2222 * This method validates the arguments set up for the paging bar and then
2223 * produces fragments of HTML to assist display later on.
2225 * @param renderer_base $output
2226 * @param moodle_page $page
2227 * @param string $target
2228 * @throws coding_exception
2230 public function prepare(renderer_base
$output, moodle_page
$page, $target) {
2231 if (!isset($this->totalcount
) ||
is_null($this->totalcount
)) {
2232 throw new coding_exception('paging_bar requires a totalcount value.');
2234 if (!isset($this->page
) ||
is_null($this->page
)) {
2235 throw new coding_exception('paging_bar requires a page value.');
2237 if (empty($this->perpage
)) {
2238 throw new coding_exception('paging_bar requires a perpage value.');
2240 if (empty($this->baseurl
)) {
2241 throw new coding_exception('paging_bar requires a baseurl value.');
2244 if ($this->totalcount
> $this->perpage
) {
2245 $pagenum = $this->page
- 1;
2247 if ($this->page
> 0) {
2248 $this->previouslink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2251 if ($this->perpage
> 0) {
2252 $lastpage = ceil($this->totalcount
/ $this->perpage
);
2257 if ($this->page
> 15) {
2258 $startpage = $this->page
- 10;
2260 $this->firstlink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>0)), '1', array('class'=>'first'));
2265 $currpage = $startpage;
2266 $displaycount = $displaypage = 0;
2268 while ($displaycount < $this->maxdisplay
and $currpage < $lastpage) {
2269 $displaypage = $currpage +
1;
2271 if ($this->page
== $currpage) {
2272 $this->pagelinks
[] = $displaypage;
2274 $pagelink = html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$currpage)), $displaypage);
2275 $this->pagelinks
[] = $pagelink;
2282 if ($currpage < $lastpage) {
2283 $lastpageactual = $lastpage - 1;
2284 $this->lastlink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$lastpageactual)), $lastpage, array('class'=>'last'));
2287 $pagenum = $this->page +
1;
2289 if ($pagenum != $displaypage) {
2290 $this->nextlink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$pagenum)), get_string('next'), array('class'=>'next'));
2297 * This class represents how a block appears on a page.
2299 * During output, each block instance is asked to return a block_contents object,
2300 * those are then passed to the $OUTPUT->block function for display.
2302 * contents should probably be generated using a moodle_block_..._renderer.
2304 * Other block-like things that need to appear on the page, for example the
2305 * add new block UI, are also represented as block_contents objects.
2307 * @copyright 2009 Tim Hunt
2308 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2313 class block_contents
{
2315 /** Used when the block cannot be collapsed **/
2316 const NOT_HIDEABLE
= 0;
2318 /** Used when the block can be collapsed but currently is not **/
2321 /** Used when the block has been collapsed **/
2325 * @var int Used to set $skipid.
2327 protected static $idcounter = 1;
2330 * @var int All the blocks (or things that look like blocks) printed on
2331 * a page are given a unique number that can be used to construct id="" attributes.
2332 * This is set automatically be the {@link prepare()} method.
2333 * Do not try to set it manually.
2338 * @var int If this is the contents of a real block, this should be set
2339 * to the block_instance.id. Otherwise this should be set to 0.
2341 public $blockinstanceid = 0;
2344 * @var int If this is a real block instance, and there is a corresponding
2345 * block_position.id for the block on this page, this should be set to that id.
2346 * Otherwise it should be 0.
2348 public $blockpositionid = 0;
2351 * @var array An array of attribute => value pairs that are put on the outer div of this
2352 * block. {@link $id} and {@link $classes} attributes should be set separately.
2357 * @var string The title of this block. If this came from user input, it should already
2358 * have had format_string() processing done on it. This will be output inside
2359 * <h2> tags. Please do not cause invalid XHTML.
2364 * @var string HTML for the content
2366 public $content = '';
2369 * @var array An alternative to $content, it you want a list of things with optional icons.
2371 public $footer = '';
2374 * @var string Any small print that should appear under the block to explain
2375 * to the teacher about the block, for example 'This is a sticky block that was
2376 * added in the system context.'
2378 public $annotation = '';
2381 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2382 * the user can toggle whether this block is visible.
2384 public $collapsible = self
::NOT_HIDEABLE
;
2387 * @var array A (possibly empty) array of editing controls. Each element of
2388 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2389 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2391 public $controls = array();
2395 * Create new instance of block content
2396 * @param array $attributes
2398 public function __construct(array $attributes = null) {
2399 $this->skipid
= self
::$idcounter;
2400 self
::$idcounter +
= 1;
2404 $this->attributes
= $attributes;
2406 // simple "fake" blocks used in some modules and "Add new block" block
2407 $this->attributes
= array('class'=>'block');
2412 * Add html class to block
2414 * @param string $class
2416 public function add_class($class) {
2417 $this->attributes
['class'] .= ' '.$class;
2423 * This class represents a target for where a block can go when it is being moved.
2425 * This needs to be rendered as a form with the given hidden from fields, and
2426 * clicking anywhere in the form should submit it. The form action should be
2429 * @copyright 2009 Tim Hunt
2430 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2435 class block_move_target
{
2438 * @var moodle_url Move url
2449 * @param string $text
2450 * @param moodle_url $url
2452 public function __construct($text, moodle_url
$url) {
2453 $this->text
= $text;
2461 * This class is used to represent one item within a custom menu that may or may
2462 * not have children.
2464 * @copyright 2010 Sam Hemelryk
2465 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2470 class custom_menu_item
implements renderable
{
2473 * @var string The text to show for the item
2478 * @var moodle_url The link to give the icon if it has no children
2483 * @var string A title to apply to the item. By default the text
2488 * @var int A sort order for the item, not necessary if you order things in
2494 * @var custom_menu_item A reference to the parent for this item or NULL if
2495 * it is a top level item
2500 * @var array A array in which to store children this item has.
2502 protected $children = array();
2505 * @var int A reference to the sort var of the last child that was added
2507 protected $lastsort = 0;
2510 * Constructs the new custom menu item
2512 * @param string $text
2513 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2514 * @param string $title A title to apply to this item [Optional]
2515 * @param int $sort A sort or to use if we need to sort differently [Optional]
2516 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2517 * belongs to, only if the child has a parent. [Optional]
2519 public function __construct($text, moodle_url
$url=null, $title=null, $sort = null, custom_menu_item
$parent = null) {
2520 $this->text
= $text;
2522 $this->title
= $title;
2523 $this->sort
= (int)$sort;
2524 $this->parent
= $parent;
2528 * Adds a custom menu item as a child of this node given its properties.
2530 * @param string $text
2531 * @param moodle_url $url
2532 * @param string $title
2534 * @return custom_menu_item
2536 public function add($text, moodle_url
$url = null, $title = null, $sort = null) {
2537 $key = count($this->children
);
2539 $sort = $this->lastsort +
1;
2541 $this->children
[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2542 $this->lastsort
= (int)$sort;
2543 return $this->children
[$key];
2547 * Returns the text for this item
2550 public function get_text() {
2555 * Returns the url for this item
2556 * @return moodle_url
2558 public function get_url() {
2563 * Returns the title for this item
2566 public function get_title() {
2567 return $this->title
;
2571 * Sorts and returns the children for this item
2574 public function get_children() {
2576 return $this->children
;
2580 * Gets the sort order for this child
2583 public function get_sort_order() {
2588 * Gets the parent this child belong to
2589 * @return custom_menu_item
2591 public function get_parent() {
2592 return $this->parent
;
2596 * Sorts the children this item has
2598 public function sort() {
2599 usort($this->children
, array('custom_menu','sort_custom_menu_items'));
2603 * Returns true if this item has any children
2606 public function has_children() {
2607 return (count($this->children
) > 0);
2611 * Sets the text for the node
2612 * @param string $text
2614 public function set_text($text) {
2615 $this->text
= (string)$text;
2619 * Sets the title for the node
2620 * @param string $title
2622 public function set_title($title) {
2623 $this->title
= (string)$title;
2627 * Sets the url for the node
2628 * @param moodle_url $url
2630 public function set_url(moodle_url
$url) {
2638 * This class is used to operate a custom menu that can be rendered for the page.
2639 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2640 * of custom_menu_item nodes that can be rendered by the core renderer.
2642 * To configure the custom menu:
2643 * Settings: Administration > Appearance > Themes > Theme settings
2645 * @copyright 2010 Sam Hemelryk
2646 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2651 class custom_menu
extends custom_menu_item
{
2654 * @var string The language we should render for, null disables multilang support.
2656 protected $currentlanguage = null;
2659 * Creates the custom menu
2661 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2662 * @param string $currentlanguage the current language code, null disables multilang support
2664 public function __construct($definition = '', $currentlanguage = null) {
2665 $this->currentlanguage
= $currentlanguage;
2666 parent
::__construct('root'); // create virtual root element of the menu
2667 if (!empty($definition)) {
2668 $this->override_children(self
::convert_text_to_menu_nodes($definition, $currentlanguage));
2673 * Overrides the children of this custom menu. Useful when getting children
2674 * from $CFG->custommenuitems
2676 * @param array $children
2678 public function override_children(array $children) {
2679 $this->children
= array();
2680 foreach ($children as $child) {
2681 if ($child instanceof custom_menu_item
) {
2682 $this->children
[] = $child;
2688 * Converts a string into a structured array of custom_menu_items which can
2689 * then be added to a custom menu.
2692 * text|url|title|langs
2693 * The number of hyphens at the start determines the depth of the item. The
2694 * languages are optional, comma separated list of languages the line is for.
2696 * Example structure:
2697 * First level first item|http://www.moodle.com/
2698 * -Second level first item|http://www.moodle.com/partners/
2699 * -Second level second item|http://www.moodle.com/hq/
2700 * --Third level first item|http://www.moodle.com/jobs/
2701 * -Second level third item|http://www.moodle.com/development/
2702 * First level second item|http://www.moodle.com/feedback/
2703 * First level third item
2704 * English only|http://moodle.com|English only item|en
2705 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2709 * @param string $text the menu items definition
2710 * @param string $language the language code, null disables multilang support
2713 public static function convert_text_to_menu_nodes($text, $language = null) {
2714 $lines = explode("\n", $text);
2715 $children = array();
2719 foreach ($lines as $line) {
2720 $line = trim($line);
2721 $bits = explode('|', $line, 4); // name|url|title|langs
2722 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2723 // Every item must have a name to be valid
2726 $bits[0] = ltrim($bits[0],'-');
2728 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2729 // Set the url to null
2732 // Make sure the url is a moodle url
2733 $bits[1] = new moodle_url(trim($bits[1]));
2735 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2736 // Set the title to null seeing as there isn't one
2737 $bits[2] = $bits[0];
2739 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2740 // The item is valid for all languages
2743 $itemlangs = array_map('trim', explode(',', $bits[3]));
2745 if (!empty($language) and !empty($itemlangs)) {
2746 // check that the item is intended for the current language
2747 if (!in_array($language, $itemlangs)) {
2751 // Set an incremental sort order to keep it simple.
2753 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2754 $depth = strlen($match[1]);
2755 if ($depth < $lastdepth) {
2756 $difference = $lastdepth - $depth;
2757 if ($lastdepth > 1 && $lastdepth != $difference) {
2758 $tempchild = $lastchild->get_parent();
2759 for ($i =0; $i < $difference; $i++
) {
2760 $tempchild = $tempchild->get_parent();
2762 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2765 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2766 $children[] = $lastchild;
2768 } else if ($depth > $lastdepth) {
2769 $depth = $lastdepth +
1;
2770 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2773 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2774 $children[] = $lastchild;
2776 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2781 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2782 $children[] = $lastchild;
2784 $lastdepth = $depth;
2790 * Sorts two custom menu items
2792 * This function is designed to be used with the usort method
2793 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2796 * @param custom_menu_item $itema
2797 * @param custom_menu_item $itemb
2800 public static function sort_custom_menu_items(custom_menu_item
$itema, custom_menu_item
$itemb) {
2801 $itema = $itema->get_sort_order();
2802 $itemb = $itemb->get_sort_order();
2803 if ($itema == $itemb) {
2806 return ($itema > $itemb) ? +
1 : -1;