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 = get_context_instance(CONTEXT_USER
, $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
>= 50) {
326 $size = (int)$this->size
;
329 $size = (int)$this->size
;
332 $defaulturl = $renderer->pix_url('u/'.$filename); // default image
334 if ((!empty($CFG->forcelogin
) and !isloggedin()) ||
335 (!empty($CFG->forceloginforprofileimage
) && (!isloggedin() ||
isguestuser()))) {
336 // Protect images if login required and not logged in;
337 // also if login is required for profile images and is not logged in or guest
338 // do not use require_login() because it is expensive and not suitable here anyway.
342 // First try to detect deleted users - but do not read from database for performance reasons!
343 if (!empty($this->user
->deleted
) or strpos($this->user
->email
, '@') === false) {
344 // All deleted users should have email replaced by md5 hash,
345 // all active users are expected to have valid email.
349 // Did the user upload a picture?
350 if ($this->user
->picture
> 0) {
351 if (!empty($this->user
->contextid
)) {
352 $contextid = $this->user
->contextid
;
354 $context = context_user
::instance($this->user
->id
, IGNORE_MISSING
);
356 // This must be an incorrectly deleted user, all other users have context.
359 $contextid = $context->id
;
363 if (clean_param($page->theme
->name
, PARAM_THEME
) == $page->theme
->name
) {
364 // We append the theme name to the file path if we have it so that
365 // in the circumstance that the profile picture is not available
366 // when the user actually requests it they still get the profile
367 // picture for the correct theme.
368 $path .= $page->theme
->name
.'/';
370 // Set the image URL to the URL for the uploaded file and return.
371 $url = moodle_url
::make_pluginfile_url($contextid, 'user', 'icon', NULL, $path, $filename);
372 $url->param('rev', $this->user
->picture
);
376 if ($this->user
->picture
== 0 and !empty($CFG->enablegravatar
)) {
377 // Normalise the size variable to acceptable bounds
378 if ($size < 1 ||
$size > 512) {
381 // Hash the users email address
382 $md5 = md5(strtolower(trim($this->user
->email
)));
383 // Build a gravatar URL with what we know.
384 // If the currently requested page is https then we'll return an
385 // https gravatar page.
386 if (strpos($CFG->httpswwwroot
, 'https:') === 0) {
387 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $defaulturl->out(false)));
389 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $defaulturl->out(false)));
398 * Data structure representing a help icon.
400 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
401 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
406 class old_help_icon
implements renderable
{
409 * @var string Lang pack identifier
411 public $helpidentifier;
414 * @var string A descriptive text for title tooltip
416 public $title = null;
419 * @var string Component name, the same as in get_string()
421 public $component = 'moodle';
424 * @var string Extra descriptive text next to the icon
426 public $linktext = null;
429 * Constructor: sets up the other components in case they are needed
431 * @param string $helpidentifier The keyword that defines a help page
432 * @param string $title A descriptive text for accessibility only
433 * @param string $component
435 public function __construct($helpidentifier, $title, $component = 'moodle') {
437 throw new coding_exception('A help_icon object requires a $text parameter');
439 if (empty($helpidentifier)) {
440 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
443 $this->helpidentifier
= $helpidentifier;
444 $this->title
= $title;
445 $this->component
= $component;
450 * Data structure representing a help icon.
452 * @copyright 2010 Petr Skoda (info@skodak.org)
453 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
458 class help_icon
implements renderable
{
461 * @var string lang pack identifier (without the "_help" suffix),
462 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
468 * @var string Component name, the same as in get_string()
473 * @var string Extra descriptive text next to the icon
475 public $linktext = null;
480 * @param string $identifier string for help page title,
481 * string with _help suffix is used for the actual help text.
482 * string with _link suffix is used to create a link to further info (if it exists)
483 * @param string $component
485 public function __construct($identifier, $component) {
486 $this->identifier
= $identifier;
487 $this->component
= $component;
491 * Verifies that both help strings exists, shows debug warnings if not
493 public function diag_strings() {
494 $sm = get_string_manager();
495 if (!$sm->string_exists($this->identifier
, $this->component
)) {
496 debugging("Help title string does not exist: [$this->identifier, $this->component]");
498 if (!$sm->string_exists($this->identifier
.'_help', $this->component
)) {
499 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
506 * Data structure representing an icon.
508 * @copyright 2010 Petr Skoda
509 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
514 class pix_icon
implements renderable
{
517 * @var string The icon name
522 * @var string The component the icon belongs to.
527 * @var array An array of attributes to use on the icon
529 var $attributes = array();
534 * @param string $pix short icon name
535 * @param string $alt The alt text to use for the icon
536 * @param string $component component name
537 * @param array $attributes html attributes
539 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
541 $this->component
= $component;
542 $this->attributes
= (array)$attributes;
544 $this->attributes
['alt'] = $alt;
545 if (empty($this->attributes
['class'])) {
546 $this->attributes
['class'] = 'smallicon';
548 if (!isset($this->attributes
['title'])) {
549 $this->attributes
['title'] = $this->attributes
['alt'];
555 * Data structure representing an emoticon image
557 * @copyright 2010 David Mudrak
558 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
563 class pix_emoticon
extends pix_icon
implements renderable
{
567 * @param string $pix short icon name
568 * @param string $alt alternative text
569 * @param string $component emoticon image provider
570 * @param array $attributes explicit HTML attributes
572 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
573 if (empty($attributes['class'])) {
574 $attributes['class'] = 'emoticon';
576 parent
::__construct($pix, $alt, $component, $attributes);
581 * Data structure representing a simple form with only one button.
583 * @copyright 2009 Petr Skoda
584 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
589 class single_button
implements renderable
{
592 * @var moodle_url Target url
597 * @var string Button label
602 * @var string Form submit method post or get
604 var $method = 'post';
607 * @var string Wrapping div class
609 var $class = 'singlebutton';
612 * @var bool True if button disabled, false if normal
614 var $disabled = false;
617 * @var string Button tooltip
622 * @var string Form id
627 * @var array List of attached actions
629 var $actions = array();
633 * @param moodle_url $url
634 * @param string $label button text
635 * @param string $method get or post submit method
637 public function __construct(moodle_url
$url, $label, $method='post') {
638 $this->url
= clone($url);
639 $this->label
= $label;
640 $this->method
= $method;
644 * Shortcut for adding a JS confirm dialog when the button is clicked.
645 * The message must be a yes/no question.
647 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
649 public function add_confirm_action($confirmmessage) {
650 $this->add_action(new confirm_action($confirmmessage));
654 * Add action to the button.
655 * @param component_action $action
657 public function add_action(component_action
$action) {
658 $this->actions
[] = $action;
664 * Simple form with just one select field that gets submitted automatically.
666 * If JS not enabled small go button is printed too.
668 * @copyright 2009 Petr Skoda
669 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
674 class single_select
implements renderable
{
677 * @var moodle_url Target url - includes hidden fields
682 * @var string Name of the select element.
687 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
688 * it is also possible to specify optgroup as complex label array ex.:
689 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
690 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
695 * @var string Selected option
700 * @var array Nothing selected
705 * @var array Extra select field attributes
707 var $attributes = array();
710 * @var string Button label
715 * @var string Form submit method post or get
720 * @var string Wrapping div class
722 var $class = 'singleselect';
725 * @var bool True if button disabled, false if normal
727 var $disabled = false;
730 * @var string Button tooltip
735 * @var string Form id
740 * @var array List of attached actions
742 var $helpicon = null;
746 * @param moodle_url $url form action target, includes hidden fields
747 * @param string $name name of selection field - the changing parameter in url
748 * @param array $options list of options
749 * @param string $selected selected element
750 * @param array $nothing
751 * @param string $formid
753 public function __construct(moodle_url
$url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
756 $this->options
= $options;
757 $this->selected
= $selected;
758 $this->nothing
= $nothing;
759 $this->formid
= $formid;
763 * Shortcut for adding a JS confirm dialog when the button is clicked.
764 * The message must be a yes/no question.
766 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
768 public function add_confirm_action($confirmmessage) {
769 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
773 * Add action to the button.
775 * @param component_action $action
777 public function add_action(component_action
$action) {
778 $this->actions
[] = $action;
784 * @param string $helppage The keyword that defines a help page
785 * @param string $title A descriptive text for accessibility only
786 * @param string $component
788 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
789 $this->helpicon
= new old_help_icon($helppage, $title, $component);
795 * @param string $identifier The keyword that defines a help page
796 * @param string $component
798 public function set_help_icon($identifier, $component = 'moodle') {
799 $this->helpicon
= new help_icon($identifier, $component);
803 * Sets select's label
805 * @param string $label
807 public function set_label($label) {
808 $this->label
= $label;
813 * Simple URL selection widget description.
815 * @copyright 2009 Petr Skoda
816 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
821 class url_select
implements renderable
{
823 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
824 * it is also possible to specify optgroup as complex label array ex.:
825 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
826 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
831 * @var string Selected option
836 * @var array Nothing selected
841 * @var array Extra select field attributes
843 var $attributes = array();
846 * @var string Button label
851 * @var string Wrapping div class
853 var $class = 'urlselect';
856 * @var bool True if button disabled, false if normal
858 var $disabled = false;
861 * @var string Button tooltip
866 * @var string Form id
871 * @var array List of attached actions
873 var $helpicon = null;
876 * @var string If set, makes button visible with given name for button
878 var $showbutton = null;
882 * @param array $urls list of options
883 * @param string $selected selected element
884 * @param array $nothing
885 * @param string $formid
886 * @param string $showbutton Set to text of button if it should be visible
887 * or null if it should be hidden (hidden version always has text 'go')
889 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
891 $this->selected
= $selected;
892 $this->nothing
= $nothing;
893 $this->formid
= $formid;
894 $this->showbutton
= $showbutton;
900 * @param string $helppage The keyword that defines a help page
901 * @param string $title A descriptive text for accessibility only
902 * @param string $component
904 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
905 $this->helpicon
= new old_help_icon($helppage, $title, $component);
911 * @param string $identifier The keyword that defines a help page
912 * @param string $component
914 public function set_help_icon($identifier, $component = 'moodle') {
915 $this->helpicon
= new help_icon($identifier, $component);
919 * Sets select's label
921 * @param string $label
923 public function set_label($label) {
924 $this->label
= $label;
929 * Data structure describing html link with special action attached.
931 * @copyright 2010 Petr Skoda
932 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
937 class action_link
implements renderable
{
940 * @var moodle_url Href url
945 * @var string Link text HTML fragment
950 * @var array HTML attributes
955 * @var array List of actions attached to link
961 * @param moodle_url $url
962 * @param string $text HTML fragment
963 * @param component_action $action
964 * @param array $attributes associative array of html link attributes + disabled
966 public function __construct(moodle_url
$url, $text, component_action
$action = null, array $attributes = null) {
967 $this->url
= clone($url);
969 $this->attributes
= (array)$attributes;
971 $this->add_action($action);
976 * Add action to the link.
978 * @param component_action $action
980 public function add_action(component_action
$action) {
981 $this->actions
[] = $action;
985 * Adds a CSS class to this action link object
986 * @param string $class
988 public function add_class($class) {
989 if (empty($this->attributes
['class'])) {
990 $this->attributes
['class'] = $class;
992 $this->attributes
['class'] .= ' ' . $class;
998 * Simple html output class
1000 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1001 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1009 * Outputs a tag with attributes and contents
1011 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1012 * @param string $contents What goes between the opening and closing tags
1013 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1014 * @return string HTML fragment
1016 public static function tag($tagname, $contents, array $attributes = null) {
1017 return self
::start_tag($tagname, $attributes) . $contents . self
::end_tag($tagname);
1021 * Outputs an opening tag with attributes
1023 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1024 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1025 * @return string HTML fragment
1027 public static function start_tag($tagname, array $attributes = null) {
1028 return '<' . $tagname . self
::attributes($attributes) . '>';
1032 * Outputs a closing tag
1034 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1035 * @return string HTML fragment
1037 public static function end_tag($tagname) {
1038 return '</' . $tagname . '>';
1042 * Outputs an empty tag with attributes
1044 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1045 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1046 * @return string HTML fragment
1048 public static function empty_tag($tagname, array $attributes = null) {
1049 return '<' . $tagname . self
::attributes($attributes) . ' />';
1053 * Outputs a tag, but only if the contents are not empty
1055 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1056 * @param string $contents What goes between the opening and closing tags
1057 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1058 * @return string HTML fragment
1060 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1061 if ($contents === '' ||
is_null($contents)) {
1064 return self
::tag($tagname, $contents, $attributes);
1068 * Outputs a HTML attribute and value
1070 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1071 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1072 * @return string HTML fragment
1074 public static function attribute($name, $value) {
1075 if (is_array($value)) {
1076 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER
);
1078 if ($value instanceof moodle_url
) {
1079 return ' ' . $name . '="' . $value->out() . '"';
1082 // special case, we do not want these in output
1083 if ($value === null) {
1087 // no sloppy trimming here!
1088 return ' ' . $name . '="' . s($value) . '"';
1092 * Outputs a list of HTML attributes and values
1094 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1095 * The values will be escaped with {@link s()}
1096 * @return string HTML fragment
1098 public static function attributes(array $attributes = null) {
1099 $attributes = (array)$attributes;
1101 foreach ($attributes as $name => $value) {
1102 $output .= self
::attribute($name, $value);
1108 * Generates random html element id.
1110 * @staticvar int $counter
1111 * @staticvar type $uniq
1112 * @param string $base A string fragment that will be included in the random ID.
1113 * @return string A unique ID
1115 public static function random_id($base='random') {
1116 static $counter = 0;
1119 if (!isset($uniq)) {
1124 return $base.$uniq.$counter;
1128 * Generates a simple html link
1130 * @param string|moodle_url $url The URL
1131 * @param string $text The text
1132 * @param array $attributes HTML attributes
1133 * @return string HTML fragment
1135 public static function link($url, $text, array $attributes = null) {
1136 $attributes = (array)$attributes;
1137 $attributes['href'] = $url;
1138 return self
::tag('a', $text, $attributes);
1142 * Generates a simple checkbox with optional label
1144 * @param string $name The name of the checkbox
1145 * @param string $value The value of the checkbox
1146 * @param bool $checked Whether the checkbox is checked
1147 * @param string $label The label for the checkbox
1148 * @param array $attributes Any attributes to apply to the checkbox
1149 * @return string html fragment
1151 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1152 $attributes = (array)$attributes;
1155 if ($label !== '' and !is_null($label)) {
1156 if (empty($attributes['id'])) {
1157 $attributes['id'] = self
::random_id('checkbox_');
1160 $attributes['type'] = 'checkbox';
1161 $attributes['value'] = $value;
1162 $attributes['name'] = $name;
1163 $attributes['checked'] = $checked ?
'checked' : null;
1165 $output .= self
::empty_tag('input', $attributes);
1167 if ($label !== '' and !is_null($label)) {
1168 $output .= self
::tag('label', $label, array('for'=>$attributes['id']));
1175 * Generates a simple select yes/no form field
1177 * @param string $name name of select element
1178 * @param bool $selected
1179 * @param array $attributes - html select element attributes
1180 * @return string HTML fragment
1182 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1183 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1184 return self
::select($options, $name, $selected, null, $attributes);
1188 * Generates a simple select form field
1190 * @param array $options associative array value=>label ex.:
1191 * array(1=>'One, 2=>Two)
1192 * it is also possible to specify optgroup as complex label array ex.:
1193 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1194 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1195 * @param string $name name of select element
1196 * @param string|array $selected value or array of values depending on multiple attribute
1197 * @param array|bool $nothing add nothing selected option, or false of not added
1198 * @param array $attributes html select element attributes
1199 * @return string HTML fragment
1201 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1202 $attributes = (array)$attributes;
1203 if (is_array($nothing)) {
1204 foreach ($nothing as $k=>$v) {
1205 if ($v === 'choose' or $v === 'choosedots') {
1206 $nothing[$k] = get_string('choosedots');
1209 $options = $nothing +
$options; // keep keys, do not override
1211 } else if (is_string($nothing) and $nothing !== '') {
1213 $options = array(''=>$nothing) +
$options;
1216 // we may accept more values if multiple attribute specified
1217 $selected = (array)$selected;
1218 foreach ($selected as $k=>$v) {
1219 $selected[$k] = (string)$v;
1222 if (!isset($attributes['id'])) {
1224 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1225 $id = str_replace('[', '', $id);
1226 $id = str_replace(']', '', $id);
1227 $attributes['id'] = $id;
1230 if (!isset($attributes['class'])) {
1231 $class = 'menu'.$name;
1232 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1233 $class = str_replace('[', '', $class);
1234 $class = str_replace(']', '', $class);
1235 $attributes['class'] = $class;
1237 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
1239 $attributes['name'] = $name;
1241 if (!empty($attributes['disabled'])) {
1242 $attributes['disabled'] = 'disabled';
1244 unset($attributes['disabled']);
1248 foreach ($options as $value=>$label) {
1249 if (is_array($label)) {
1250 // ignore key, it just has to be unique
1251 $output .= self
::select_optgroup(key($label), current($label), $selected);
1253 $output .= self
::select_option($label, $value, $selected);
1256 return self
::tag('select', $output, $attributes);
1260 * Returns HTML to display a select box option.
1262 * @param string $label The label to display as the option.
1263 * @param string|int $value The value the option represents
1264 * @param array $selected An array of selected options
1265 * @return string HTML fragment
1267 private static function select_option($label, $value, array $selected) {
1268 $attributes = array();
1269 $value = (string)$value;
1270 if (in_array($value, $selected, true)) {
1271 $attributes['selected'] = 'selected';
1273 $attributes['value'] = $value;
1274 return self
::tag('option', $label, $attributes);
1278 * Returns HTML to display a select box option group.
1280 * @param string $groupname The label to use for the group
1281 * @param array $options The options in the group
1282 * @param array $selected An array of selected values.
1283 * @return string HTML fragment.
1285 private static function select_optgroup($groupname, $options, array $selected) {
1286 if (empty($options)) {
1289 $attributes = array('label'=>$groupname);
1291 foreach ($options as $value=>$label) {
1292 $output .= self
::select_option($label, $value, $selected);
1294 return self
::tag('optgroup', $output, $attributes);
1298 * This is a shortcut for making an hour selector menu.
1300 * @param string $type The type of selector (years, months, days, hours, minutes)
1301 * @param string $name fieldname
1302 * @param int $currenttime A default timestamp in GMT
1303 * @param int $step minute spacing
1304 * @param array $attributes - html select element attributes
1305 * @return HTML fragment
1307 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1308 if (!$currenttime) {
1309 $currenttime = time();
1311 $currentdate = usergetdate($currenttime);
1312 $userdatetype = $type;
1313 $timeunits = array();
1317 for ($i=1970; $i<=2020; $i++
) {
1318 $timeunits[$i] = $i;
1320 $userdatetype = 'year';
1323 for ($i=1; $i<=12; $i++
) {
1324 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1326 $userdatetype = 'month';
1327 $currentdate['month'] = (int)$currentdate['mon'];
1330 for ($i=1; $i<=31; $i++
) {
1331 $timeunits[$i] = $i;
1333 $userdatetype = 'mday';
1336 for ($i=0; $i<=23; $i++
) {
1337 $timeunits[$i] = sprintf("%02d",$i);
1342 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1345 for ($i=0; $i<=59; $i+
=$step) {
1346 $timeunits[$i] = sprintf("%02d",$i);
1350 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1353 if (empty($attributes['id'])) {
1354 $attributes['id'] = self
::random_id('ts_');
1356 $timerselector = self
::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1357 $label = self
::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1359 return $label.$timerselector;
1363 * Shortcut for quick making of lists
1365 * Note: 'list' is a reserved keyword ;-)
1367 * @param array $items
1368 * @param array $attributes
1369 * @param string $tag ul or ol
1372 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1375 foreach ($items as $item) {
1376 $output .= html_writer
::start_tag('li') . "\n";
1377 $output .= $item . "\n";
1378 $output .= html_writer
::end_tag('li') . "\n";
1381 return html_writer
::tag($tag, $output, $attributes);
1385 * Returns hidden input fields created from url parameters.
1387 * @param moodle_url $url
1388 * @param array $exclude list of excluded parameters
1389 * @return string HTML fragment
1391 public static function input_hidden_params(moodle_url
$url, array $exclude = null) {
1392 $exclude = (array)$exclude;
1393 $params = $url->params();
1394 foreach ($exclude as $key) {
1395 unset($params[$key]);
1399 foreach ($params as $key => $value) {
1400 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1401 $output .= self
::empty_tag('input', $attributes)."\n";
1407 * Generate a script tag containing the the specified code.
1409 * @param string $jscode the JavaScript code
1410 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
1411 * @return string HTML, the code wrapped in <script> tags.
1413 public static function script($jscode, $url=null) {
1415 $attributes = array('type'=>'text/javascript');
1416 return self
::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1419 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1420 return self
::tag('script', '', $attributes) . "\n";
1428 * Renders HTML table
1430 * This method may modify the passed instance by adding some default properties if they are not set yet.
1431 * If this is not what you want, you should make a full clone of your data before passing them to this
1432 * method. In most cases this is not an issue at all so we do not clone by default for performance
1433 * and memory consumption reasons.
1435 * @param html_table $table data to be rendered
1436 * @return string HTML code
1438 public static function table(html_table
$table) {
1439 // prepare table data and populate missing properties with reasonable defaults
1440 if (!empty($table->align
)) {
1441 foreach ($table->align
as $key => $aa) {
1443 $table->align
[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1445 $table->align
[$key] = null;
1449 if (!empty($table->size
)) {
1450 foreach ($table->size
as $key => $ss) {
1452 $table->size
[$key] = 'width:'. $ss .';';
1454 $table->size
[$key] = null;
1458 if (!empty($table->wrap
)) {
1459 foreach ($table->wrap
as $key => $ww) {
1461 $table->wrap
[$key] = 'white-space:nowrap;';
1463 $table->wrap
[$key] = '';
1467 if (!empty($table->head
)) {
1468 foreach ($table->head
as $key => $val) {
1469 if (!isset($table->align
[$key])) {
1470 $table->align
[$key] = null;
1472 if (!isset($table->size
[$key])) {
1473 $table->size
[$key] = null;
1475 if (!isset($table->wrap
[$key])) {
1476 $table->wrap
[$key] = null;
1481 if (empty($table->attributes
['class'])) {
1482 $table->attributes
['class'] = 'generaltable';
1484 if (!empty($table->tablealign
)) {
1485 $table->attributes
['class'] .= ' boxalign' . $table->tablealign
;
1488 // explicitly assigned properties override those defined via $table->attributes
1489 $table->attributes
['class'] = trim($table->attributes
['class']);
1490 $attributes = array_merge($table->attributes
, array(
1492 'width' => $table->width
,
1493 'summary' => $table->summary
,
1494 'cellpadding' => $table->cellpadding
,
1495 'cellspacing' => $table->cellspacing
,
1497 $output = html_writer
::start_tag('table', $attributes) . "\n";
1501 if (!empty($table->head
)) {
1502 $countcols = count($table->head
);
1504 $output .= html_writer
::start_tag('thead', array()) . "\n";
1505 $output .= html_writer
::start_tag('tr', array()) . "\n";
1506 $keys = array_keys($table->head
);
1507 $lastkey = end($keys);
1509 foreach ($table->head
as $key => $heading) {
1510 // Convert plain string headings into html_table_cell objects
1511 if (!($heading instanceof html_table_cell
)) {
1512 $headingtext = $heading;
1513 $heading = new html_table_cell();
1514 $heading->text
= $headingtext;
1515 $heading->header
= true;
1518 if ($heading->header
!== false) {
1519 $heading->header
= true;
1522 if ($heading->header
&& empty($heading->scope
)) {
1523 $heading->scope
= 'col';
1526 $heading->attributes
['class'] .= ' header c' . $key;
1527 if (isset($table->headspan
[$key]) && $table->headspan
[$key] > 1) {
1528 $heading->colspan
= $table->headspan
[$key];
1529 $countcols +
= $table->headspan
[$key] - 1;
1532 if ($key == $lastkey) {
1533 $heading->attributes
['class'] .= ' lastcol';
1535 if (isset($table->colclasses
[$key])) {
1536 $heading->attributes
['class'] .= ' ' . $table->colclasses
[$key];
1538 $heading->attributes
['class'] = trim($heading->attributes
['class']);
1539 $attributes = array_merge($heading->attributes
, array(
1540 'style' => $table->align
[$key] . $table->size
[$key] . $heading->style
,
1541 'scope' => $heading->scope
,
1542 'colspan' => $heading->colspan
,
1546 if ($heading->header
=== true) {
1549 $output .= html_writer
::tag($tagtype, $heading->text
, $attributes) . "\n";
1551 $output .= html_writer
::end_tag('tr') . "\n";
1552 $output .= html_writer
::end_tag('thead') . "\n";
1554 if (empty($table->data
)) {
1555 // For valid XHTML strict every table must contain either a valid tr
1556 // or a valid tbody... both of which must contain a valid td
1557 $output .= html_writer
::start_tag('tbody', array('class' => 'empty'));
1558 $output .= html_writer
::tag('tr', html_writer
::tag('td', '', array('colspan'=>count($table->head
))));
1559 $output .= html_writer
::end_tag('tbody');
1563 if (!empty($table->data
)) {
1565 $keys = array_keys($table->data
);
1566 $lastrowkey = end($keys);
1567 $output .= html_writer
::start_tag('tbody', array());
1569 foreach ($table->data
as $key => $row) {
1570 if (($row === 'hr') && ($countcols)) {
1571 $output .= html_writer
::tag('td', html_writer
::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1573 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1574 if (!($row instanceof html_table_row
)) {
1575 $newrow = new html_table_row();
1577 foreach ($row as $item) {
1578 $cell = new html_table_cell();
1579 $cell->text
= $item;
1580 $newrow->cells
[] = $cell;
1585 $oddeven = $oddeven ?
0 : 1;
1586 if (isset($table->rowclasses
[$key])) {
1587 $row->attributes
['class'] .= ' ' . $table->rowclasses
[$key];
1590 $row->attributes
['class'] .= ' r' . $oddeven;
1591 if ($key == $lastrowkey) {
1592 $row->attributes
['class'] .= ' lastrow';
1595 $output .= html_writer
::start_tag('tr', array('class' => trim($row->attributes
['class']), 'style' => $row->style
, 'id' => $row->id
)) . "\n";
1596 $keys2 = array_keys($row->cells
);
1597 $lastkey = end($keys2);
1599 $gotlastkey = false; //flag for sanity checking
1600 foreach ($row->cells
as $key => $cell) {
1602 //This should never happen. Why do we have a cell after the last cell?
1603 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1606 if (!($cell instanceof html_table_cell
)) {
1607 $mycell = new html_table_cell();
1608 $mycell->text
= $cell;
1612 if (($cell->header
=== true) && empty($cell->scope
)) {
1613 $cell->scope
= 'row';
1616 if (isset($table->colclasses
[$key])) {
1617 $cell->attributes
['class'] .= ' ' . $table->colclasses
[$key];
1620 $cell->attributes
['class'] .= ' cell c' . $key;
1621 if ($key == $lastkey) {
1622 $cell->attributes
['class'] .= ' lastcol';
1626 $tdstyle .= isset($table->align
[$key]) ?
$table->align
[$key] : '';
1627 $tdstyle .= isset($table->size
[$key]) ?
$table->size
[$key] : '';
1628 $tdstyle .= isset($table->wrap
[$key]) ?
$table->wrap
[$key] : '';
1629 $cell->attributes
['class'] = trim($cell->attributes
['class']);
1630 $tdattributes = array_merge($cell->attributes
, array(
1631 'style' => $tdstyle . $cell->style
,
1632 'colspan' => $cell->colspan
,
1633 'rowspan' => $cell->rowspan
,
1635 'abbr' => $cell->abbr
,
1636 'scope' => $cell->scope
,
1639 if ($cell->header
=== true) {
1642 $output .= html_writer
::tag($tagtype, $cell->text
, $tdattributes) . "\n";
1645 $output .= html_writer
::end_tag('tr') . "\n";
1647 $output .= html_writer
::end_tag('tbody') . "\n";
1649 $output .= html_writer
::end_tag('table') . "\n";
1655 * Renders form element label
1657 * By default, the label is suffixed with a label separator defined in the
1658 * current language pack (colon by default in the English lang pack).
1659 * Adding the colon can be explicitly disabled if needed. Label separators
1660 * are put outside the label tag itself so they are not read by
1661 * screenreaders (accessibility).
1663 * Parameter $for explicitly associates the label with a form control. When
1664 * set, the value of this attribute must be the same as the value of
1665 * the id attribute of the form control in the same document. When null,
1666 * the label being defined is associated with the control inside the label
1669 * @param string $text content of the label tag
1670 * @param string|null $for id of the element this label is associated with, null for no association
1671 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1672 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1673 * @return string HTML of the label element
1675 public static function label($text, $for, $colonize = true, array $attributes=array()) {
1676 if (!is_null($for)) {
1677 $attributes = array_merge($attributes, array('for' => $for));
1679 $text = trim($text);
1680 $label = self
::tag('label', $text, $attributes);
1682 // TODO MDL-12192 $colonize disabled for now yet
1683 // if (!empty($text) and $colonize) {
1684 // // the $text may end with the colon already, though it is bad string definition style
1685 // $colon = get_string('labelsep', 'langconfig');
1686 // if (!empty($colon)) {
1687 // $trimmed = trim($colon);
1688 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1689 // //debugging('The label text should not end with colon or other label separator,
1690 // // please fix the string definition.', DEBUG_DEVELOPER);
1692 // $label .= $colon;
1702 * Simple javascript output class
1704 * @copyright 2010 Petr Skoda
1705 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1713 * Returns javascript code calling the function
1715 * @param string $function function name, can be complex like Y.Event.purgeElement
1716 * @param array $arguments parameters
1717 * @param int $delay execution delay in seconds
1718 * @return string JS code fragment
1720 public static function function_call($function, array $arguments = null, $delay=0) {
1722 $arguments = array_map('json_encode', convert_to_array($arguments));
1723 $arguments = implode(', ', $arguments);
1727 $js = "$function($arguments);";
1730 $delay = $delay * 1000; // in miliseconds
1731 $js = "setTimeout(function() { $js }, $delay);";
1737 * Special function which adds Y as first argument of function call.
1739 * @param string $function The function to call
1740 * @param array $extraarguments Any arguments to pass to it
1741 * @return string Some JS code
1743 public static function function_call_with_Y($function, array $extraarguments = null) {
1744 if ($extraarguments) {
1745 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1746 $arguments = 'Y, ' . implode(', ', $extraarguments);
1750 return "$function($arguments);\n";
1754 * Returns JavaScript code to initialise a new object
1756 * @param string $var If it is null then no var is assigned the new object.
1757 * @param string $class The class to initialise an object for.
1758 * @param array $arguments An array of args to pass to the init method.
1759 * @param array $requirements Any modules required for this class.
1760 * @param int $delay The delay before initialisation. 0 = no delay.
1761 * @return string Some JS code
1763 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1764 if (is_array($arguments)) {
1765 $arguments = array_map('json_encode', convert_to_array($arguments));
1766 $arguments = implode(', ', $arguments);
1769 if ($var === null) {
1770 $js = "new $class(Y, $arguments);";
1771 } else if (strpos($var, '.')!==false) {
1772 $js = "$var = new $class(Y, $arguments);";
1774 $js = "var $var = new $class(Y, $arguments);";
1778 $delay = $delay * 1000; // in miliseconds
1779 $js = "setTimeout(function() { $js }, $delay);";
1782 if (count($requirements) > 0) {
1783 $requirements = implode("', '", $requirements);
1784 $js = "Y.use('$requirements', function(Y){ $js });";
1790 * Returns code setting value to variable
1792 * @param string $name
1793 * @param mixed $value json serialised value
1794 * @param bool $usevar add var definition, ignored for nested properties
1795 * @return string JS code fragment
1797 public static function set_variable($name, $value, $usevar = true) {
1801 if (strpos($name, '.')) {
1808 $output .= "$name = ".json_encode($value).";";
1814 * Writes event handler attaching code
1816 * @param array|string $selector standard YUI selector for elements, may be
1817 * array or string, element id is in the form "#idvalue"
1818 * @param string $event A valid DOM event (click, mousedown, change etc.)
1819 * @param string $function The name of the function to call
1820 * @param array $arguments An optional array of argument parameters to pass to the function
1821 * @return string JS code fragment
1823 public static function event_handler($selector, $event, $function, array $arguments = null) {
1824 $selector = json_encode($selector);
1825 $output = "Y.on('$event', $function, $selector, null";
1826 if (!empty($arguments)) {
1827 $output .= ', ' . json_encode($arguments);
1829 return $output . ");\n";
1834 * Holds all the information required to render a <table> by {@link core_renderer::table()}
1837 * $t = new html_table();
1838 * ... // set various properties of the object $t as described below
1839 * echo html_writer::table($t);
1841 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1842 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1850 * @var string Value to use for the id attribute of the table
1855 * @var array Attributes of HTML attributes for the <table> element
1857 public $attributes = array();
1860 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
1861 * For more control over the rendering of the headers, an array of html_table_cell objects
1862 * can be passed instead of an array of strings.
1865 * $t->head = array('Student', 'Grade');
1870 * @var array An array that can be used to make a heading span multiple columns.
1871 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1872 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
1875 * $t->headspan = array(2,1);
1880 * @var array An array of column alignments.
1881 * The value is used as CSS 'text-align' property. Therefore, possible
1882 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1883 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1885 * Examples of usage:
1886 * $t->align = array(null, 'right');
1888 * $t->align[1] = 'right';
1893 * @var array The value is used as CSS 'size' property.
1895 * Examples of usage:
1896 * $t->size = array('50%', '50%');
1898 * $t->size[1] = '120px';
1903 * @var array An array of wrapping information.
1904 * The only possible value is 'nowrap' that sets the
1905 * CSS property 'white-space' to the value 'nowrap' in the given column.
1908 * $t->wrap = array(null, 'nowrap');
1913 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
1914 * $head specified, the string 'hr' (for horizontal ruler) can be used
1915 * instead of an array of cells data resulting in a divider rendered.
1917 * Example of usage with array of arrays:
1918 * $row1 = array('Harry Potter', '76 %');
1919 * $row2 = array('Hermione Granger', '100 %');
1920 * $t->data = array($row1, $row2);
1922 * Example with array of html_table_row objects: (used for more fine-grained control)
1923 * $cell1 = new html_table_cell();
1924 * $cell1->text = 'Harry Potter';
1925 * $cell1->colspan = 2;
1926 * $row1 = new html_table_row();
1927 * $row1->cells[] = $cell1;
1928 * $cell2 = new html_table_cell();
1929 * $cell2->text = 'Hermione Granger';
1930 * $cell3 = new html_table_cell();
1931 * $cell3->text = '100 %';
1932 * $row2 = new html_table_row();
1933 * $row2->cells = array($cell2, $cell3);
1934 * $t->data = array($row1, $row2);
1939 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1940 * @var string Width of the table, percentage of the page preferred.
1942 public $width = null;
1945 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1946 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
1948 public $tablealign = null;
1951 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1952 * @var int Padding on each cell, in pixels
1954 public $cellpadding = null;
1957 * @var int Spacing between cells, in pixels
1958 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1960 public $cellspacing = null;
1963 * @var array Array of classes to add to particular rows, space-separated string.
1964 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1965 * respectively. Class 'lastrow' is added automatically for the last row
1969 * $t->rowclasses[9] = 'tenth'
1974 * @var array An array of classes to add to every cell in a particular column,
1975 * space-separated string. Class 'cell' is added automatically by the renderer.
1976 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1977 * respectively. Class 'lastcol' is added automatically for all last cells
1981 * $t->colclasses = array(null, 'grade');
1986 * @var string Description of the contents for screen readers.
1993 public function __construct() {
1994 $this->attributes
['class'] = '';
1999 * Component representing a table row.
2001 * @copyright 2009 Nicolas Connault
2002 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2007 class html_table_row
{
2010 * @var string Value to use for the id attribute of the row.
2015 * @var array Array of html_table_cell objects
2017 public $cells = array();
2020 * @var string Value to use for the style attribute of the table row
2022 public $style = null;
2025 * @var array Attributes of additional HTML attributes for the <tr> element
2027 public $attributes = array();
2031 * @param array $cells
2033 public function __construct(array $cells=null) {
2034 $this->attributes
['class'] = '';
2035 $cells = (array)$cells;
2036 foreach ($cells as $cell) {
2037 if ($cell instanceof html_table_cell
) {
2038 $this->cells
[] = $cell;
2040 $this->cells
[] = new html_table_cell($cell);
2047 * Component representing a table cell.
2049 * @copyright 2009 Nicolas Connault
2050 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2055 class html_table_cell
{
2058 * @var string Value to use for the id attribute of the cell.
2063 * @var string The contents of the cell.
2068 * @var string Abbreviated version of the contents of the cell.
2070 public $abbr = null;
2073 * @var int Number of columns this cell should span.
2075 public $colspan = null;
2078 * @var int Number of rows this cell should span.
2080 public $rowspan = null;
2083 * @var string Defines a way to associate header cells and data cells in a table.
2085 public $scope = null;
2088 * @var bool Whether or not this cell is a header cell.
2090 public $header = null;
2093 * @var string Value to use for the style attribute of the table cell
2095 public $style = null;
2098 * @var array Attributes of additional HTML attributes for the <td> element
2100 public $attributes = array();
2103 * Constructs a table cell
2105 * @param string $text
2107 public function __construct($text = null) {
2108 $this->text
= $text;
2109 $this->attributes
['class'] = '';
2114 * Component representing a paging bar.
2116 * @copyright 2009 Nicolas Connault
2117 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2122 class paging_bar
implements renderable
{
2125 * @var int The maximum number of pagelinks to display.
2127 public $maxdisplay = 18;
2130 * @var int The total number of entries to be pages through..
2135 * @var int The page you are currently viewing.
2140 * @var int The number of entries that should be shown per page.
2145 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2146 * an equals sign and the page number.
2147 * If this is a moodle_url object then the pagevar param will be replaced by
2148 * the page no, for each page.
2153 * @var string This is the variable name that you use for the pagenumber in your
2154 * code (ie. 'tablepage', 'blogpage', etc)
2159 * @var string A HTML link representing the "previous" page.
2161 public $previouslink = null;
2164 * @var string A HTML link representing the "next" page.
2166 public $nextlink = null;
2169 * @var string A HTML link representing the first page.
2171 public $firstlink = null;
2174 * @var string A HTML link representing the last page.
2176 public $lastlink = null;
2179 * @var array An array of strings. One of them is just a string: the current page
2181 public $pagelinks = array();
2184 * Constructor paging_bar with only the required params.
2186 * @param int $totalcount The total number of entries available to be paged through
2187 * @param int $page The page you are currently viewing
2188 * @param int $perpage The number of entries that should be shown per page
2189 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2190 * @param string $pagevar name of page parameter that holds the page number
2192 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2193 $this->totalcount
= $totalcount;
2194 $this->page
= $page;
2195 $this->perpage
= $perpage;
2196 $this->baseurl
= $baseurl;
2197 $this->pagevar
= $pagevar;
2201 * Prepares the paging bar for output.
2203 * This method validates the arguments set up for the paging bar and then
2204 * produces fragments of HTML to assist display later on.
2206 * @param renderer_base $output
2207 * @param moodle_page $page
2208 * @param string $target
2209 * @throws coding_exception
2211 public function prepare(renderer_base
$output, moodle_page
$page, $target) {
2212 if (!isset($this->totalcount
) ||
is_null($this->totalcount
)) {
2213 throw new coding_exception('paging_bar requires a totalcount value.');
2215 if (!isset($this->page
) ||
is_null($this->page
)) {
2216 throw new coding_exception('paging_bar requires a page value.');
2218 if (empty($this->perpage
)) {
2219 throw new coding_exception('paging_bar requires a perpage value.');
2221 if (empty($this->baseurl
)) {
2222 throw new coding_exception('paging_bar requires a baseurl value.');
2225 if ($this->totalcount
> $this->perpage
) {
2226 $pagenum = $this->page
- 1;
2228 if ($this->page
> 0) {
2229 $this->previouslink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2232 if ($this->perpage
> 0) {
2233 $lastpage = ceil($this->totalcount
/ $this->perpage
);
2238 if ($this->page
> 15) {
2239 $startpage = $this->page
- 10;
2241 $this->firstlink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>0)), '1', array('class'=>'first'));
2246 $currpage = $startpage;
2247 $displaycount = $displaypage = 0;
2249 while ($displaycount < $this->maxdisplay
and $currpage < $lastpage) {
2250 $displaypage = $currpage +
1;
2252 if ($this->page
== $currpage) {
2253 $this->pagelinks
[] = $displaypage;
2255 $pagelink = html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$currpage)), $displaypage);
2256 $this->pagelinks
[] = $pagelink;
2263 if ($currpage < $lastpage) {
2264 $lastpageactual = $lastpage - 1;
2265 $this->lastlink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$lastpageactual)), $lastpage, array('class'=>'last'));
2268 $pagenum = $this->page +
1;
2270 if ($pagenum != $displaypage) {
2271 $this->nextlink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$pagenum)), get_string('next'), array('class'=>'next'));
2278 * This class represents how a block appears on a page.
2280 * During output, each block instance is asked to return a block_contents object,
2281 * those are then passed to the $OUTPUT->block function for display.
2283 * contents should probably be generated using a moodle_block_..._renderer.
2285 * Other block-like things that need to appear on the page, for example the
2286 * add new block UI, are also represented as block_contents objects.
2288 * @copyright 2009 Tim Hunt
2289 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2294 class block_contents
{
2296 /** Used when the block cannot be collapsed **/
2297 const NOT_HIDEABLE
= 0;
2299 /** Used when the block can be collapsed but currently is not **/
2302 /** Used when the block has been collapsed **/
2306 * @var int Used to set $skipid.
2308 protected static $idcounter = 1;
2311 * @var int All the blocks (or things that look like blocks) printed on
2312 * a page are given a unique number that can be used to construct id="" attributes.
2313 * This is set automatically be the {@link prepare()} method.
2314 * Do not try to set it manually.
2319 * @var int If this is the contents of a real block, this should be set
2320 * to the block_instance.id. Otherwise this should be set to 0.
2322 public $blockinstanceid = 0;
2325 * @var int If this is a real block instance, and there is a corresponding
2326 * block_position.id for the block on this page, this should be set to that id.
2327 * Otherwise it should be 0.
2329 public $blockpositionid = 0;
2332 * @var array An array of attribute => value pairs that are put on the outer div of this
2333 * block. {@link $id} and {@link $classes} attributes should be set separately.
2338 * @var string The title of this block. If this came from user input, it should already
2339 * have had format_string() processing done on it. This will be output inside
2340 * <h2> tags. Please do not cause invalid XHTML.
2345 * @var string HTML for the content
2347 public $content = '';
2350 * @var array An alternative to $content, it you want a list of things with optional icons.
2352 public $footer = '';
2355 * @var string Any small print that should appear under the block to explain
2356 * to the teacher about the block, for example 'This is a sticky block that was
2357 * added in the system context.'
2359 public $annotation = '';
2362 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2363 * the user can toggle whether this block is visible.
2365 public $collapsible = self
::NOT_HIDEABLE
;
2368 * @var array A (possibly empty) array of editing controls. Each element of
2369 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2370 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2372 public $controls = array();
2376 * Create new instance of block content
2377 * @param array $attributes
2379 public function __construct(array $attributes = null) {
2380 $this->skipid
= self
::$idcounter;
2381 self
::$idcounter +
= 1;
2385 $this->attributes
= $attributes;
2387 // simple "fake" blocks used in some modules and "Add new block" block
2388 $this->attributes
= array('class'=>'block');
2393 * Add html class to block
2395 * @param string $class
2397 public function add_class($class) {
2398 $this->attributes
['class'] .= ' '.$class;
2404 * This class represents a target for where a block can go when it is being moved.
2406 * This needs to be rendered as a form with the given hidden from fields, and
2407 * clicking anywhere in the form should submit it. The form action should be
2410 * @copyright 2009 Tim Hunt
2411 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2416 class block_move_target
{
2419 * @var moodle_url Move url
2430 * @param string $text
2431 * @param moodle_url $url
2433 public function __construct($text, moodle_url
$url) {
2434 $this->text
= $text;
2442 * This class is used to represent one item within a custom menu that may or may
2443 * not have children.
2445 * @copyright 2010 Sam Hemelryk
2446 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2451 class custom_menu_item
implements renderable
{
2454 * @var string The text to show for the item
2459 * @var moodle_url The link to give the icon if it has no children
2464 * @var string A title to apply to the item. By default the text
2469 * @var int A sort order for the item, not necessary if you order things in
2475 * @var custom_menu_item A reference to the parent for this item or NULL if
2476 * it is a top level item
2481 * @var array A array in which to store children this item has.
2483 protected $children = array();
2486 * @var int A reference to the sort var of the last child that was added
2488 protected $lastsort = 0;
2491 * Constructs the new custom menu item
2493 * @param string $text
2494 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2495 * @param string $title A title to apply to this item [Optional]
2496 * @param int $sort A sort or to use if we need to sort differently [Optional]
2497 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2498 * belongs to, only if the child has a parent. [Optional]
2500 public function __construct($text, moodle_url
$url=null, $title=null, $sort = null, custom_menu_item
$parent = null) {
2501 $this->text
= $text;
2503 $this->title
= $title;
2504 $this->sort
= (int)$sort;
2505 $this->parent
= $parent;
2509 * Adds a custom menu item as a child of this node given its properties.
2511 * @param string $text
2512 * @param moodle_url $url
2513 * @param string $title
2515 * @return custom_menu_item
2517 public function add($text, moodle_url
$url = null, $title = null, $sort = null) {
2518 $key = count($this->children
);
2520 $sort = $this->lastsort +
1;
2522 $this->children
[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2523 $this->lastsort
= (int)$sort;
2524 return $this->children
[$key];
2528 * Returns the text for this item
2531 public function get_text() {
2536 * Returns the url for this item
2537 * @return moodle_url
2539 public function get_url() {
2544 * Returns the title for this item
2547 public function get_title() {
2548 return $this->title
;
2552 * Sorts and returns the children for this item
2555 public function get_children() {
2557 return $this->children
;
2561 * Gets the sort order for this child
2564 public function get_sort_order() {
2569 * Gets the parent this child belong to
2570 * @return custom_menu_item
2572 public function get_parent() {
2573 return $this->parent
;
2577 * Sorts the children this item has
2579 public function sort() {
2580 usort($this->children
, array('custom_menu','sort_custom_menu_items'));
2584 * Returns true if this item has any children
2587 public function has_children() {
2588 return (count($this->children
) > 0);
2592 * Sets the text for the node
2593 * @param string $text
2595 public function set_text($text) {
2596 $this->text
= (string)$text;
2600 * Sets the title for the node
2601 * @param string $title
2603 public function set_title($title) {
2604 $this->title
= (string)$title;
2608 * Sets the url for the node
2609 * @param moodle_url $url
2611 public function set_url(moodle_url
$url) {
2619 * This class is used to operate a custom menu that can be rendered for the page.
2620 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2621 * of custom_menu_item nodes that can be rendered by the core renderer.
2623 * To configure the custom menu:
2624 * Settings: Administration > Appearance > Themes > Theme settings
2626 * @copyright 2010 Sam Hemelryk
2627 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2632 class custom_menu
extends custom_menu_item
{
2635 * @var string The language we should render for, null disables multilang support.
2637 protected $currentlanguage = null;
2640 * Creates the custom menu
2642 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2643 * @param string $currentlanguage the current language code, null disables multilang support
2645 public function __construct($definition = '', $currentlanguage = null) {
2646 $this->currentlanguage
= $currentlanguage;
2647 parent
::__construct('root'); // create virtual root element of the menu
2648 if (!empty($definition)) {
2649 $this->override_children(self
::convert_text_to_menu_nodes($definition, $currentlanguage));
2654 * Overrides the children of this custom menu. Useful when getting children
2655 * from $CFG->custommenuitems
2657 * @param array $children
2659 public function override_children(array $children) {
2660 $this->children
= array();
2661 foreach ($children as $child) {
2662 if ($child instanceof custom_menu_item
) {
2663 $this->children
[] = $child;
2669 * Converts a string into a structured array of custom_menu_items which can
2670 * then be added to a custom menu.
2673 * text|url|title|langs
2674 * The number of hyphens at the start determines the depth of the item. The
2675 * languages are optional, comma separated list of languages the line is for.
2677 * Example structure:
2678 * First level first item|http://www.moodle.com/
2679 * -Second level first item|http://www.moodle.com/partners/
2680 * -Second level second item|http://www.moodle.com/hq/
2681 * --Third level first item|http://www.moodle.com/jobs/
2682 * -Second level third item|http://www.moodle.com/development/
2683 * First level second item|http://www.moodle.com/feedback/
2684 * First level third item
2685 * English only|http://moodle.com|English only item|en
2686 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2690 * @param string $text the menu items definition
2691 * @param string $language the language code, null disables multilang support
2694 public static function convert_text_to_menu_nodes($text, $language = null) {
2695 $lines = explode("\n", $text);
2696 $children = array();
2700 foreach ($lines as $line) {
2701 $line = trim($line);
2702 $bits = explode('|', $line, 4); // name|url|title|langs
2703 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2704 // Every item must have a name to be valid
2707 $bits[0] = ltrim($bits[0],'-');
2709 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2710 // Set the url to null
2713 // Make sure the url is a moodle url
2714 $bits[1] = new moodle_url(trim($bits[1]));
2716 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2717 // Set the title to null seeing as there isn't one
2718 $bits[2] = $bits[0];
2720 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2721 // The item is valid for all languages
2724 $itemlangs = array_map('trim', explode(',', $bits[3]));
2726 if (!empty($language) and !empty($itemlangs)) {
2727 // check that the item is intended for the current language
2728 if (!in_array($language, $itemlangs)) {
2732 // Set an incremental sort order to keep it simple.
2734 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2735 $depth = strlen($match[1]);
2736 if ($depth < $lastdepth) {
2737 $difference = $lastdepth - $depth;
2738 if ($lastdepth > 1 && $lastdepth != $difference) {
2739 $tempchild = $lastchild->get_parent();
2740 for ($i =0; $i < $difference; $i++
) {
2741 $tempchild = $tempchild->get_parent();
2743 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2746 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2747 $children[] = $lastchild;
2749 } else if ($depth > $lastdepth) {
2750 $depth = $lastdepth +
1;
2751 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2754 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2755 $children[] = $lastchild;
2757 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2762 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2763 $children[] = $lastchild;
2765 $lastdepth = $depth;
2771 * Sorts two custom menu items
2773 * This function is designed to be used with the usort method
2774 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2777 * @param custom_menu_item $itema
2778 * @param custom_menu_item $itemb
2781 public static function sort_custom_menu_items(custom_menu_item
$itema, custom_menu_item
$itemb) {
2782 $itema = $itema->get_sort_order();
2783 $itemb = $itemb->get_sort_order();
2784 if ($itema == $itemb) {
2787 return ($itema > $itemb) ? +
1 : -1;