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(),
61 foreach ($defaults as $key=>$value) {
62 if (empty($options->$key)) {
63 $options->$key = $value;
67 $options->currentfile = '';
68 if (!empty($options->itemid)) {
69 $fs = get_file_storage();
70 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
71 if (empty($options->filename)) {
72 if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
73 $file = reset($files);
76 $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
79 $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
83 // initilise options, getting files in root path
84 $this->options = initialise_filepicker($options);
86 // copying other options
87 foreach ($options as $name=>$value) {
88 if (!isset($this->options->$name)) {
89 $this->options->$name = $value;
96 * Data structure representing a user picture.
98 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
99 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
102 class user_picture implements renderable {
104 * @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)
106 protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'imagealt', 'email');
109 * @var object $user A user object with at least fields all columns specified in $fields array constant set.
113 * @var int $courseid The course id. Used when constructing the link to the user's profile,
114 * page course id used if not specified.
118 * @var bool $link add course profile link to image
122 * @var int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility
126 * @var boolean $alttext add non-blank alt-text to the image.
127 * Default true, set to false when image alt just duplicates text in screenreaders.
129 public $alttext = true;
131 * @var boolean $popup Whether or not to open the link in a popup window.
133 public $popup = false;
135 * @var string Image class attribute
137 public $class = 'userpicture';
140 * User picture constructor.
142 * @param object $user user record with at least id, picture, imagealt, firstname and lastname set.
143 * @param array $options such as link, size, link, ...
145 public function __construct(stdClass $user) {
148 if (empty($user->id)) {
149 throw new coding_exception('User id is required when printing user avatar image.');
152 // only touch the DB if we are missing data and complain loudly...
154 foreach (self::$fields as $field) {
155 if (!array_key_exists($field, $user)) {
157 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
158 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
164 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
166 $this->user = clone($user);
171 * Returns a list of required user fields, useful when fetching required user info from db.
173 * In some cases we have to fetch the user data together with some other information,
174 * the idalias is useful there because the id would otherwise override the main
175 * id of the result record. Please note it has to be converted back to id before rendering.
177 * @param string $tableprefix name of database table prefix in query
178 * @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)
179 * @param string $idalias alias of id field
182 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id') {
183 if (!$tableprefix and !$extrafields and !$idalias) {
184 return implode(',', self::$fields);
190 foreach (self::$fields as $field) {
191 if ($field === 'id' and $idalias and $idalias !== 'id') {
192 $fields[$field] = "$tableprefix$field AS $idalias";
194 $fields[$field] = $tableprefix.$field;
197 // add extra fields if not already there
199 foreach ($extrafields as $e) {
200 if ($e === 'id' or isset($fields[$e])) {
203 $fields[$e] = $tableprefix.$e;
206 return implode(',', $fields);
212 * Data structure representing a help icon.
214 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
215 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
218 class old_help_icon implements renderable {
220 * @var string $helpidentifier lang pack identifier
222 public $helpidentifier;
224 * @var string $title A descriptive text for title tooltip
226 public $title = null;
228 * @var string $component Component name, the same as in get_string()
230 public $component = 'moodle';
232 * @var string $linktext Extra descriptive text next to the icon
234 public $linktext = null;
237 * Constructor: sets up the other components in case they are needed
238 * @param string $helpidentifier The keyword that defines a help page
239 * @param string $title A descriptive text for accessibility only
240 * @param string $component
241 * @param bool $linktext add extra text to icon
244 public function __construct($helpidentifier, $title, $component = 'moodle') {
246 throw new coding_exception('A help_icon object requires a $text parameter');
248 if (empty($helpidentifier)) {
249 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
252 $this->helpidentifier = $helpidentifier;
253 $this->title = $title;
254 $this->component = $component;
259 * Data structure representing a help icon.
261 * @copyright 2010 Petr Skoda (info@skodak.org)
262 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
265 class help_icon implements renderable {
267 * @var string $identifier lang pack identifier (without the "_help" suffix),
268 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
273 * @var string $component Component name, the same as in get_string()
277 * @var string $linktext Extra descriptive text next to the icon
279 public $linktext = null;
283 * @param string $identifier string for help page title,
284 * string with _help suffix is used for the actual help text.
285 * string with _link suffix is used to create a link to further info (if it exists)
286 * @param string $component
288 public function __construct($identifier, $component) {
289 $this->identifier = $identifier;
290 $this->component = $component;
294 * Verifies that both help strings exists, shows debug warnings if not
296 public function diag_strings() {
297 $sm = get_string_manager();
298 if (!$sm->string_exists($this->identifier, $this->component)) {
299 debugging("Help title string does not exist: [$this->identifier, $this->component]");
301 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
302 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
309 * Data structure representing an icon.
311 * @copyright 2010 Petr Skoda
312 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
315 class pix_icon implements renderable {
318 var $attributes = array();
322 * @param string $pix short icon name
323 * @param string $component component name
324 * @param array $attributes html attributes
326 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
328 $this->component = $component;
329 $this->attributes = (array)$attributes;
331 $this->attributes['alt'] = $alt;
332 if (empty($this->attributes['class'])) {
333 $this->attributes['class'] = 'smallicon';
335 if (!isset($this->attributes['title'])) {
336 $this->attributes['title'] = $this->attributes['alt'];
342 * Data structure representing an emoticon image
346 class pix_emoticon extends pix_icon implements renderable {
350 * @param string $pix short icon name
351 * @param string $alt alternative text
352 * @param string $component emoticon image provider
353 * @param array $attributes explicit HTML attributes
355 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
356 if (empty($attributes['class'])) {
357 $attributes['class'] = 'emoticon';
359 parent::__construct($pix, $alt, $component, $attributes);
364 * Data structure representing a simple form with only one button.
366 * @copyright 2009 Petr Skoda
367 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
370 class single_button implements renderable {
383 * @var string post or get
385 var $method = 'post';
390 var $class = 'singlebutton';
392 * True if button disabled, false if normal
395 var $disabled = false;
407 * List of attached actions
408 * @var array of component_action
410 var $actions = array();
414 * @param string|moodle_url $url
415 * @param string $label button text
416 * @param string $method get or post submit method
418 public function __construct(moodle_url $url, $label, $method='post') {
419 $this->url = clone($url);
420 $this->label = $label;
421 $this->method = $method;
425 * Shortcut for adding a JS confirm dialog when the button is clicked.
426 * The message must be a yes/no question.
427 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
430 public function add_confirm_action($confirmmessage) {
431 $this->add_action(new component_action('click', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
435 * Add action to the button.
436 * @param component_action $action
439 public function add_action(component_action $action) {
440 $this->actions[] = $action;
446 * Simple form with just one select field that gets submitted automatically.
447 * If JS not enabled small go button is printed too.
449 * @copyright 2009 Petr Skoda
450 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
453 class single_select implements renderable {
455 * Target url - includes hidden fields
460 * Name of the select element.
465 * @var array $options associative array value=>label ex.:
466 * array(1=>'One, 2=>Two)
467 * it is also possible to specify optgroup as complex label array ex.:
468 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
469 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
483 * Extra select field attributes
486 var $attributes = array();
494 * @var string post or get
501 var $class = 'singleselect';
503 * True if button disabled, false if normal
506 var $disabled = false;
518 * List of attached actions
519 * @var array of component_action
521 var $helpicon = null;
524 * @param moodle_url $url form action target, includes hidden fields
525 * @param string $name name of selection field - the changing parameter in url
526 * @param array $options list of options
527 * @param string $selected selected element
528 * @param array $nothing
529 * @param string $formid
531 public function __construct(moodle_url $url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
534 $this->options = $options;
535 $this->selected = $selected;
536 $this->nothing = $nothing;
537 $this->formid = $formid;
541 * Shortcut for adding a JS confirm dialog when the button is clicked.
542 * The message must be a yes/no question.
543 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
546 public function add_confirm_action($confirmmessage) {
547 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
551 * Add action to the button.
552 * @param component_action $action
555 public function add_action(component_action $action) {
556 $this->actions[] = $action;
561 * @param string $page The keyword that defines a help page
562 * @param string $title A descriptive text for accessibility only
563 * @param string $component
564 * @param bool $linktext add extra text to icon
567 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
568 $this->helpicon = new old_help_icon($helppage, $title, $component);
573 * @param string $identifier The keyword that defines a help page
574 * @param string $component
575 * @param bool $linktext add extra text to icon
578 public function set_help_icon($identifier, $component = 'moodle') {
579 $this->helpicon = new help_icon($identifier, $component);
583 * Sets select's label
584 * @param string $label
587 public function set_label($label) {
588 $this->label = $label;
594 * Simple URL selection widget description.
595 * @copyright 2009 Petr Skoda
596 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
599 class url_select implements renderable {
601 * @var array $urls associative array value=>label ex.:
602 * array(1=>'One, 2=>Two)
603 * it is also possible to specify optgroup as complex label array ex.:
604 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
605 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
619 * Extra select field attributes
622 var $attributes = array();
632 var $class = 'urlselect';
634 * True if button disabled, false if normal
637 var $disabled = false;
649 * List of attached actions
650 * @var array of component_action
652 var $helpicon = null;
654 * @var string If set, makes button visible with given name for button
656 var $showbutton = null;
659 * @param array $urls list of options
660 * @param string $selected selected element
661 * @param array $nothing
662 * @param string $formid
663 * @param string $showbutton Set to text of button if it should be visible
664 * or null if it should be hidden (hidden version always has text 'go')
666 public function __construct(array $urls, $selected='', $nothing=array(''=>'choosedots'),
667 $formid=null, $showbutton=null) {
669 $this->selected = $selected;
670 $this->nothing = $nothing;
671 $this->formid = $formid;
672 $this->showbutton = $showbutton;
677 * @param string $page The keyword that defines a help page
678 * @param string $title A descriptive text for accessibility only
679 * @param string $component
680 * @param bool $linktext add extra text to icon
683 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
684 $this->helpicon = new old_help_icon($helppage, $title, $component);
689 * @param string $identifier The keyword that defines a help page
690 * @param string $component
691 * @param bool $linktext add extra text to icon
694 public function set_help_icon($identifier, $component = 'moodle') {
695 $this->helpicon = new help_icon($identifier, $component);
699 * Sets select's label
700 * @param string $label
703 public function set_label($label) {
704 $this->label = $label;
710 * Data structure describing html link with special action attached.
711 * @copyright 2010 Petr Skoda
712 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
715 class action_link implements renderable {
723 * @var string HTML fragment
732 * List of actions attached to link
733 * @var array of component_action
739 * @param string|moodle_url $url
740 * @param string $text HTML fragment
741 * @param component_action $action
742 * @param array $attributes associative array of html link attributes + disabled
744 public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null) {
745 $this->url = clone($url);
747 $this->attributes = (array)$attributes;
749 $this->add_action($action);
754 * Add action to the link.
755 * @param component_action $action
758 public function add_action(component_action $action) {
759 $this->actions[] = $action;
762 public function add_class($class) {
763 if (empty($this->attributes['class'])) {
764 $this->attributes['class'] = $class;
766 $this->attributes['class'] .= ' ' . $class;
771 // ==== HTML writer and helper classes, will be probably moved elsewhere ======
774 * Simple html output class
775 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
779 * Outputs a tag with attributes and contents
780 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
781 * @param string $contents What goes between the opening and closing tags
782 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
783 * @return string HTML fragment
785 public static function tag($tagname, $contents, array $attributes = null) {
786 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
790 * Outputs an opening tag with attributes
791 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
792 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
793 * @return string HTML fragment
795 public static function start_tag($tagname, array $attributes = null) {
796 return '<' . $tagname . self::attributes($attributes) . '>';
800 * Outputs a closing tag
801 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
802 * @return string HTML fragment
804 public static function end_tag($tagname) {
805 return '</' . $tagname . '>';
809 * Outputs an empty tag with attributes
810 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
811 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
812 * @return string HTML fragment
814 public static function empty_tag($tagname, array $attributes = null) {
815 return '<' . $tagname . self::attributes($attributes) . ' />';
819 * Outputs a tag, but only if the contents are not empty
820 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
821 * @param string $contents What goes between the opening and closing tags
822 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
823 * @return string HTML fragment
825 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
826 if ($contents === '' || is_null($contents)) {
829 return self::tag($tagname, $contents, $attributes);
833 * Outputs a HTML attribute and value
834 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
835 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
836 * @return string HTML fragment
838 public static function attribute($name, $value) {
839 if (is_array($value)) {
840 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
842 if ($value instanceof moodle_url) {
843 return ' ' . $name . '="' . $value->out() . '"';
846 // special case, we do not want these in output
847 if ($value === null) {
851 // no sloppy trimming here!
852 return ' ' . $name . '="' . s($value) . '"';
856 * Outputs a list of HTML attributes and values
857 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
858 * The values will be escaped with {@link s()}
859 * @return string HTML fragment
861 public static function attributes(array $attributes = null) {
862 $attributes = (array)$attributes;
864 foreach ($attributes as $name => $value) {
865 $output .= self::attribute($name, $value);
871 * Generates random html element id.
872 * @param string $base
875 public static function random_id($base='random') {
876 return uniqid($base);
880 * Generates a simple html link
881 * @param string|moodle_url $url
882 * @param string $text link txt
883 * @param array $attributes extra html attributes
884 * @return string HTML fragment
886 public static function link($url, $text, array $attributes = null) {
887 $attributes = (array)$attributes;
888 $attributes['href'] = $url;
889 return self::tag('a', $text, $attributes);
893 * generates a simple checkbox with optional label
894 * @param string $name
895 * @param string $value
896 * @param bool $checked
897 * @param string $label
898 * @param array $attributes
899 * @return string html fragment
901 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
902 $attributes = (array)$attributes;
905 if ($label !== '' and !is_null($label)) {
906 if (empty($attributes['id'])) {
907 $attributes['id'] = self::random_id('checkbox_');
910 $attributes['type'] = 'checkbox';
911 $attributes['value'] = $value;
912 $attributes['name'] = $name;
913 $attributes['checked'] = $checked ? 'checked' : null;
915 $output .= self::empty_tag('input', $attributes);
917 if ($label !== '' and !is_null($label)) {
918 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
925 * Generates a simple select yes/no form field
926 * @param string $name name of select element
927 * @param bool $selected
928 * @param array $attributes - html select element attributes
929 * @return string HRML fragment
931 public static function select_yes_no($name, $selected=true, array $attributes = null) {
932 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
933 return self::select($options, $name, $selected, null, $attributes);
937 * Generates a simple select form field
938 * @param array $options associative array value=>label ex.:
939 * array(1=>'One, 2=>Two)
940 * it is also possible to specify optgroup as complex label array ex.:
941 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
942 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
943 * @param string $name name of select element
944 * @param string|array $selected value or array of values depending on multiple attribute
945 * @param array|bool $nothing, add nothing selected option, or false of not added
946 * @param array $attributes - html select element attributes
947 * @return string HTML fragment
949 public static function select(array $options, $name, $selected = '', $nothing = array(''=>'choosedots'), array $attributes = null) {
950 $attributes = (array)$attributes;
951 if (is_array($nothing)) {
952 foreach ($nothing as $k=>$v) {
953 if ($v === 'choose' or $v === 'choosedots') {
954 $nothing[$k] = get_string('choosedots');
957 $options = $nothing + $options; // keep keys, do not override
959 } else if (is_string($nothing) and $nothing !== '') {
961 $options = array(''=>$nothing) + $options;
964 // we may accept more values if multiple attribute specified
965 $selected = (array)$selected;
966 foreach ($selected as $k=>$v) {
967 $selected[$k] = (string)$v;
970 if (!isset($attributes['id'])) {
972 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
973 $id = str_replace('[', '', $id);
974 $id = str_replace(']', '', $id);
975 $attributes['id'] = $id;
978 if (!isset($attributes['class'])) {
979 $class = 'menu'.$name;
980 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
981 $class = str_replace('[', '', $class);
982 $class = str_replace(']', '', $class);
983 $attributes['class'] = $class;
985 $attributes['class'] = 'select ' . $attributes['class']; /// Add 'select' selector always
987 $attributes['name'] = $name;
990 foreach ($options as $value=>$label) {
991 if (is_array($label)) {
992 // ignore key, it just has to be unique
993 $output .= self::select_optgroup(key($label), current($label), $selected);
995 $output .= self::select_option($label, $value, $selected);
998 return self::tag('select', $output, $attributes);
1001 private static function select_option($label, $value, array $selected) {
1002 $attributes = array();
1003 $value = (string)$value;
1004 if (in_array($value, $selected, true)) {
1005 $attributes['selected'] = 'selected';
1007 $attributes['value'] = $value;
1008 return self::tag('option', $label, $attributes);
1011 private static function select_optgroup($groupname, $options, array $selected) {
1012 if (empty($options)) {
1015 $attributes = array('label'=>$groupname);
1017 foreach ($options as $value=>$label) {
1018 $output .= self::select_option($label, $value, $selected);
1020 return self::tag('optgroup', $output, $attributes);
1024 * This is a shortcut for making an hour selector menu.
1025 * @param string $type The type of selector (years, months, days, hours, minutes)
1026 * @param string $name fieldname
1027 * @param int $currenttime A default timestamp in GMT
1028 * @param int $step minute spacing
1029 * @param array $attributes - html select element attributes
1030 * @return HTML fragment
1032 public static function select_time($type, $name, $currenttime=0, $step=5, array $attributes=null) {
1033 if (!$currenttime) {
1034 $currenttime = time();
1036 $currentdate = usergetdate($currenttime);
1037 $userdatetype = $type;
1038 $timeunits = array();
1042 for ($i=1970; $i<=2020; $i++) {
1043 $timeunits[$i] = $i;
1045 $userdatetype = 'year';
1048 for ($i=1; $i<=12; $i++) {
1049 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1051 $userdatetype = 'month';
1052 $currentdate['month'] = $currentdate['mon'];
1055 for ($i=1; $i<=31; $i++) {
1056 $timeunits[$i] = $i;
1058 $userdatetype = 'mday';
1061 for ($i=0; $i<=23; $i++) {
1062 $timeunits[$i] = sprintf("%02d",$i);
1067 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1070 for ($i=0; $i<=59; $i+=$step) {
1071 $timeunits[$i] = sprintf("%02d",$i);
1075 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1078 if (empty($attributes['id'])) {
1079 $attributes['id'] = self::random_id('ts_');
1081 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1082 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1084 return $label.$timerselector;
1088 * Shortcut for quick making of lists
1089 * @param array $items
1090 * @param string $tag ul or ol
1091 * @param array $attributes
1094 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1095 //note: 'list' is a reserved keyword ;-)
1099 foreach ($items as $item) {
1100 $output .= html_writer::start_tag('li') . "\n";
1101 $output .= $item . "\n";
1102 $output .= html_writer::end_tag('li') . "\n";
1105 return html_writer::tag($tag, $output, $attributes);
1109 * Returns hidden input fields created from url parameters.
1110 * @param moodle_url $url
1111 * @param array $exclude list of excluded parameters
1112 * @return string HTML fragment
1114 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1115 $exclude = (array)$exclude;
1116 $params = $url->params();
1117 foreach ($exclude as $key) {
1118 unset($params[$key]);
1122 foreach ($params as $key => $value) {
1123 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1124 $output .= self::empty_tag('input', $attributes)."\n";
1130 * Generate a script tag containing the the specified code.
1132 * @param string $js the JavaScript code
1133 * @param moodle_url|string optional url of the external script, $code ignored if specified
1134 * @return string HTML, the code wrapped in <script> tags.
1136 public static function script($jscode, $url=null) {
1138 $attributes = array('type'=>'text/javascript');
1139 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1142 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1143 return self::tag('script', '', $attributes) . "\n";
1151 * Renders HTML table
1153 * This method may modify the passed instance by adding some default properties if they are not set yet.
1154 * If this is not what you want, you should make a full clone of your data before passing them to this
1155 * method. In most cases this is not an issue at all so we do not clone by default for performance
1156 * and memory consumption reasons.
1158 * @param html_table $table data to be rendered
1159 * @return string HTML code
1161 public static function table(html_table $table) {
1162 // prepare table data and populate missing properties with reasonable defaults
1163 if (!empty($table->align)) {
1164 foreach ($table->align as $key => $aa) {
1166 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1168 $table->align[$key] = null;
1172 if (!empty($table->size)) {
1173 foreach ($table->size as $key => $ss) {
1175 $table->size[$key] = 'width:'. $ss .';';
1177 $table->size[$key] = null;
1181 if (!empty($table->wrap)) {
1182 foreach ($table->wrap as $key => $ww) {
1184 $table->wrap[$key] = 'white-space:nowrap;';
1186 $table->wrap[$key] = '';
1190 if (!empty($table->head)) {
1191 foreach ($table->head as $key => $val) {
1192 if (!isset($table->align[$key])) {
1193 $table->align[$key] = null;
1195 if (!isset($table->size[$key])) {
1196 $table->size[$key] = null;
1198 if (!isset($table->wrap[$key])) {
1199 $table->wrap[$key] = null;
1204 if (empty($table->attributes['class'])) {
1205 $table->attributes['class'] = 'generaltable';
1207 if (!empty($table->tablealign)) {
1208 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1211 // explicitly assigned properties override those defined via $table->attributes
1212 $table->attributes['class'] = trim($table->attributes['class']);
1213 $attributes = array_merge($table->attributes, array(
1215 'width' => $table->width,
1216 'summary' => $table->summary,
1217 'cellpadding' => $table->cellpadding,
1218 'cellspacing' => $table->cellspacing,
1220 $output = html_writer::start_tag('table', $attributes) . "\n";
1224 if (!empty($table->head)) {
1225 $countcols = count($table->head);
1227 $output .= html_writer::start_tag('thead', array()) . "\n";
1228 $output .= html_writer::start_tag('tr', array()) . "\n";
1229 $keys = array_keys($table->head);
1230 $lastkey = end($keys);
1232 foreach ($table->head as $key => $heading) {
1233 // Convert plain string headings into html_table_cell objects
1234 if (!($heading instanceof html_table_cell)) {
1235 $headingtext = $heading;
1236 $heading = new html_table_cell();
1237 $heading->text = $headingtext;
1238 $heading->header = true;
1241 if ($heading->header !== false) {
1242 $heading->header = true;
1245 if ($heading->header && empty($heading->scope)) {
1246 $heading->scope = 'col';
1249 $heading->attributes['class'] .= ' header c' . $key;
1250 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1251 $heading->colspan = $table->headspan[$key];
1252 $countcols += $table->headspan[$key] - 1;
1255 if ($key == $lastkey) {
1256 $heading->attributes['class'] .= ' lastcol';
1258 if (isset($table->colclasses[$key])) {
1259 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1261 $heading->attributes['class'] = trim($heading->attributes['class']);
1262 $attributes = array_merge($heading->attributes, array(
1263 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1264 'scope' => $heading->scope,
1265 'colspan' => $heading->colspan,
1269 if ($heading->header === true) {
1272 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1274 $output .= html_writer::end_tag('tr') . "\n";
1275 $output .= html_writer::end_tag('thead') . "\n";
1277 if (empty($table->data)) {
1278 // For valid XHTML strict every table must contain either a valid tr
1279 // or a valid tbody... both of which must contain a valid td
1280 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1281 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1282 $output .= html_writer::end_tag('tbody');
1286 if (!empty($table->data)) {
1288 $keys = array_keys($table->data);
1289 $lastrowkey = end($keys);
1290 $output .= html_writer::start_tag('tbody', array());
1292 foreach ($table->data as $key => $row) {
1293 if (($row === 'hr') && ($countcols)) {
1294 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1296 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1297 if (!($row instanceof html_table_row)) {
1298 $newrow = new html_table_row();
1300 foreach ($row as $item) {
1301 $cell = new html_table_cell();
1302 $cell->text = $item;
1303 $newrow->cells[] = $cell;
1308 $oddeven = $oddeven ? 0 : 1;
1309 if (isset($table->rowclasses[$key])) {
1310 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1313 $row->attributes['class'] .= ' r' . $oddeven;
1314 if ($key == $lastrowkey) {
1315 $row->attributes['class'] .= ' lastrow';
1318 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1319 $keys2 = array_keys($row->cells);
1320 $lastkey = end($keys2);
1322 $gotlastkey = false; //flag for sanity checking
1323 foreach ($row->cells as $key => $cell) {
1325 //This should never happen. Why do we have a cell after the last cell?
1326 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1329 if (!($cell instanceof html_table_cell)) {
1330 $mycell = new html_table_cell();
1331 $mycell->text = $cell;
1335 if (($cell->header === true) && empty($cell->scope)) {
1336 $cell->scope = 'row';
1339 if (isset($table->colclasses[$key])) {
1340 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1343 $cell->attributes['class'] .= ' cell c' . $key;
1344 if ($key == $lastkey) {
1345 $cell->attributes['class'] .= ' lastcol';
1349 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1350 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1351 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1352 $cell->attributes['class'] = trim($cell->attributes['class']);
1353 $tdattributes = array_merge($cell->attributes, array(
1354 'style' => $tdstyle . $cell->style,
1355 'colspan' => $cell->colspan,
1356 'rowspan' => $cell->rowspan,
1358 'abbr' => $cell->abbr,
1359 'scope' => $cell->scope,
1362 if ($cell->header === true) {
1365 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1368 $output .= html_writer::end_tag('tr') . "\n";
1370 $output .= html_writer::end_tag('tbody') . "\n";
1372 $output .= html_writer::end_tag('table') . "\n";
1378 * Renders form element label
1380 * By default, the label is suffixed with a label separator defined in the
1381 * current language pack (colon by default in the English lang pack).
1382 * Adding the colon can be explicitly disabled if needed. Label separators
1383 * are put outside the label tag itself so they are not read by
1384 * screenreaders (accessibility).
1386 * Parameter $for explicitly associates the label with a form control. When
1387 * set, the value of this attribute must be the same as the value of
1388 * the id attribute of the form control in the same document. When null,
1389 * the label being defined is associated with the control inside the label
1392 * @param string $text content of the label tag
1393 * @param string|null $for id of the element this label is associated with, null for no association
1394 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1395 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1396 * @return string HTML of the label element
1398 public static function label($text, $for, $colonize=true, array $attributes=array()) {
1399 if (!is_null($for)) {
1400 $attributes = array_merge($attributes, array('for' => $for));
1402 $text = trim($text);
1403 $label = self::tag('label', $text, $attributes);
1406 // TODO $colonize disabled for now yet - see MDL-12192 for details
1407 if (!empty($text) and $colonize) {
1408 // the $text may end with the colon already, though it is bad string definition style
1409 $colon = get_string('labelsep', 'langconfig');
1410 if (!empty($colon)) {
1411 $trimmed = trim($colon);
1412 if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1413 //debugging('The label text should not end with colon or other label separator,
1414 // please fix the string definition.', DEBUG_DEVELOPER);
1426 // ==== JS writer and helper classes, will be probably moved elsewhere ======
1429 * Simple javascript output class
1430 * @copyright 2010 Petr Skoda
1434 * Returns javascript code calling the function
1435 * @param string $function function name, can be complex like Y.Event.purgeElement
1436 * @param array $arguments parameters
1437 * @param int $delay execution delay in seconds
1438 * @return string JS code fragment
1440 public static function function_call($function, array $arguments = null, $delay=0) {
1442 $arguments = array_map('json_encode', $arguments);
1443 $arguments = implode(', ', $arguments);
1447 $js = "$function($arguments);";
1450 $delay = $delay * 1000; // in miliseconds
1451 $js = "setTimeout(function() { $js }, $delay);";
1457 * Special function which adds Y as first argument of fucntion call.
1458 * @param string $function
1459 * @param array $extraarguments
1462 public static function function_call_with_Y($function, array $extraarguments = null) {
1463 if ($extraarguments) {
1464 $extraarguments = array_map('json_encode', $extraarguments);
1465 $arguments = 'Y, ' . implode(', ', $extraarguments);
1469 return "$function($arguments);\n";
1473 * Returns JavaScript code to initialise a new object
1474 * @param string|null $var If it is null then no var is assigned the new object
1475 * @param string $class
1476 * @param array $arguments
1477 * @param array $requirements
1481 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1482 if (is_array($arguments)) {
1483 $arguments = array_map('json_encode', $arguments);
1484 $arguments = implode(', ', $arguments);
1487 if ($var === null) {
1488 $js = "new $class(Y, $arguments);";
1489 } else if (strpos($var, '.')!==false) {
1490 $js = "$var = new $class(Y, $arguments);";
1492 $js = "var $var = new $class(Y, $arguments);";
1496 $delay = $delay * 1000; // in miliseconds
1497 $js = "setTimeout(function() { $js }, $delay);";
1500 if (count($requirements) > 0) {
1501 $requirements = implode("', '", $requirements);
1502 $js = "Y.use('$requirements', function(Y){ $js });";
1508 * Returns code setting value to variable
1509 * @param string $name
1510 * @param mixed $value json serialised value
1511 * @param bool $usevar add var definition, ignored for nested properties
1512 * @return string JS code fragment
1514 public static function set_variable($name, $value, $usevar=true) {
1518 if (strpos($name, '.')) {
1525 $output .= "$name = ".json_encode($value).";";
1531 * Writes event handler attaching code
1532 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1533 * @param string $event A valid DOM event (click, mousedown, change etc.)
1534 * @param string $function The name of the function to call
1535 * @param array $arguments An optional array of argument parameters to pass to the function
1536 * @return string JS code fragment
1538 public static function event_handler($selector, $event, $function, array $arguments = null) {
1539 $selector = json_encode($selector);
1540 $output = "Y.on('$event', $function, $selector, null";
1541 if (!empty($arguments)) {
1542 $output .= ', ' . json_encode($arguments);
1544 return $output . ");\n";
1549 * Holds all the information required to render a <table> by {@see core_renderer::table()}
1552 * $t = new html_table();
1553 * ... // set various properties of the object $t as described below
1554 * echo html_writer::table($t);
1556 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1557 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1562 * @var string value to use for the id attribute of the table
1566 * @var array attributes of HTML attributes for the <table> element
1568 public $attributes = array();
1570 * For more control over the rendering of the headers, an array of html_table_cell objects
1571 * can be passed instead of an array of strings.
1572 * @var array of headings. The n-th array item is used as a heading of the n-th column.
1575 * $t->head = array('Student', 'Grade');
1579 * @var array can be used to make a heading span multiple columns
1582 * $t->headspan = array(2,1);
1584 * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
1585 * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
1589 * @var array of column alignments. The value is used as CSS 'text-align' property. Therefore, possible
1590 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1591 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1593 * Examples of usage:
1594 * $t->align = array(null, 'right');
1596 * $t->align[1] = 'right';
1601 * @var array of column sizes. The value is used as CSS 'size' property.
1603 * Examples of usage:
1604 * $t->size = array('50%', '50%');
1606 * $t->size[1] = '120px';
1610 * @var array of wrapping information. The only possible value is 'nowrap' that sets the
1611 * CSS property 'white-space' to the value 'nowrap' in the given column.
1614 * $t->wrap = array(null, 'nowrap');
1618 * @var array of arrays or html_table_row objects containing the data. Alternatively, if you have
1619 * $head specified, the string 'hr' (for horizontal ruler) can be used
1620 * instead of an array of cells data resulting in a divider rendered.
1622 * Example of usage with array of arrays:
1623 * $row1 = array('Harry Potter', '76 %');
1624 * $row2 = array('Hermione Granger', '100 %');
1625 * $t->data = array($row1, $row2);
1627 * Example with array of html_table_row objects: (used for more fine-grained control)
1628 * $cell1 = new html_table_cell();
1629 * $cell1->text = 'Harry Potter';
1630 * $cell1->colspan = 2;
1631 * $row1 = new html_table_row();
1632 * $row1->cells[] = $cell1;
1633 * $cell2 = new html_table_cell();
1634 * $cell2->text = 'Hermione Granger';
1635 * $cell3 = new html_table_cell();
1636 * $cell3->text = '100 %';
1637 * $row2 = new html_table_row();
1638 * $row2->cells = array($cell2, $cell3);
1639 * $t->data = array($row1, $row2);
1643 * @var string width of the table, percentage of the page preferred. Defaults to 80%
1644 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1646 public $width = null;
1648 * @var string alignment the whole table. Can be 'right', 'left' or 'center' (default).
1649 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1651 public $tablealign = null;
1653 * @var int padding on each cell, in pixels
1654 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1656 public $cellpadding = null;
1658 * @var int spacing between cells, in pixels
1659 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1661 public $cellspacing = null;
1663 * @var array classes to add to particular rows, space-separated string.
1664 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1665 * respectively. Class 'lastrow' is added automatically for the last row
1669 * $t->rowclasses[9] = 'tenth'
1673 * @var array classes to add to every cell in a particular column,
1674 * space-separated string. Class 'cell' is added automatically by the renderer.
1675 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1676 * respectively. Class 'lastcol' is added automatically for all last cells
1680 * $t->colclasses = array(null, 'grade');
1684 * @var string description of the contents for screen readers.
1691 public function __construct() {
1692 $this->attributes['class'] = '';
1698 * Component representing a table row.
1700 * @copyright 2009 Nicolas Connault
1701 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1704 class html_table_row {
1706 * @var string value to use for the id attribute of the row
1710 * @var array $cells Array of html_table_cell objects
1712 public $cells = array();
1714 * @var string $style value to use for the style attribute of the table row
1716 public $style = null;
1718 * @var array attributes of additional HTML attributes for the <tr> element
1720 public $attributes = array();
1724 * @param array $cells
1726 public function __construct(array $cells=null) {
1727 $this->attributes['class'] = '';
1728 $cells = (array)$cells;
1729 foreach ($cells as $cell) {
1730 if ($cell instanceof html_table_cell) {
1731 $this->cells[] = $cell;
1733 $this->cells[] = new html_table_cell($cell);
1741 * Component representing a table cell.
1743 * @copyright 2009 Nicolas Connault
1744 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1747 class html_table_cell {
1749 * @var string value to use for the id attribute of the cell
1753 * @var string $text The contents of the cell
1757 * @var string $abbr Abbreviated version of the contents of the cell
1759 public $abbr = null;
1761 * @var int $colspan Number of columns this cell should span
1763 public $colspan = null;
1765 * @var int $rowspan Number of rows this cell should span
1767 public $rowspan = null;
1769 * @var string $scope Defines a way to associate header cells and data cells in a table
1771 public $scope = null;
1773 * @var boolean $header Whether or not this cell is a header cell
1775 public $header = null;
1777 * @var string $style value to use for the style attribute of the table cell
1779 public $style = null;
1781 * @var array attributes of additional HTML attributes for the <td> element
1783 public $attributes = array();
1785 public function __construct($text = null) {
1786 $this->text = $text;
1787 $this->attributes['class'] = '';
1792 /// Complex components aggregating simpler components
1796 * Component representing a paging bar.
1798 * @copyright 2009 Nicolas Connault
1799 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1802 class paging_bar implements renderable {
1804 * @var int $maxdisplay The maximum number of pagelinks to display
1806 public $maxdisplay = 18;
1808 * @var int $totalcount post or get
1812 * @var int $page The page you are currently viewing
1816 * @var int $perpage The number of entries that should be shown per page
1820 * @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.
1821 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
1825 * @var string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
1829 * @var string $previouslink A HTML link representing the "previous" page
1831 public $previouslink = null;
1833 * @var tring $nextlink A HTML link representing the "next" page
1835 public $nextlink = null;
1837 * @var tring $firstlink A HTML link representing the first page
1839 public $firstlink = null;
1841 * @var tring $lastlink A HTML link representing the last page
1843 public $lastlink = null;
1845 * @var array $pagelinks An array of strings. One of them is just a string: the current page
1847 public $pagelinks = array();
1850 * Constructor paging_bar with only the required params.
1852 * @param int $totalcount The total number of entries available to be paged through
1853 * @param int $page The page you are currently viewing
1854 * @param int $perpage The number of entries that should be shown per page
1855 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
1856 * @param string $pagevar name of page parameter that holds the page number
1858 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
1859 $this->totalcount = $totalcount;
1860 $this->page = $page;
1861 $this->perpage = $perpage;
1862 $this->baseurl = $baseurl;
1863 $this->pagevar = $pagevar;
1869 public function prepare(renderer_base $output, moodle_page $page, $target) {
1870 if (!isset($this->totalcount) || is_null($this->totalcount)) {
1871 throw new coding_exception('paging_bar requires a totalcount value.');
1873 if (!isset($this->page) || is_null($this->page)) {
1874 throw new coding_exception('paging_bar requires a page value.');
1876 if (empty($this->perpage)) {
1877 throw new coding_exception('paging_bar requires a perpage value.');
1879 if (empty($this->baseurl)) {
1880 throw new coding_exception('paging_bar requires a baseurl value.');
1883 if ($this->totalcount > $this->perpage) {
1884 $pagenum = $this->page - 1;
1886 if ($this->page > 0) {
1887 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
1890 if ($this->perpage > 0) {
1891 $lastpage = ceil($this->totalcount / $this->perpage);
1896 if ($this->page > 15) {
1897 $startpage = $this->page - 10;
1899 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
1904 $currpage = $startpage;
1905 $displaycount = $displaypage = 0;
1907 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
1908 $displaypage = $currpage + 1;
1910 if ($this->page == $currpage) {
1911 $this->pagelinks[] = $displaypage;
1913 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
1914 $this->pagelinks[] = $pagelink;
1921 if ($currpage < $lastpage) {
1922 $lastpageactual = $lastpage - 1;
1923 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
1926 $pagenum = $this->page + 1;
1928 if ($pagenum != $displaypage) {
1929 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
1937 * This class represents how a block appears on a page.
1939 * During output, each block instance is asked to return a block_contents object,
1940 * those are then passed to the $OUTPUT->block function for display.
1942 * {@link $contents} should probably be generated using a moodle_block_..._renderer.
1944 * Other block-like things that need to appear on the page, for example the
1945 * add new block UI, are also represented as block_contents objects.
1947 * @copyright 2009 Tim Hunt
1948 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1951 class block_contents {
1952 /** @var int used to set $skipid. */
1953 protected static $idcounter = 1;
1955 const NOT_HIDEABLE = 0;
1960 * @var integer $skipid All the blocks (or things that look like blocks)
1961 * printed on a page are given a unique number that can be used to construct
1962 * id="" attributes. This is set automatically be the {@link prepare()} method.
1963 * Do not try to set it manually.
1968 * @var integer If this is the contents of a real block, this should be set to
1969 * the block_instance.id. Otherwise this should be set to 0.
1971 public $blockinstanceid = 0;
1974 * @var integer if this is a real block instance, and there is a corresponding
1975 * block_position.id for the block on this page, this should be set to that id.
1976 * Otherwise it should be 0.
1978 public $blockpositionid = 0;
1981 * @param array $attributes an array of attribute => value pairs that are put on the
1982 * outer div of this block. {@link $id} and {@link $classes} attributes should be set separately.
1987 * @param string $title The title of this block. If this came from user input,
1988 * it should already have had format_string() processing done on it. This will
1989 * be output inside <h2> tags. Please do not cause invalid XHTML.
1994 * @param string $content HTML for the content
1996 public $content = '';
1999 * @param array $list an alternative to $content, it you want a list of things with optional icons.
2001 public $footer = '';
2004 * Any small print that should appear under the block to explain to the
2005 * teacher about the block, for example 'This is a sticky block that was
2006 * added in the system context.'
2009 public $annotation = '';
2012 * @var integer one of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2013 * the user can toggle whether this block is visible.
2015 public $collapsible = self::NOT_HIDEABLE;
2018 * A (possibly empty) array of editing controls. Each element of this array
2019 * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2020 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2023 public $controls = array();
2027 * Create new instance of block content
2028 * @param array $attributes
2030 public function __construct(array $attributes=null) {
2031 $this->skipid = self::$idcounter;
2032 self::$idcounter += 1;
2036 $this->attributes = $attributes;
2038 // simple "fake" blocks used in some modules and "Add new block" block
2039 $this->attributes = array('class'=>'block');
2044 * Add html class to block
2045 * @param string $class
2048 public function add_class($class) {
2049 $this->attributes['class'] .= ' '.$class;
2055 * This class represents a target for where a block can go when it is being moved.
2057 * This needs to be rendered as a form with the given hidden from fields, and
2058 * clicking anywhere in the form should submit it. The form action should be
2061 * @copyright 2009 Tim Hunt
2062 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2065 class block_move_target {
2079 * @param string $text
2080 * @param moodle_url $url
2082 public function __construct($text, moodle_url $url) {
2083 $this->text = $text;
2091 * This class is used to represent one item within a custom menu that may or may
2092 * not have children.
2094 * @copyright 2010 Sam Hemelryk
2095 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2098 class custom_menu_item implements renderable {
2100 * The text to show for the item
2105 * The link to give the icon if it has no children
2110 * A title to apply to the item. By default the text
2115 * A sort order for the item, not necessary if you order things in the CFG var
2120 * A reference to the parent for this item or NULL if it is a top level item
2121 * @var custom_menu_item
2125 * A array in which to store children this item has.
2128 protected $children = array();
2130 * A reference to the sort var of the last child that was added
2133 protected $lastsort = 0;
2135 * Constructs the new custom menu item
2137 * @param string $text
2138 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2139 * @param string $title A title to apply to this item [Optional]
2140 * @param int $sort A sort or to use if we need to sort differently [Optional]
2141 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2142 * belongs to, only if the child has a parent. [Optional]
2144 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent=null) {
2145 $this->text = $text;
2147 $this->title = $title;
2148 $this->sort = (int)$sort;
2149 $this->parent = $parent;
2153 * Adds a custom menu item as a child of this node given its properties.
2155 * @param string $text
2156 * @param moodle_url $url
2157 * @param string $title
2159 * @return custom_menu_item
2161 public function add($text, moodle_url $url=null, $title=null, $sort = null) {
2162 $key = count($this->children);
2164 $sort = $this->lastsort + 1;
2166 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2167 $this->lastsort = (int)$sort;
2168 return $this->children[$key];
2171 * Returns the text for this item
2174 public function get_text() {
2178 * Returns the url for this item
2179 * @return moodle_url
2181 public function get_url() {
2185 * Returns the title for this item
2188 public function get_title() {
2189 return $this->title;
2192 * Sorts and returns the children for this item
2195 public function get_children() {
2197 return $this->children;
2200 * Gets the sort order for this child
2203 public function get_sort_order() {
2207 * Gets the parent this child belong to
2208 * @return custom_menu_item
2210 public function get_parent() {
2211 return $this->parent;
2214 * Sorts the children this item has
2216 public function sort() {
2217 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2220 * Returns true if this item has any children
2223 public function has_children() {
2224 return (count($this->children) > 0);
2228 * Sets the text for the node
2229 * @param string $text
2231 public function set_text($text) {
2232 $this->text = (string)$text;
2236 * Sets the title for the node
2237 * @param string $title
2239 public function set_title($title) {
2240 $this->title = (string)$title;
2244 * Sets the url for the node
2245 * @param moodle_url $url
2247 public function set_url(moodle_url $url) {
2255 * This class is used to operate a custom menu that can be rendered for the page.
2256 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2257 * of custom_menu_item nodes that can be rendered by the core renderer.
2259 * To configure the custom menu:
2260 * Settings: Administration > Appearance > Themes > Theme settings
2262 * @copyright 2010 Sam Hemelryk
2263 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2266 class custom_menu extends custom_menu_item {
2268 * Creates the custom menu
2269 * @param string $text Sets the text for this custom menu, never gets used and is optional
2271 public function __construct($text='base') {
2273 parent::__construct($text);
2274 if (!empty($CFG->custommenuitems)) {
2275 $this->override_children(self::convert_text_to_menu_nodes($CFG->custommenuitems));
2280 * Overrides the children of this custom menu. Useful when getting children
2281 * from $CFG->custommenuitems
2283 public function override_children(array $children) {
2284 $this->children = array();
2285 foreach ($children as $child) {
2286 if ($child instanceof custom_menu_item) {
2287 $this->children[] = $child;
2293 * Converts a string into a structured array of custom_menu_items which can
2294 * then be added to a custom menu.
2298 * The number of hyphens at the start determines the depth of the item
2300 * Example structure:
2301 * First level first item|http://www.moodle.com/
2302 * -Second level first item|http://www.moodle.com/partners/
2303 * -Second level second item|http://www.moodle.com/hq/
2304 * --Third level first item|http://www.moodle.com/jobs/
2305 * -Second level third item|http://www.moodle.com/development/
2306 * First level second item|http://www.moodle.com/feedback/
2307 * First level third item
2310 * @param string $text
2313 public static function convert_text_to_menu_nodes($text) {
2314 $lines = explode("\n", $text);
2315 $children = array();
2319 foreach ($lines as $line) {
2320 $line = trim($line);
2321 $bits = explode('|', $line ,4); // name|url|title|sort
2322 if (!array_key_exists(0, $bits) || empty($bits[0])) {
2323 // Every item must have a name to be valid
2326 $bits[0] = ltrim($bits[0],'-');
2328 if (!array_key_exists(1, $bits)) {
2329 // Set the url to null
2332 // Make sure the url is a moodle url
2333 $bits[1] = new moodle_url(trim($bits[1]));
2335 if (!array_key_exists(2, $bits)) {
2336 // Set the title to null seeing as there isn't one
2337 $bits[2] = $bits[0];
2339 // Set an incremental sort order to keep it simple.
2340 $bits[3] = $lastsort;
2341 $lastsort = $bits[3]+1;
2342 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2343 $depth = strlen($match[1]);
2344 if ($depth < $lastdepth) {
2345 if ($lastdepth > 1) {
2346 $depth = $lastdepth - 1;
2347 $lastchild = $lastchild->get_parent()->get_parent()->add($bits[0], $bits[1], $bits[2], $bits[3]);
2350 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $bits[3]);
2351 $children[] = $lastchild;
2353 } else if ($depth > $lastdepth) {
2354 $depth = $lastdepth + 1;
2355 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $bits[3]);
2358 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $bits[3]);
2359 $children[] = $lastchild;
2361 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $bits[3]);
2366 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $bits[3]);
2367 $children[] = $lastchild;
2369 $lastdepth = $depth;
2375 * Sorts two custom menu items
2377 * This function is designed to be used with the usort method
2378 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2380 * @param custom_menu_item $itema
2381 * @param custom_menu_item $itemb
2384 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2385 $itema = $itema->get_sort_order();
2386 $itemb = $itemb->get_sort_order();
2387 if ($itema == $itemb) {
2390 return ($itema > $itemb) ? +1 : -1;