3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Classes representing HTML elements, used by $OUTPUT methods
21 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
26 * @copyright 2009 Tim Hunt
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 defined('MOODLE_INTERNAL') || die();
33 * Interface marking other classes as suitable for renderer_base::render()
34 * @author 2010 Petr Skoda (skodak) info@skodak.org
36 interface renderable {
37 // intentionally empty
41 * Data structure representing a file picker.
43 * @copyright 2010 Dongsheng Cai
44 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47 class file_picker implements renderable {
49 public function __construct(stdClass $options) {
50 global $CFG, $USER, $PAGE;
51 require_once($CFG->dirroot. '/repository/lib.php');
53 'accepted_types'=>'*',
54 'return_types'=>FILE_INTERNAL,
55 'env' => 'filepicker',
56 'client_id' => uniqid(),
62 foreach ($defaults as $key=>$value) {
63 if (empty($options->$key)) {
64 $options->$key = $value;
68 $options->currentfile = '';
69 if (!empty($options->itemid)) {
70 $fs = get_file_storage();
71 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
72 if (empty($options->filename)) {
73 if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
74 $file = reset($files);
77 $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
80 $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
84 // initilise options, getting files in root path
85 $this->options = initialise_filepicker($options);
87 // copying other options
88 foreach ($options as $name=>$value) {
89 if (!isset($this->options->$name)) {
90 $this->options->$name = $value;
97 * Data structure representing a user picture.
99 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
100 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
103 class user_picture implements renderable {
105 * @var array List of mandatory fields in user record here. (do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
107 protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'imagealt', 'email'); //TODO: add deleted
110 * @var object $user A user object with at least fields all columns specified in $fields array constant set.
114 * @var int $courseid The course id. Used when constructing the link to the user's profile,
115 * page course id used if not specified.
119 * @var bool $link add course profile link to image
123 * @var int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility
127 * @var boolean $alttext add non-blank alt-text to the image.
128 * Default true, set to false when image alt just duplicates text in screenreaders.
130 public $alttext = true;
132 * @var boolean $popup Whether or not to open the link in a popup window.
134 public $popup = false;
136 * @var string Image class attribute
138 public $class = 'userpicture';
141 * User picture constructor.
143 * @param object $user user record with at least id, picture, imagealt, firstname and lastname set.
144 * @param array $options such as link, size, link, ...
146 public function __construct(stdClass $user) {
149 if (empty($user->id)) {
150 throw new coding_exception('User id is required when printing user avatar image.');
153 // only touch the DB if we are missing data and complain loudly...
155 foreach (self::$fields as $field) {
156 if (!array_key_exists($field, $user)) {
158 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
159 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
165 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
167 $this->user = clone($user);
172 * Returns a list of required user fields, useful when fetching required user info from db.
174 * In some cases we have to fetch the user data together with some other information,
175 * the idalias is useful there because the id would otherwise override the main
176 * id of the result record. Please note it has to be converted back to id before rendering.
178 * @param string $tableprefix name of database table prefix in query
179 * @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)
180 * @param string $idalias alias of id field
181 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
184 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
185 if (!$tableprefix and !$extrafields and !$idalias) {
186 return implode(',', self::$fields);
192 foreach (self::$fields as $field) {
193 if ($field === 'id' and $idalias and $idalias !== 'id') {
194 $fields[$field] = "$tableprefix$field AS $idalias";
196 if ($fieldprefix and $field !== 'id') {
197 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
199 $fields[$field] = "$tableprefix$field";
203 // add extra fields if not already there
205 foreach ($extrafields as $e) {
206 if ($e === 'id' or isset($fields[$e])) {
210 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
212 $fields[$e] = "$tableprefix$e";
216 return implode(',', $fields);
220 * Extract the aliased user fields from a given record
222 * Given a record that was previously obtained using {@link self::fields()} with aliases,
223 * this method extracts user related unaliased fields.
225 * @param stdClass $record containing user picture fields
226 * @param array $extrafields extra fields included in the $record
227 * @param string $idalias alias of the id field
228 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
229 * @return stdClass object with unaliased user fields
231 public static function unalias(stdClass $record, array $extrafields=null, $idalias='id', $fieldprefix='') {
233 if (empty($idalias)) {
237 $return = new stdClass();
239 foreach (self::$fields as $field) {
240 if ($field === 'id') {
241 if (property_exists($record, $idalias)) {
242 $return->id = $record->{$idalias};
245 if (property_exists($record, $fieldprefix.$field)) {
246 $return->{$field} = $record->{$fieldprefix.$field};
250 // add extra fields if not already there
252 foreach ($extrafields as $e) {
253 if ($e === 'id' or property_exists($return, $e)) {
256 $return->{$e} = $record->{$fieldprefix.$e};
264 * Works out the URL for the users picture.
266 * This method is recommended as it avoids costly redirects of user pictures
267 * if requests are made for non-existent files etc.
269 * @param renderer_base $renderer
272 public function get_url(moodle_page $page, renderer_base $renderer = null) {
273 global $CFG, $FULLME;
275 if (is_null($renderer)) {
276 $renderer = $page->get_renderer('core');
279 if (!empty($CFG->forcelogin) and !isloggedin()) {
280 // protect images if login required and not logged in;
281 // do not use require_login() because it is expensive and not suitable here anyway
282 return $renderer->pix_url('u/f1');
285 // Sort out the filename and size. Size is only required for the gravatar
286 // implementation presently.
287 if (empty($this->size)) {
290 } else if ($this->size === true or $this->size == 1) {
293 } else if ($this->size >= 50) {
295 $size = (int)$this->size;
298 $size = (int)$this->size;
301 // First we need to determine whether the user has uploaded a profile
303 if (!empty($this->user->deleted) or !$context = context_user::instance($this->user->id, IGNORE_MISSING)) {
304 $hasuploadedfile = false;
306 $fs = get_file_storage();
307 $hasuploadedfile = ($fs->file_exists($context->id, 'user', 'icon', 0, '/', $filename.'/.png') || $fs->file_exists($context->id, 'user', 'icon', 0, '/', $filename.'/.jpg'));
310 $imageurl = $renderer->pix_url('u/'.$filename);
311 if ($hasuploadedfile && $this->user->picture == 1) {
313 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
314 // We append the theme name to the file path if we have it so that
315 // in the circumstance that the profile picture is not available
316 // when the user actually requests it they still get the profile
317 // picture for the correct theme.
318 $path .= $page->theme->name.'/';
320 // Set the image URL to the URL for the uploaded file.
321 $imageurl = moodle_url::make_pluginfile_url($context->id, 'user', 'icon', NULL, $path, $filename);
322 } else if (!empty($CFG->enablegravatar)) {
323 // Normalise the size variable to acceptable bounds
324 if ($size < 1 || $size > 512) {
327 // Hash the users email address
328 $md5 = md5(strtolower(trim($this->user->email)));
329 // Build a gravatar URL with what we know.
330 // If the currently requested page is https then we'll return an
331 // https gravatar page.
332 if (strpos($FULLME, 'https://') === 0) {
333 $imageurl = new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $imageurl->out(false)));
335 $imageurl = new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $imageurl->out(false)));
339 // Return the URL that has been generated.
345 * Data structure representing a help icon.
347 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
348 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
351 class old_help_icon implements renderable {
353 * @var string $helpidentifier lang pack identifier
355 public $helpidentifier;
357 * @var string $title A descriptive text for title tooltip
359 public $title = null;
361 * @var string $component Component name, the same as in get_string()
363 public $component = 'moodle';
365 * @var string $linktext Extra descriptive text next to the icon
367 public $linktext = null;
370 * Constructor: sets up the other components in case they are needed
371 * @param string $helpidentifier The keyword that defines a help page
372 * @param string $title A descriptive text for accessibility only
373 * @param string $component
374 * @param bool $linktext add extra text to icon
377 public function __construct($helpidentifier, $title, $component = 'moodle') {
379 throw new coding_exception('A help_icon object requires a $text parameter');
381 if (empty($helpidentifier)) {
382 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
385 $this->helpidentifier = $helpidentifier;
386 $this->title = $title;
387 $this->component = $component;
392 * Data structure representing a help icon.
394 * @copyright 2010 Petr Skoda (info@skodak.org)
395 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
398 class help_icon implements renderable {
400 * @var string $identifier lang pack identifier (without the "_help" suffix),
401 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
406 * @var string $component Component name, the same as in get_string()
410 * @var string $linktext Extra descriptive text next to the icon
412 public $linktext = null;
416 * @param string $identifier string for help page title,
417 * string with _help suffix is used for the actual help text.
418 * string with _link suffix is used to create a link to further info (if it exists)
419 * @param string $component
421 public function __construct($identifier, $component) {
422 $this->identifier = $identifier;
423 $this->component = $component;
427 * Verifies that both help strings exists, shows debug warnings if not
429 public function diag_strings() {
430 $sm = get_string_manager();
431 if (!$sm->string_exists($this->identifier, $this->component)) {
432 debugging("Help title string does not exist: [$this->identifier, $this->component]");
434 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
435 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
442 * Data structure representing an icon.
444 * @copyright 2010 Petr Skoda
445 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
448 class pix_icon implements renderable {
451 var $attributes = array();
455 * @param string $pix short icon name
456 * @param string $alt The alt text to use for the icon
457 * @param string $component component name
458 * @param array $attributes html attributes
460 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
462 $this->component = $component;
463 $this->attributes = (array)$attributes;
465 $this->attributes['alt'] = $alt;
466 if (empty($this->attributes['class'])) {
467 $this->attributes['class'] = 'smallicon';
469 if (!isset($this->attributes['title'])) {
470 $this->attributes['title'] = $this->attributes['alt'];
476 * Data structure representing an emoticon image
480 class pix_emoticon extends pix_icon implements renderable {
484 * @param string $pix short icon name
485 * @param string $alt alternative text
486 * @param string $component emoticon image provider
487 * @param array $attributes explicit HTML attributes
489 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
490 if (empty($attributes['class'])) {
491 $attributes['class'] = 'emoticon';
493 parent::__construct($pix, $alt, $component, $attributes);
498 * Data structure representing a simple form with only one button.
500 * @copyright 2009 Petr Skoda
501 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
504 class single_button implements renderable {
517 * @var string post or get
519 var $method = 'post';
524 var $class = 'singlebutton';
526 * True if button disabled, false if normal
529 var $disabled = false;
541 * List of attached actions
542 * @var array of component_action
544 var $actions = array();
548 * @param string|moodle_url $url
549 * @param string $label button text
550 * @param string $method get or post submit method
552 public function __construct(moodle_url $url, $label, $method='post') {
553 $this->url = clone($url);
554 $this->label = $label;
555 $this->method = $method;
559 * Shortcut for adding a JS confirm dialog when the button is clicked.
560 * The message must be a yes/no question.
561 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
564 public function add_confirm_action($confirmmessage) {
565 $this->add_action(new confirm_action($confirmmessage));
569 * Add action to the button.
570 * @param component_action $action
573 public function add_action(component_action $action) {
574 $this->actions[] = $action;
580 * Simple form with just one select field that gets submitted automatically.
581 * If JS not enabled small go button is printed too.
583 * @copyright 2009 Petr Skoda
584 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
587 class single_select implements renderable {
589 * Target url - includes hidden fields
594 * Name of the select element.
599 * @var array $options associative array value=>label ex.:
600 * array(1=>'One, 2=>Two)
601 * it is also possible to specify optgroup as complex label array ex.:
602 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
603 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
617 * Extra select field attributes
620 var $attributes = array();
628 * @var string post or get
635 var $class = 'singleselect';
637 * True if button disabled, false if normal
640 var $disabled = false;
652 * List of attached actions
653 * @var array of component_action
655 var $helpicon = null;
658 * @param moodle_url $url form action target, includes hidden fields
659 * @param string $name name of selection field - the changing parameter in url
660 * @param array $options list of options
661 * @param string $selected selected element
662 * @param array $nothing
663 * @param string $formid
665 public function __construct(moodle_url $url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
668 $this->options = $options;
669 $this->selected = $selected;
670 $this->nothing = $nothing;
671 $this->formid = $formid;
675 * Shortcut for adding a JS confirm dialog when the button is clicked.
676 * The message must be a yes/no question.
677 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
680 public function add_confirm_action($confirmmessage) {
681 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
685 * Add action to the button.
686 * @param component_action $action
689 public function add_action(component_action $action) {
690 $this->actions[] = $action;
695 * @param string $page The keyword that defines a help page
696 * @param string $title A descriptive text for accessibility only
697 * @param string $component
698 * @param bool $linktext add extra text to icon
701 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
702 $this->helpicon = new old_help_icon($helppage, $title, $component);
707 * @param string $identifier The keyword that defines a help page
708 * @param string $component
709 * @param bool $linktext add extra text to icon
712 public function set_help_icon($identifier, $component = 'moodle') {
713 $this->helpicon = new help_icon($identifier, $component);
717 * Sets select's label
718 * @param string $label
721 public function set_label($label) {
722 $this->label = $label;
728 * Simple URL selection widget description.
729 * @copyright 2009 Petr Skoda
730 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
733 class url_select implements renderable {
735 * @var array $urls associative array value=>label ex.:
736 * array(1=>'One, 2=>Two)
737 * it is also possible to specify optgroup as complex label array ex.:
738 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
739 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
753 * Extra select field attributes
756 var $attributes = array();
766 var $class = 'urlselect';
768 * True if button disabled, false if normal
771 var $disabled = false;
783 * List of attached actions
784 * @var array of component_action
786 var $helpicon = null;
788 * @var string If set, makes button visible with given name for button
790 var $showbutton = null;
793 * @param array $urls list of options
794 * @param string $selected selected element
795 * @param array $nothing
796 * @param string $formid
797 * @param string $showbutton Set to text of button if it should be visible
798 * or null if it should be hidden (hidden version always has text 'go')
800 public function __construct(array $urls, $selected='', $nothing=array(''=>'choosedots'),
801 $formid=null, $showbutton=null) {
803 $this->selected = $selected;
804 $this->nothing = $nothing;
805 $this->formid = $formid;
806 $this->showbutton = $showbutton;
811 * @param string $page The keyword that defines a help page
812 * @param string $title A descriptive text for accessibility only
813 * @param string $component
814 * @param bool $linktext add extra text to icon
817 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
818 $this->helpicon = new old_help_icon($helppage, $title, $component);
823 * @param string $identifier The keyword that defines a help page
824 * @param string $component
825 * @param bool $linktext add extra text to icon
828 public function set_help_icon($identifier, $component = 'moodle') {
829 $this->helpicon = new help_icon($identifier, $component);
833 * Sets select's label
834 * @param string $label
837 public function set_label($label) {
838 $this->label = $label;
844 * Data structure describing html link with special action attached.
845 * @copyright 2010 Petr Skoda
846 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
849 class action_link implements renderable {
857 * @var string HTML fragment
866 * List of actions attached to link
867 * @var array of component_action
873 * @param string|moodle_url $url
874 * @param string $text HTML fragment
875 * @param component_action $action
876 * @param array $attributes associative array of html link attributes + disabled
878 public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null) {
879 $this->url = clone($url);
881 $this->attributes = (array)$attributes;
883 $this->add_action($action);
888 * Add action to the link.
889 * @param component_action $action
892 public function add_action(component_action $action) {
893 $this->actions[] = $action;
896 public function add_class($class) {
897 if (empty($this->attributes['class'])) {
898 $this->attributes['class'] = $class;
900 $this->attributes['class'] .= ' ' . $class;
905 // ==== HTML writer and helper classes, will be probably moved elsewhere ======
908 * Simple html output class
909 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
913 * Outputs a tag with attributes and contents
914 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
915 * @param string $contents What goes between the opening and closing tags
916 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
917 * @return string HTML fragment
919 public static function tag($tagname, $contents, array $attributes = null) {
920 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
924 * Outputs an opening tag with attributes
925 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
926 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
927 * @return string HTML fragment
929 public static function start_tag($tagname, array $attributes = null) {
930 return '<' . $tagname . self::attributes($attributes) . '>';
934 * Outputs a closing tag
935 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
936 * @return string HTML fragment
938 public static function end_tag($tagname) {
939 return '</' . $tagname . '>';
943 * Outputs an empty tag with attributes
944 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
945 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
946 * @return string HTML fragment
948 public static function empty_tag($tagname, array $attributes = null) {
949 return '<' . $tagname . self::attributes($attributes) . ' />';
953 * Outputs a tag, but only if the contents are not empty
954 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
955 * @param string $contents What goes between the opening and closing tags
956 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
957 * @return string HTML fragment
959 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
960 if ($contents === '' || is_null($contents)) {
963 return self::tag($tagname, $contents, $attributes);
967 * Outputs a HTML attribute and value
968 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
969 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
970 * @return string HTML fragment
972 public static function attribute($name, $value) {
973 if (is_array($value)) {
974 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
976 if ($value instanceof moodle_url) {
977 return ' ' . $name . '="' . $value->out() . '"';
980 // special case, we do not want these in output
981 if ($value === null) {
985 // no sloppy trimming here!
986 return ' ' . $name . '="' . s($value) . '"';
990 * Outputs a list of HTML attributes and values
991 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
992 * The values will be escaped with {@link s()}
993 * @return string HTML fragment
995 public static function attributes(array $attributes = null) {
996 $attributes = (array)$attributes;
998 foreach ($attributes as $name => $value) {
999 $output .= self::attribute($name, $value);
1005 * Generates random html element id.
1006 * @param string $base
1009 public static function random_id($base='random') {
1010 static $counter = 0;
1013 if (!isset($uniq)) {
1018 return $base.$uniq.$counter;
1022 * Generates a simple html link
1023 * @param string|moodle_url $url
1024 * @param string $text link txt
1025 * @param array $attributes extra html attributes
1026 * @return string HTML fragment
1028 public static function link($url, $text, array $attributes = null) {
1029 $attributes = (array)$attributes;
1030 $attributes['href'] = $url;
1031 return self::tag('a', $text, $attributes);
1035 * generates a simple checkbox with optional label
1036 * @param string $name
1037 * @param string $value
1038 * @param bool $checked
1039 * @param string $label
1040 * @param array $attributes
1041 * @return string html fragment
1043 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1044 $attributes = (array)$attributes;
1047 if ($label !== '' and !is_null($label)) {
1048 if (empty($attributes['id'])) {
1049 $attributes['id'] = self::random_id('checkbox_');
1052 $attributes['type'] = 'checkbox';
1053 $attributes['value'] = $value;
1054 $attributes['name'] = $name;
1055 $attributes['checked'] = $checked ? 'checked' : null;
1057 $output .= self::empty_tag('input', $attributes);
1059 if ($label !== '' and !is_null($label)) {
1060 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1067 * Generates a simple select yes/no form field
1068 * @param string $name name of select element
1069 * @param bool $selected
1070 * @param array $attributes - html select element attributes
1071 * @return string HRML fragment
1073 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1074 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1075 return self::select($options, $name, $selected, null, $attributes);
1079 * Generates a simple select form field
1080 * @param array $options associative array value=>label ex.:
1081 * array(1=>'One, 2=>Two)
1082 * it is also possible to specify optgroup as complex label array ex.:
1083 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1084 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1085 * @param string $name name of select element
1086 * @param string|array $selected value or array of values depending on multiple attribute
1087 * @param array|bool $nothing, add nothing selected option, or false of not added
1088 * @param array $attributes - html select element attributes
1089 * @return string HTML fragment
1091 public static function select(array $options, $name, $selected = '', $nothing = array(''=>'choosedots'), array $attributes = null) {
1092 $attributes = (array)$attributes;
1093 if (is_array($nothing)) {
1094 foreach ($nothing as $k=>$v) {
1095 if ($v === 'choose' or $v === 'choosedots') {
1096 $nothing[$k] = get_string('choosedots');
1099 $options = $nothing + $options; // keep keys, do not override
1101 } else if (is_string($nothing) and $nothing !== '') {
1103 $options = array(''=>$nothing) + $options;
1106 // we may accept more values if multiple attribute specified
1107 $selected = (array)$selected;
1108 foreach ($selected as $k=>$v) {
1109 $selected[$k] = (string)$v;
1112 if (!isset($attributes['id'])) {
1114 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1115 $id = str_replace('[', '', $id);
1116 $id = str_replace(']', '', $id);
1117 $attributes['id'] = $id;
1120 if (!isset($attributes['class'])) {
1121 $class = 'menu'.$name;
1122 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1123 $class = str_replace('[', '', $class);
1124 $class = str_replace(']', '', $class);
1125 $attributes['class'] = $class;
1127 $attributes['class'] = 'select ' . $attributes['class']; /// Add 'select' selector always
1129 $attributes['name'] = $name;
1131 if (!empty($attributes['disabled'])) {
1132 $attributes['disabled'] = 'disabled';
1134 unset($attributes['disabled']);
1138 foreach ($options as $value=>$label) {
1139 if (is_array($label)) {
1140 // ignore key, it just has to be unique
1141 $output .= self::select_optgroup(key($label), current($label), $selected);
1143 $output .= self::select_option($label, $value, $selected);
1146 return self::tag('select', $output, $attributes);
1149 private static function select_option($label, $value, array $selected) {
1150 $attributes = array();
1151 $value = (string)$value;
1152 if (in_array($value, $selected, true)) {
1153 $attributes['selected'] = 'selected';
1155 $attributes['value'] = $value;
1156 return self::tag('option', $label, $attributes);
1159 private static function select_optgroup($groupname, $options, array $selected) {
1160 if (empty($options)) {
1163 $attributes = array('label'=>$groupname);
1165 foreach ($options as $value=>$label) {
1166 $output .= self::select_option($label, $value, $selected);
1168 return self::tag('optgroup', $output, $attributes);
1172 * This is a shortcut for making an hour selector menu.
1173 * @param string $type The type of selector (years, months, days, hours, minutes)
1174 * @param string $name fieldname
1175 * @param int $currenttime A default timestamp in GMT
1176 * @param int $step minute spacing
1177 * @param array $attributes - html select element attributes
1178 * @return HTML fragment
1180 public static function select_time($type, $name, $currenttime=0, $step=5, array $attributes=null) {
1181 if (!$currenttime) {
1182 $currenttime = time();
1184 $currentdate = usergetdate($currenttime);
1185 $userdatetype = $type;
1186 $timeunits = array();
1190 for ($i=1970; $i<=2020; $i++) {
1191 $timeunits[$i] = $i;
1193 $userdatetype = 'year';
1196 for ($i=1; $i<=12; $i++) {
1197 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1199 $userdatetype = 'month';
1200 $currentdate['month'] = $currentdate['mon'];
1203 for ($i=1; $i<=31; $i++) {
1204 $timeunits[$i] = $i;
1206 $userdatetype = 'mday';
1209 for ($i=0; $i<=23; $i++) {
1210 $timeunits[$i] = sprintf("%02d",$i);
1215 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1218 for ($i=0; $i<=59; $i+=$step) {
1219 $timeunits[$i] = sprintf("%02d",$i);
1223 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1226 if (empty($attributes['id'])) {
1227 $attributes['id'] = self::random_id('ts_');
1229 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1230 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1232 return $label.$timerselector;
1236 * Shortcut for quick making of lists
1237 * @param array $items
1238 * @param string $tag ul or ol
1239 * @param array $attributes
1242 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1243 //note: 'list' is a reserved keyword ;-)
1247 foreach ($items as $item) {
1248 $output .= html_writer::start_tag('li') . "\n";
1249 $output .= $item . "\n";
1250 $output .= html_writer::end_tag('li') . "\n";
1253 return html_writer::tag($tag, $output, $attributes);
1257 * Returns hidden input fields created from url parameters.
1258 * @param moodle_url $url
1259 * @param array $exclude list of excluded parameters
1260 * @return string HTML fragment
1262 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1263 $exclude = (array)$exclude;
1264 $params = $url->params();
1265 foreach ($exclude as $key) {
1266 unset($params[$key]);
1270 foreach ($params as $key => $value) {
1271 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1272 $output .= self::empty_tag('input', $attributes)."\n";
1278 * Generate a script tag containing the the specified code.
1280 * @param string $js the JavaScript code
1281 * @param moodle_url|string optional url of the external script, $code ignored if specified
1282 * @return string HTML, the code wrapped in <script> tags.
1284 public static function script($jscode, $url=null) {
1286 $attributes = array('type'=>'text/javascript');
1287 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1290 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1291 return self::tag('script', '', $attributes) . "\n";
1299 * Renders HTML table
1301 * This method may modify the passed instance by adding some default properties if they are not set yet.
1302 * If this is not what you want, you should make a full clone of your data before passing them to this
1303 * method. In most cases this is not an issue at all so we do not clone by default for performance
1304 * and memory consumption reasons.
1306 * @param html_table $table data to be rendered
1307 * @return string HTML code
1309 public static function table(html_table $table) {
1310 // prepare table data and populate missing properties with reasonable defaults
1311 if (!empty($table->align)) {
1312 foreach ($table->align as $key => $aa) {
1314 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1316 $table->align[$key] = null;
1320 if (!empty($table->size)) {
1321 foreach ($table->size as $key => $ss) {
1323 $table->size[$key] = 'width:'. $ss .';';
1325 $table->size[$key] = null;
1329 if (!empty($table->wrap)) {
1330 foreach ($table->wrap as $key => $ww) {
1332 $table->wrap[$key] = 'white-space:nowrap;';
1334 $table->wrap[$key] = '';
1338 if (!empty($table->head)) {
1339 foreach ($table->head as $key => $val) {
1340 if (!isset($table->align[$key])) {
1341 $table->align[$key] = null;
1343 if (!isset($table->size[$key])) {
1344 $table->size[$key] = null;
1346 if (!isset($table->wrap[$key])) {
1347 $table->wrap[$key] = null;
1352 if (empty($table->attributes['class'])) {
1353 $table->attributes['class'] = 'generaltable';
1355 if (!empty($table->tablealign)) {
1356 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1359 // explicitly assigned properties override those defined via $table->attributes
1360 $table->attributes['class'] = trim($table->attributes['class']);
1361 $attributes = array_merge($table->attributes, array(
1363 'width' => $table->width,
1364 'summary' => $table->summary,
1365 'cellpadding' => $table->cellpadding,
1366 'cellspacing' => $table->cellspacing,
1368 $output = html_writer::start_tag('table', $attributes) . "\n";
1372 if (!empty($table->head)) {
1373 $countcols = count($table->head);
1375 $output .= html_writer::start_tag('thead', array()) . "\n";
1376 $output .= html_writer::start_tag('tr', array()) . "\n";
1377 $keys = array_keys($table->head);
1378 $lastkey = end($keys);
1380 foreach ($table->head as $key => $heading) {
1381 // Convert plain string headings into html_table_cell objects
1382 if (!($heading instanceof html_table_cell)) {
1383 $headingtext = $heading;
1384 $heading = new html_table_cell();
1385 $heading->text = $headingtext;
1386 $heading->header = true;
1389 if ($heading->header !== false) {
1390 $heading->header = true;
1393 if ($heading->header && empty($heading->scope)) {
1394 $heading->scope = 'col';
1397 $heading->attributes['class'] .= ' header c' . $key;
1398 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1399 $heading->colspan = $table->headspan[$key];
1400 $countcols += $table->headspan[$key] - 1;
1403 if ($key == $lastkey) {
1404 $heading->attributes['class'] .= ' lastcol';
1406 if (isset($table->colclasses[$key])) {
1407 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1409 $heading->attributes['class'] = trim($heading->attributes['class']);
1410 $attributes = array_merge($heading->attributes, array(
1411 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1412 'scope' => $heading->scope,
1413 'colspan' => $heading->colspan,
1417 if ($heading->header === true) {
1420 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1422 $output .= html_writer::end_tag('tr') . "\n";
1423 $output .= html_writer::end_tag('thead') . "\n";
1425 if (empty($table->data)) {
1426 // For valid XHTML strict every table must contain either a valid tr
1427 // or a valid tbody... both of which must contain a valid td
1428 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1429 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1430 $output .= html_writer::end_tag('tbody');
1434 if (!empty($table->data)) {
1436 $keys = array_keys($table->data);
1437 $lastrowkey = end($keys);
1438 $output .= html_writer::start_tag('tbody', array());
1440 foreach ($table->data as $key => $row) {
1441 if (($row === 'hr') && ($countcols)) {
1442 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1444 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1445 if (!($row instanceof html_table_row)) {
1446 $newrow = new html_table_row();
1448 foreach ($row as $item) {
1449 $cell = new html_table_cell();
1450 $cell->text = $item;
1451 $newrow->cells[] = $cell;
1456 $oddeven = $oddeven ? 0 : 1;
1457 if (isset($table->rowclasses[$key])) {
1458 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1461 $row->attributes['class'] .= ' r' . $oddeven;
1462 if ($key == $lastrowkey) {
1463 $row->attributes['class'] .= ' lastrow';
1466 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1467 $keys2 = array_keys($row->cells);
1468 $lastkey = end($keys2);
1470 $gotlastkey = false; //flag for sanity checking
1471 foreach ($row->cells as $key => $cell) {
1473 //This should never happen. Why do we have a cell after the last cell?
1474 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1477 if (!($cell instanceof html_table_cell)) {
1478 $mycell = new html_table_cell();
1479 $mycell->text = $cell;
1483 if (($cell->header === true) && empty($cell->scope)) {
1484 $cell->scope = 'row';
1487 if (isset($table->colclasses[$key])) {
1488 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1491 $cell->attributes['class'] .= ' cell c' . $key;
1492 if ($key == $lastkey) {
1493 $cell->attributes['class'] .= ' lastcol';
1497 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1498 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1499 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1500 $cell->attributes['class'] = trim($cell->attributes['class']);
1501 $tdattributes = array_merge($cell->attributes, array(
1502 'style' => $tdstyle . $cell->style,
1503 'colspan' => $cell->colspan,
1504 'rowspan' => $cell->rowspan,
1506 'abbr' => $cell->abbr,
1507 'scope' => $cell->scope,
1510 if ($cell->header === true) {
1513 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1516 $output .= html_writer::end_tag('tr') . "\n";
1518 $output .= html_writer::end_tag('tbody') . "\n";
1520 $output .= html_writer::end_tag('table') . "\n";
1526 * Renders form element label
1528 * By default, the label is suffixed with a label separator defined in the
1529 * current language pack (colon by default in the English lang pack).
1530 * Adding the colon can be explicitly disabled if needed. Label separators
1531 * are put outside the label tag itself so they are not read by
1532 * screenreaders (accessibility).
1534 * Parameter $for explicitly associates the label with a form control. When
1535 * set, the value of this attribute must be the same as the value of
1536 * the id attribute of the form control in the same document. When null,
1537 * the label being defined is associated with the control inside the label
1540 * @param string $text content of the label tag
1541 * @param string|null $for id of the element this label is associated with, null for no association
1542 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1543 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1544 * @return string HTML of the label element
1546 public static function label($text, $for, $colonize=true, array $attributes=array()) {
1547 if (!is_null($for)) {
1548 $attributes = array_merge($attributes, array('for' => $for));
1550 $text = trim($text);
1551 $label = self::tag('label', $text, $attributes);
1554 // TODO $colonize disabled for now yet - see MDL-12192 for details
1555 if (!empty($text) and $colonize) {
1556 // the $text may end with the colon already, though it is bad string definition style
1557 $colon = get_string('labelsep', 'langconfig');
1558 if (!empty($colon)) {
1559 $trimmed = trim($colon);
1560 if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1561 //debugging('The label text should not end with colon or other label separator,
1562 // please fix the string definition.', DEBUG_DEVELOPER);
1574 // ==== JS writer and helper classes, will be probably moved elsewhere ======
1577 * Simple javascript output class
1578 * @copyright 2010 Petr Skoda
1582 * Returns javascript code calling the function
1583 * @param string $function function name, can be complex like Y.Event.purgeElement
1584 * @param array $arguments parameters
1585 * @param int $delay execution delay in seconds
1586 * @return string JS code fragment
1588 public static function function_call($function, array $arguments = null, $delay=0) {
1590 $arguments = array_map('json_encode', $arguments);
1591 $arguments = implode(', ', $arguments);
1595 $js = "$function($arguments);";
1598 $delay = $delay * 1000; // in miliseconds
1599 $js = "setTimeout(function() { $js }, $delay);";
1605 * Special function which adds Y as first argument of fucntion call.
1606 * @param string $function
1607 * @param array $extraarguments
1610 public static function function_call_with_Y($function, array $extraarguments = null) {
1611 if ($extraarguments) {
1612 $extraarguments = array_map('json_encode', $extraarguments);
1613 $arguments = 'Y, ' . implode(', ', $extraarguments);
1617 return "$function($arguments);\n";
1621 * Returns JavaScript code to initialise a new object
1622 * @param string|null $var If it is null then no var is assigned the new object
1623 * @param string $class
1624 * @param array $arguments
1625 * @param array $requirements
1629 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1630 if (is_array($arguments)) {
1631 $arguments = array_map('json_encode', $arguments);
1632 $arguments = implode(', ', $arguments);
1635 if ($var === null) {
1636 $js = "new $class(Y, $arguments);";
1637 } else if (strpos($var, '.')!==false) {
1638 $js = "$var = new $class(Y, $arguments);";
1640 $js = "var $var = new $class(Y, $arguments);";
1644 $delay = $delay * 1000; // in miliseconds
1645 $js = "setTimeout(function() { $js }, $delay);";
1648 if (count($requirements) > 0) {
1649 $requirements = implode("', '", $requirements);
1650 $js = "Y.use('$requirements', function(Y){ $js });";
1656 * Returns code setting value to variable
1657 * @param string $name
1658 * @param mixed $value json serialised value
1659 * @param bool $usevar add var definition, ignored for nested properties
1660 * @return string JS code fragment
1662 public static function set_variable($name, $value, $usevar=true) {
1666 if (strpos($name, '.')) {
1673 $output .= "$name = ".json_encode($value).";";
1679 * Writes event handler attaching code
1680 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1681 * @param string $event A valid DOM event (click, mousedown, change etc.)
1682 * @param string $function The name of the function to call
1683 * @param array $arguments An optional array of argument parameters to pass to the function
1684 * @return string JS code fragment
1686 public static function event_handler($selector, $event, $function, array $arguments = null) {
1687 $selector = json_encode($selector);
1688 $output = "Y.on('$event', $function, $selector, null";
1689 if (!empty($arguments)) {
1690 $output .= ', ' . json_encode($arguments);
1692 return $output . ");\n";
1697 * Holds all the information required to render a <table> by {@see core_renderer::table()}
1700 * $t = new html_table();
1701 * ... // set various properties of the object $t as described below
1702 * echo html_writer::table($t);
1704 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1705 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1710 * @var string value to use for the id attribute of the table
1714 * @var array attributes of HTML attributes for the <table> element
1716 public $attributes = array();
1718 * For more control over the rendering of the headers, an array of html_table_cell objects
1719 * can be passed instead of an array of strings.
1720 * @var array of headings. The n-th array item is used as a heading of the n-th column.
1723 * $t->head = array('Student', 'Grade');
1727 * @var array can be used to make a heading span multiple columns
1730 * $t->headspan = array(2,1);
1732 * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
1733 * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
1737 * @var array of column alignments. The value is used as CSS 'text-align' property. Therefore, possible
1738 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1739 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1741 * Examples of usage:
1742 * $t->align = array(null, 'right');
1744 * $t->align[1] = 'right';
1749 * @var array of column sizes. The value is used as CSS 'size' property.
1751 * Examples of usage:
1752 * $t->size = array('50%', '50%');
1754 * $t->size[1] = '120px';
1758 * @var array of wrapping information. The only possible value is 'nowrap' that sets the
1759 * CSS property 'white-space' to the value 'nowrap' in the given column.
1762 * $t->wrap = array(null, 'nowrap');
1766 * @var array of arrays or html_table_row objects containing the data. Alternatively, if you have
1767 * $head specified, the string 'hr' (for horizontal ruler) can be used
1768 * instead of an array of cells data resulting in a divider rendered.
1770 * Example of usage with array of arrays:
1771 * $row1 = array('Harry Potter', '76 %');
1772 * $row2 = array('Hermione Granger', '100 %');
1773 * $t->data = array($row1, $row2);
1775 * Example with array of html_table_row objects: (used for more fine-grained control)
1776 * $cell1 = new html_table_cell();
1777 * $cell1->text = 'Harry Potter';
1778 * $cell1->colspan = 2;
1779 * $row1 = new html_table_row();
1780 * $row1->cells[] = $cell1;
1781 * $cell2 = new html_table_cell();
1782 * $cell2->text = 'Hermione Granger';
1783 * $cell3 = new html_table_cell();
1784 * $cell3->text = '100 %';
1785 * $row2 = new html_table_row();
1786 * $row2->cells = array($cell2, $cell3);
1787 * $t->data = array($row1, $row2);
1791 * @var string width of the table, percentage of the page preferred. Defaults to 80%
1792 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1794 public $width = null;
1796 * @var string alignment the whole table. Can be 'right', 'left' or 'center' (default).
1797 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1799 public $tablealign = null;
1801 * @var int padding on each cell, in pixels
1802 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1804 public $cellpadding = null;
1806 * @var int spacing between cells, in pixels
1807 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1809 public $cellspacing = null;
1811 * @var array classes to add to particular rows, space-separated string.
1812 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1813 * respectively. Class 'lastrow' is added automatically for the last row
1817 * $t->rowclasses[9] = 'tenth'
1821 * @var array classes to add to every cell in a particular column,
1822 * space-separated string. Class 'cell' is added automatically by the renderer.
1823 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1824 * respectively. Class 'lastcol' is added automatically for all last cells
1828 * $t->colclasses = array(null, 'grade');
1832 * @var string description of the contents for screen readers.
1839 public function __construct() {
1840 $this->attributes['class'] = '';
1846 * Component representing a table row.
1848 * @copyright 2009 Nicolas Connault
1849 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1852 class html_table_row {
1854 * @var string value to use for the id attribute of the row
1858 * @var array $cells Array of html_table_cell objects
1860 public $cells = array();
1862 * @var string $style value to use for the style attribute of the table row
1864 public $style = null;
1866 * @var array attributes of additional HTML attributes for the <tr> element
1868 public $attributes = array();
1872 * @param array $cells
1874 public function __construct(array $cells=null) {
1875 $this->attributes['class'] = '';
1876 $cells = (array)$cells;
1877 foreach ($cells as $cell) {
1878 if ($cell instanceof html_table_cell) {
1879 $this->cells[] = $cell;
1881 $this->cells[] = new html_table_cell($cell);
1889 * Component representing a table cell.
1891 * @copyright 2009 Nicolas Connault
1892 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1895 class html_table_cell {
1897 * @var string value to use for the id attribute of the cell
1901 * @var string $text The contents of the cell
1905 * @var string $abbr Abbreviated version of the contents of the cell
1907 public $abbr = null;
1909 * @var int $colspan Number of columns this cell should span
1911 public $colspan = null;
1913 * @var int $rowspan Number of rows this cell should span
1915 public $rowspan = null;
1917 * @var string $scope Defines a way to associate header cells and data cells in a table
1919 public $scope = null;
1921 * @var boolean $header Whether or not this cell is a header cell
1923 public $header = null;
1925 * @var string $style value to use for the style attribute of the table cell
1927 public $style = null;
1929 * @var array attributes of additional HTML attributes for the <td> element
1931 public $attributes = array();
1933 public function __construct($text = null) {
1934 $this->text = $text;
1935 $this->attributes['class'] = '';
1940 /// Complex components aggregating simpler components
1944 * Component representing a paging bar.
1946 * @copyright 2009 Nicolas Connault
1947 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1950 class paging_bar implements renderable {
1952 * @var int $maxdisplay The maximum number of pagelinks to display
1954 public $maxdisplay = 18;
1956 * @var int $totalcount post or get
1960 * @var int $page The page you are currently viewing
1964 * @var int $perpage The number of entries that should be shown per page
1968 * @var string $baseurl If this is a string then it is the url which will be appended with $pagevar, an equals sign and the page number.
1969 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
1973 * @var string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
1977 * @var string $previouslink A HTML link representing the "previous" page
1979 public $previouslink = null;
1981 * @var tring $nextlink A HTML link representing the "next" page
1983 public $nextlink = null;
1985 * @var tring $firstlink A HTML link representing the first page
1987 public $firstlink = null;
1989 * @var tring $lastlink A HTML link representing the last page
1991 public $lastlink = null;
1993 * @var array $pagelinks An array of strings. One of them is just a string: the current page
1995 public $pagelinks = array();
1998 * Constructor paging_bar with only the required params.
2000 * @param int $totalcount The total number of entries available to be paged through
2001 * @param int $page The page you are currently viewing
2002 * @param int $perpage The number of entries that should be shown per page
2003 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2004 * @param string $pagevar name of page parameter that holds the page number
2006 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2007 $this->totalcount = $totalcount;
2008 $this->page = $page;
2009 $this->perpage = $perpage;
2010 $this->baseurl = $baseurl;
2011 $this->pagevar = $pagevar;
2017 public function prepare(renderer_base $output, moodle_page $page, $target) {
2018 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2019 throw new coding_exception('paging_bar requires a totalcount value.');
2021 if (!isset($this->page) || is_null($this->page)) {
2022 throw new coding_exception('paging_bar requires a page value.');
2024 if (empty($this->perpage)) {
2025 throw new coding_exception('paging_bar requires a perpage value.');
2027 if (empty($this->baseurl)) {
2028 throw new coding_exception('paging_bar requires a baseurl value.');
2031 if ($this->totalcount > $this->perpage) {
2032 $pagenum = $this->page - 1;
2034 if ($this->page > 0) {
2035 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2038 if ($this->perpage > 0) {
2039 $lastpage = ceil($this->totalcount / $this->perpage);
2044 if ($this->page > 15) {
2045 $startpage = $this->page - 10;
2047 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2052 $currpage = $startpage;
2053 $displaycount = $displaypage = 0;
2055 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2056 $displaypage = $currpage + 1;
2058 if ($this->page == $currpage) {
2059 $this->pagelinks[] = $displaypage;
2061 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2062 $this->pagelinks[] = $pagelink;
2069 if ($currpage < $lastpage) {
2070 $lastpageactual = $lastpage - 1;
2071 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2074 $pagenum = $this->page + 1;
2076 if ($pagenum != $displaypage) {
2077 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2085 * This class represents how a block appears on a page.
2087 * During output, each block instance is asked to return a block_contents object,
2088 * those are then passed to the $OUTPUT->block function for display.
2090 * {@link $contents} should probably be generated using a moodle_block_..._renderer.
2092 * Other block-like things that need to appear on the page, for example the
2093 * add new block UI, are also represented as block_contents objects.
2095 * @copyright 2009 Tim Hunt
2096 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2099 class block_contents {
2100 /** @var int used to set $skipid. */
2101 protected static $idcounter = 1;
2103 const NOT_HIDEABLE = 0;
2108 * @var integer $skipid All the blocks (or things that look like blocks)
2109 * printed on a page are given a unique number that can be used to construct
2110 * id="" attributes. This is set automatically be the {@link prepare()} method.
2111 * Do not try to set it manually.
2116 * @var integer If this is the contents of a real block, this should be set to
2117 * the block_instance.id. Otherwise this should be set to 0.
2119 public $blockinstanceid = 0;
2122 * @var integer if this is a real block instance, and there is a corresponding
2123 * block_position.id for the block on this page, this should be set to that id.
2124 * Otherwise it should be 0.
2126 public $blockpositionid = 0;
2129 * @param array $attributes an array of attribute => value pairs that are put on the
2130 * outer div of this block. {@link $id} and {@link $classes} attributes should be set separately.
2135 * @param string $title The title of this block. If this came from user input,
2136 * it should already have had format_string() processing done on it. This will
2137 * be output inside <h2> tags. Please do not cause invalid XHTML.
2142 * @param string $content HTML for the content
2144 public $content = '';
2147 * @param array $list an alternative to $content, it you want a list of things with optional icons.
2149 public $footer = '';
2152 * Any small print that should appear under the block to explain to the
2153 * teacher about the block, for example 'This is a sticky block that was
2154 * added in the system context.'
2157 public $annotation = '';
2160 * @var integer one of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2161 * the user can toggle whether this block is visible.
2163 public $collapsible = self::NOT_HIDEABLE;
2166 * A (possibly empty) array of editing controls. Each element of this array
2167 * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2168 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2171 public $controls = array();
2175 * Create new instance of block content
2176 * @param array $attributes
2178 public function __construct(array $attributes=null) {
2179 $this->skipid = self::$idcounter;
2180 self::$idcounter += 1;
2184 $this->attributes = $attributes;
2186 // simple "fake" blocks used in some modules and "Add new block" block
2187 $this->attributes = array('class'=>'block');
2192 * Add html class to block
2193 * @param string $class
2196 public function add_class($class) {
2197 $this->attributes['class'] .= ' '.$class;
2203 * This class represents a target for where a block can go when it is being moved.
2205 * This needs to be rendered as a form with the given hidden from fields, and
2206 * clicking anywhere in the form should submit it. The form action should be
2209 * @copyright 2009 Tim Hunt
2210 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2213 class block_move_target {
2227 * @param string $text
2228 * @param moodle_url $url
2230 public function __construct($text, moodle_url $url) {
2231 $this->text = $text;
2239 * This class is used to represent one item within a custom menu that may or may
2240 * not have children.
2242 * @copyright 2010 Sam Hemelryk
2243 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2246 class custom_menu_item implements renderable {
2248 * The text to show for the item
2253 * The link to give the icon if it has no children
2258 * A title to apply to the item. By default the text
2263 * A sort order for the item, not necessary if you order things in the CFG var
2268 * A reference to the parent for this item or NULL if it is a top level item
2269 * @var custom_menu_item
2273 * A array in which to store children this item has.
2276 protected $children = array();
2278 * A reference to the sort var of the last child that was added
2281 protected $lastsort = 0;
2283 * Constructs the new custom menu item
2285 * @param string $text
2286 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2287 * @param string $title A title to apply to this item [Optional]
2288 * @param int $sort A sort or to use if we need to sort differently [Optional]
2289 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2290 * belongs to, only if the child has a parent. [Optional]
2292 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent=null) {
2293 $this->text = $text;
2295 $this->title = $title;
2296 $this->sort = (int)$sort;
2297 $this->parent = $parent;
2301 * Adds a custom menu item as a child of this node given its properties.
2303 * @param string $text
2304 * @param moodle_url $url
2305 * @param string $title
2307 * @return custom_menu_item
2309 public function add($text, moodle_url $url=null, $title=null, $sort = null) {
2310 $key = count($this->children);
2312 $sort = $this->lastsort + 1;
2314 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2315 $this->lastsort = (int)$sort;
2316 return $this->children[$key];
2319 * Returns the text for this item
2322 public function get_text() {
2326 * Returns the url for this item
2327 * @return moodle_url
2329 public function get_url() {
2333 * Returns the title for this item
2336 public function get_title() {
2337 return $this->title;
2340 * Sorts and returns the children for this item
2343 public function get_children() {
2345 return $this->children;
2348 * Gets the sort order for this child
2351 public function get_sort_order() {
2355 * Gets the parent this child belong to
2356 * @return custom_menu_item
2358 public function get_parent() {
2359 return $this->parent;
2362 * Sorts the children this item has
2364 public function sort() {
2365 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2368 * Returns true if this item has any children
2371 public function has_children() {
2372 return (count($this->children) > 0);
2376 * Sets the text for the node
2377 * @param string $text
2379 public function set_text($text) {
2380 $this->text = (string)$text;
2384 * Sets the title for the node
2385 * @param string $title
2387 public function set_title($title) {
2388 $this->title = (string)$title;
2392 * Sets the url for the node
2393 * @param moodle_url $url
2395 public function set_url(moodle_url $url) {
2403 * This class is used to operate a custom menu that can be rendered for the page.
2404 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2405 * of custom_menu_item nodes that can be rendered by the core renderer.
2407 * To configure the custom menu:
2408 * Settings: Administration > Appearance > Themes > Theme settings
2410 * @copyright 2010 Sam Hemelryk
2411 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2414 class custom_menu extends custom_menu_item {
2416 /** @var string the language we should render for, null disables multilang support */
2417 protected $currentlanguage = null;
2420 * Creates the custom menu
2422 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2423 * @param string $language the current language code, null disables multilang support
2425 public function __construct($definition = '', $currentlanguage = null) {
2427 $this->currentlanguage = $currentlanguage;
2428 parent::__construct('root'); // create virtual root element of the menu
2429 if (!empty($definition)) {
2430 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2435 * Overrides the children of this custom menu. Useful when getting children
2436 * from $CFG->custommenuitems
2438 public function override_children(array $children) {
2439 $this->children = array();
2440 foreach ($children as $child) {
2441 if ($child instanceof custom_menu_item) {
2442 $this->children[] = $child;
2448 * Converts a string into a structured array of custom_menu_items which can
2449 * then be added to a custom menu.
2452 * text|url|title|langs
2453 * The number of hyphens at the start determines the depth of the item. The
2454 * languages are optional, comma separated list of languages the line is for.
2456 * Example structure:
2457 * First level first item|http://www.moodle.com/
2458 * -Second level first item|http://www.moodle.com/partners/
2459 * -Second level second item|http://www.moodle.com/hq/
2460 * --Third level first item|http://www.moodle.com/jobs/
2461 * -Second level third item|http://www.moodle.com/development/
2462 * First level second item|http://www.moodle.com/feedback/
2463 * First level third item
2464 * English only|http://moodle.com|English only item|en
2465 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2469 * @param string $text the menu items definition
2470 * @param string $language the language code, null disables multilang support
2473 public static function convert_text_to_menu_nodes($text, $language = null) {
2474 $lines = explode("\n", $text);
2475 $children = array();
2479 foreach ($lines as $line) {
2480 $line = trim($line);
2481 $bits = explode('|', $line, 4); // name|url|title|langs
2482 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2483 // Every item must have a name to be valid
2486 $bits[0] = ltrim($bits[0],'-');
2488 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2489 // Set the url to null
2492 // Make sure the url is a moodle url
2493 $bits[1] = new moodle_url(trim($bits[1]));
2495 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2496 // Set the title to null seeing as there isn't one
2497 $bits[2] = $bits[0];
2499 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2500 // The item is valid for all languages
2503 $itemlangs = array_map('trim', explode(',', $bits[3]));
2505 if (!empty($language) and !empty($itemlangs)) {
2506 // check that the item is intended for the current language
2507 if (!in_array($language, $itemlangs)) {
2511 // Set an incremental sort order to keep it simple.
2513 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2514 $depth = strlen($match[1]);
2515 if ($depth < $lastdepth) {
2516 $difference = $lastdepth - $depth;
2517 if ($lastdepth > 1 && $lastdepth != $difference) {
2518 $tempchild = $lastchild->get_parent();
2519 for ($i =0; $i < $difference; $i++) {
2520 $tempchild = $tempchild->get_parent();
2522 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2525 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2526 $children[] = $lastchild;
2528 } else if ($depth > $lastdepth) {
2529 $depth = $lastdepth + 1;
2530 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2533 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2534 $children[] = $lastchild;
2536 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2541 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2542 $children[] = $lastchild;
2544 $lastdepth = $depth;
2550 * Sorts two custom menu items
2552 * This function is designed to be used with the usort method
2553 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2555 * @param custom_menu_item $itema
2556 * @param custom_menu_item $itemb
2559 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2560 $itema = $itema->get_sort_order();
2561 $itemb = $itemb->get_sort_order();
2562 if ($itema == $itemb) {
2565 return ($itema > $itemb) ? +1 : -1;