3 // This file is part of Moodle - http://moodle.org/
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 * Classes representing HTML elements, used by $OUTPUT methods
21 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
25 * @copyright 2009 Tim Hunt
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
31 * Interface marking other classes as suitable for renderer_base::render()
32 * @author 2010 Petr Skoda (skodak) info@skodak.org
34 interface renderable {
35 // intentionally empty
39 * Data structure representing a area file tree viewer
41 * @copyright 2010 Dongsheng Cai
42 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
45 class area_file_tree_viewer implements renderable {
50 * Constructor of area_file_tree_viewer class
51 * @param int $contextid
52 * @param string $area, file area
54 * @param string $urlbase, file serving url base
56 public function __construct($contextid, $area, $itemid, $urlbase='') {
58 $fs = get_file_storage();
59 if (empty($urlbase)) {
60 $this->urlbase = "$CFG->wwwroot/pluginfile.php";
62 $this->urlbase = $urlbase;
64 $this->contextid = $contextid;
65 $this->filearea = $area;
66 $this->itemid = $itemid;
67 $this->dir = $fs->get_area_tree($contextid, $area, $itemid);
68 $this->tree_view_parser($this->dir);
71 * Pre-process file tree, generate file url
72 * @param array $dir file tree
74 public function tree_view_parser($dir) {
75 if (empty($dir['subdirs']) and empty($dir['files'])) {
78 foreach ($dir['subdirs'] as $subdir) {
79 $this->tree_view_parser($subdir);
81 foreach ($dir['files'] as $file) {
82 $path = '/'.$this->contextid.'/'.$this->filearea.'/'.$this->itemid.$file->get_filepath().$file->get_filename();
83 $downloadurl = file_encode_url($this->urlbase, $path, true);
84 $file->fileurl = $downloadurl;
90 * Data structure representing a general moodle file tree viewer
92 * @copyright 2010 Dongsheng Cai
93 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
96 class moodle_file_tree_viewer implements renderable {
99 private $enabled_fileareas;
101 * Constructor of moodle_file_tree_viewer class
102 * @param int $contextid
103 * @param string $area, file area
105 * @param string $urlbase, file serving url base
107 public function __construct($contextid, $filearea, $itemid, $filepath, $options=array()) {
108 global $CFG, $OUTPUT;
109 $this->tree = array();
110 $browser = get_file_browser();
111 $fs = get_file_storage();
112 $fileinfo = $browser->get_file_info(get_context_instance_by_id($contextid), $filearea, $itemid, $filepath);
113 $children = $fileinfo->get_children();
114 $parent_info = $fileinfo->get_parent();
115 if (!empty($options['enabled_fileareas']) && is_array($options['enabled_fileareas'])) {
116 $this->enabled_fileareas = $options['enabled_fileareas'];
118 unset($this->enabled_fileareas);
121 $level = $parent_info;
122 $this->path = array();
124 $params = $level->get_params();
125 $context = get_context_instance_by_id($params['contextid']);
126 // lock user in course level
127 if ($context->contextlevel == CONTEXT_COURSECAT or $context->contextlevel == CONTEXT_SYSTEM) {
130 $url = new moodle_url('/files/index.php', $params);
131 $this->path[] = html_writer::link($url->out(false), $level->get_visible_name());
132 $level = $level->get_parent();
134 $this->path = array_reverse($this->path);
135 $this->path[] = $fileinfo->get_visible_name();
137 foreach ($children as $child) {
138 $filedate = $child->get_timemodified();
139 $filesize = $child->get_filesize();
140 $mimetype = $child->get_mimetype();
141 $params = $child->get_params();
142 $url = new moodle_url('/files/index.php', $params);
145 'filename'=>$child->get_visible_name(),
146 'filedate'=>$filedate ? userdate($filedate) : '',
147 'filesize'=>$filesize ? display_size($filesize) : ''
149 if ($child->is_directory()) {
150 $fileitem['isdir'] = true;
151 $fileitem['url'] = $url->out(false);
152 if (isset($this->enabled_fileareas)) {
153 if (!in_array($params['filearea'], $this->enabled_fileareas)) {
156 if (!empty($params['itemid'])) {
157 $itemid = $params['itemid'];
161 $draftfiles = $fs->get_area_files($contextid, $params['filearea'], $itemid, 'id', false);
162 if (count($draftfiles) == 0) {
168 $fileitem['url'] = $child->get_url();
170 $this->tree[] = $fileitem;
177 * Data structure representing a file picker.
179 * @copyright 2010 Dongsheng Cai
180 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
183 class file_picker implements renderable {
185 public function __construct(stdClass $options) {
186 global $CFG, $USER, $PAGE;
187 require_once($CFG->dirroot. '/repository/lib.php');
189 'accepted_types'=>'*',
190 'context'=>$PAGE->context,
191 'return_types'=>FILE_INTERNAL,
192 'env' => 'filepicker',
193 'client_id' => uniqid(),
198 foreach ($defaults as $key=>$value) {
199 if (empty($options->$key)) {
200 $options->$key = $value;
204 $options->currentfile = '';
205 if (!empty($options->itemid)) {
206 $fs = get_file_storage();
207 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
208 if (empty($options->filename)) {
209 if ($files = $fs->get_area_files($usercontext->id, 'user_draft', $options->itemid, 'id DESC', false)) {
210 $file = reset($files);
213 $file = $fs->get_file($usercontext->id, 'user_draft', $options->itemid, $options->filepath, $options->filename);
216 $options->currentfile = html_writer::link(file_encode_url($CFG->wwwroot.'/draftfile.php/', $usercontext->id.'/user_draft/'.$file->get_itemid().'/'.$file->get_filename()), $file->get_filename());
220 // initilise options, getting files in root path
221 $this->options = initialise_filepicker($options);
223 // copying other options
224 foreach ($options as $name=>$value) {
225 $this->options->$name = $value;
231 * Data structure representing a file manager.
233 * @copyright 2010 Dongsheng Cai
234 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
237 class file_manager implements renderable {
239 public function __construct(stdClass $options) {
240 global $CFG, $USER, $PAGE;
241 require_once($CFG->dirroot. '/repository/lib.php');
245 'filearea'=>'user_draft',
248 'client_id'=>uniqid(),
249 'accepted_types'=>'*',
250 'return_types'=>FILE_INTERNAL,
251 'context'=>$PAGE->context
253 foreach ($defaults as $key=>$value) {
254 if (empty($options->$key)) {
255 $options->$key = $value;
259 $fs = get_file_storage();
261 // initilise options, getting files in root path
262 $this->options = file_get_user_area_files($options->itemid, '/', $options->filearea);
264 // calculate file count
265 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
266 $files = $fs->get_area_files($usercontext->id, $options->filearea, $options->itemid, 'id', false);
267 $filecount = count($files);
268 $this->options->filecount = $filecount;
270 // copying other options
271 foreach ($options as $name=>$value) {
272 $this->options->$name = $value;
275 // building file picker options
276 $params = new stdclass;
277 $params->accepted_types = $options->accepted_types;
278 $params->return_types = $options->return_types;
279 $params->context = $options->context;
280 $params->env = 'filemanager';
281 $params->disable_types = !empty($options->disable_types)?$options->disable_types:array();
282 $filepicker_options = initialise_filepicker($params);
283 $this->options->filepicker = $filepicker_options;
288 * Data structure representing a user picture.
290 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
291 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
294 class user_picture implements renderable {
296 * List of mandatory fields in user record here.
299 const FIELDS = 'id,picture,firstname,lastname,imagealt,email'; //note: the email will be useful for gravatar support int the future ;-)
302 * @var object $user A user object with at least fields all columns specified in FIELDS constant set.
306 * @var int $courseid The course id. Used when constructing the link to the user's profile,
307 * page course id used if not specified.
311 * @var bool $link add course profile link to image
315 * @var int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility
319 * @var boolean $alttext add non-blank alt-text to the image.
320 * Default true, set to false when image alt just duplicates text in screenreaders.
322 public $alttext = true;
324 * @var boolean $popup Whether or not to open the link in a popup window.
326 public $popup = false;
328 * @var string Image class attribute
330 public $class = 'userpicture';
333 * User picture constructor.
335 * @param object $user user record with at least id, picture, imagealt, firstname and lastname set.
336 * @param array $options such as link, size, link, ...
338 public function __construct(stdClass $user) {
341 static $fields = null;
342 if (is_null($fields)) {
343 $fields = explode(',', self::FIELDS);
346 if (empty($user->id)) {
347 throw new coding_exception('User id is required when printing user avatar image.');
350 // only touch the DB if we are missing data and complain loudly...
352 foreach ($fields as $field) {
353 if (!array_key_exists($field, $user)) {
355 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
356 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
362 $this->user = $DB->get_record('user', array('id'=>$user->id), self::FIELDS, MUST_EXIST);
364 $this->user = clone($user);
369 * Returns a list of required user fields, useful when fetching required user info from db.
371 * In some cases we have to fetch the user data together with some other information,
372 * the idalias is useful there because the id would otherwise override the main
373 * id of the result record. Please note it has to be converted back to id before rendering.
375 * @param string $tableprefix name of database table prefix in query
376 * @param string $idalias alias of id field
379 public static function fields($tableprefix = '', $idalias = '') {
380 if ($tableprefix === '' and $idalias === '') {
383 $fields = explode(',', self::FIELDS);
384 foreach ($fields as $key=>$field) {
385 if ($field === 'id' and $idalias !== '') {
386 $field = "$field AS $idalias";
388 $fields[$key] = "$tableprefix.$field";
390 return implode(',', $fields);
396 * Data structure representing a help icon.
398 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
399 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
402 class old_help_icon implements renderable {
404 * @var string $helpidentifier lang pack identifier
406 public $helpidentifier;
408 * @var string $title A descriptive text for title tooltip
410 public $title = null;
412 * @var string $component Component name, the same as in get_string()
414 public $component = 'moodle';
416 * @var string $linktext Extra descriptive text next to the icon
418 public $linktext = null;
421 * Constructor: sets up the other components in case they are needed
422 * @param string $helpidentifier The keyword that defines a help page
423 * @param string $title A descriptive text for accessibility only
424 * @param string $component
425 * @param bool $linktext add extra text to icon
428 public function __construct($helpidentifier, $title, $component = 'moodle') {
430 throw new coding_exception('A help_icon object requires a $text parameter');
432 if (empty($helpidentifier)) {
433 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
436 $this->helpidentifier = $helpidentifier;
437 $this->title = $title;
438 $this->component = $component;
443 * Data structure representing a help icon.
445 * @copyright 2010 Petr Skoda (info@skodak.org)
446 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
449 class help_icon implements renderable {
451 * @var string $identifier lang pack identifier (without the "_help" suffix),
452 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
457 * @var string $component Component name, the same as in get_string()
461 * @var string $linktext Extra descriptive text next to the icon
463 public $linktext = null;
467 * @param string $identifier string for help page title,
468 * string with _help suffix is used for the actual help text.
469 * string with _link suffix is used to create a link to further info (if it exists)
470 * @param string $component
472 public function __construct($identifier, $component) {
473 $this->identifier = $identifier;
474 $this->component = $component;
478 * Verifies that both help strings exists, shows debug warnings if not
480 public function diag_strings() {
481 $sm = get_string_manager();
482 if (!$sm->string_exists($this->identifier, $this->component)) {
483 debugging("Help title string does not exist: [$this->identifier, $this->component]");
485 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
486 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
493 * Data structure representing an icon.
495 * @copyright 2010 Petr Skoda
496 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
499 class pix_icon implements renderable {
502 var $attributes = array();
506 * @param string $pix short icon name
507 * @param string $component component name
508 * @param array $attributes html attributes
510 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
512 $this->component = $component;
513 $this->attributes = (array)$attributes;
515 $this->attributes['alt'] = $alt;
516 if (empty($this->attributes['class'])) {
517 $this->attributes['class'] = 'smallicon';
519 if (!isset($this->attributes['title'])) {
520 $this->attributes['title'] = $this->attributes['alt'];
527 * Data structure representing a simple form with only one button.
529 * @copyright 2009 Petr Skoda
530 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
533 class single_button implements renderable {
546 * @var string post or get
548 var $method = 'post';
553 var $class = 'singlebutton';
555 * True if button disabled, false if normal
558 var $disabled = false;
570 * List of attached actions
571 * @var array of component_action
573 var $actions = array();
577 * @param string|moodle_url $url
578 * @param string $label button text
579 * @param string $method get or post submit method
581 public function __construct(moodle_url $url, $label, $method='post') {
582 $this->url = clone($url);
583 $this->label = $label;
584 $this->method = $method;
588 * Shortcut for adding a JS confirm dialog when the button is clicked.
589 * The message must be a yes/no question.
590 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
593 public function add_confirm_action($confirmmessage) {
594 $this->add_action(new component_action('click', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
598 * Add action to the button.
599 * @param component_action $action
602 public function add_action(component_action $action) {
603 $this->actions[] = $action;
609 * Simple form with just one select field that gets submitted automatically.
610 * If JS not enabled small go button is printed too.
612 * @copyright 2009 Petr Skoda
613 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
616 class single_select implements renderable {
618 * Target url - includes hidden fields
623 * Name of the select element.
628 * @var array $options associative array value=>label ex.:
629 * array(1=>'One, 2=>Two)
630 * it is also possible to specify optgroup as complex label array ex.:
631 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
632 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
646 * Extra select field attributes
649 var $attributes = array();
657 * @var string post or get
664 var $class = 'singleselect';
666 * True if button disabled, false if normal
669 var $disabled = false;
681 * List of attached actions
682 * @var array of component_action
684 var $helpicon = null;
687 * @param moodle_url $url form action target, includes hidden fields
688 * @param string $name name of selection field - the changing parameter in url
689 * @param array $options list of options
690 * @param string $selected selected element
691 * @param array $nothing
692 * @param string $formid
694 public function __construct(moodle_url $url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
697 $this->options = $options;
698 $this->selected = $selected;
699 $this->nothing = $nothing;
700 $this->formid = $formid;
704 * Shortcut for adding a JS confirm dialog when the button is clicked.
705 * The message must be a yes/no question.
706 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
709 public function add_confirm_action($confirmmessage) {
710 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
714 * Add action to the button.
715 * @param component_action $action
718 public function add_action(component_action $action) {
719 $this->actions[] = $action;
724 * @param string $page The keyword that defines a help page
725 * @param string $title A descriptive text for accessibility only
726 * @param string $component
727 * @param bool $linktext add extra text to icon
730 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
731 $this->helpicon = new old_help_icon($helppage, $title, $component);
736 * @param string $identifier The keyword that defines a help page
737 * @param string $component
738 * @param bool $linktext add extra text to icon
741 public function set_help_icon($identifier, $component = 'moodle') {
742 $this->helpicon = new help_icon($identifier, $component);
747 * @param string $label
750 public function set_label($label) {
751 $this->label = $label;
757 * Simple URL selection widget description.
758 * @copyright 2009 Petr Skoda
759 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
762 class url_select implements renderable {
764 * @var array $urls associative array value=>label ex.:
765 * array(1=>'One, 2=>Two)
766 * it is also possible to specify optgroup as complex label array ex.:
767 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
768 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
782 * Extra select field attributes
785 var $attributes = array();
795 var $class = 'urlselect';
797 * True if button disabled, false if normal
800 var $disabled = false;
812 * List of attached actions
813 * @var array of component_action
815 var $helpicon = null;
818 * @param array $urls list of options
819 * @param string $selected selected element
820 * @param array $nothing
821 * @param string $formid
823 public function __construct(array $urls, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
825 $this->selected = $selected;
826 $this->nothing = $nothing;
827 $this->formid = $formid;
832 * @param string $page The keyword that defines a help page
833 * @param string $title A descriptive text for accessibility only
834 * @param string $component
835 * @param bool $linktext add extra text to icon
838 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
839 $this->helpicon = new old_help_icon($helppage, $title, $component);
844 * @param string $identifier The keyword that defines a help page
845 * @param string $component
846 * @param bool $linktext add extra text to icon
849 public function set_help_icon($identifier, $component = 'moodle') {
850 $this->helpicon = new help_icon($identifier, $component);
855 * @param string $label
858 public function set_label($label) {
859 $this->label = $label;
865 * Data structure describing html link with special action attached.
866 * @copyright 2010 Petr Skoda
867 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
870 class action_link implements renderable {
878 * @var string HTML fragment
887 * List of actions attached to link
888 * @var array of component_action
894 * @param string|moodle_url $url
895 * @param string $text HTML fragment
896 * @param component_action $action
897 * @param array $attributes associative array of html link attributes + disabled
899 public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null) {
900 $this->url = clone($url);
902 $this->attributes = (array)$attributes;
904 $this->add_action($action);
909 * Add action to the link.
910 * @param component_action $action
913 public function add_action(component_action $action) {
914 $this->actions[] = $action;
917 public function add_class($class) {
918 if (empty($this->attributes['class'])) {
919 $this->attributes['class'] = $class;
921 $this->attributes['class'] .= ' ' . $class;
926 // ==== HTML writer and helper classes, will be probably moved elsewhere ======
929 * Simple html output class
930 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
934 * Outputs a tag with attributes and contents
935 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
936 * @param string $contents What goes between the opening and closing tags
937 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
938 * @return string HTML fragment
940 public static function tag($tagname, $contents, array $attributes = null) {
941 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
945 * Outputs an opening tag with attributes
946 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
947 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
948 * @return string HTML fragment
950 public static function start_tag($tagname, array $attributes = null) {
951 return '<' . $tagname . self::attributes($attributes) . '>';
955 * Outputs a closing tag
956 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
957 * @return string HTML fragment
959 public static function end_tag($tagname) {
960 return '</' . $tagname . '>';
964 * Outputs an empty tag with attributes
965 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
966 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
967 * @return string HTML fragment
969 public static function empty_tag($tagname, array $attributes = null) {
970 return '<' . $tagname . self::attributes($attributes) . ' />';
974 * Outputs a tag, but only if the contents are not empty
975 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
976 * @param string $contents What goes between the opening and closing tags
977 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
978 * @return string HTML fragment
980 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
981 if ($contents === '' || is_null($contents)) {
984 return self::tag($tagname, $contents, $attributes);
988 * Outputs a HTML attribute and value
989 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
990 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
991 * @return string HTML fragment
993 public static function attribute($name, $value) {
994 if (is_array($value)) {
995 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
997 if ($value instanceof moodle_url) {
998 return ' ' . $name . '="' . $value->out() . '"';
1001 // special case, we do not want these in output
1002 if ($value === null) {
1006 // no sloppy trimming here!
1007 return ' ' . $name . '="' . s($value) . '"';
1011 * Outputs a list of HTML attributes and values
1012 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1013 * The values will be escaped with {@link s()}
1014 * @return string HTML fragment
1016 public static function attributes(array $attributes = null) {
1017 $attributes = (array)$attributes;
1019 foreach ($attributes as $name => $value) {
1020 $output .= self::attribute($name, $value);
1026 * Generates random html element id.
1027 * @param string $base
1030 public static function random_id($base='random') {
1031 return uniqid($base);
1035 * Generates a simple html link
1036 * @param string|moodle_url $url
1037 * @param string $text link txt
1038 * @param array $attributes extra html attributes
1039 * @return string HTML fragment
1041 public static function link($url, $text, array $attributes = null) {
1042 $attributes = (array)$attributes;
1043 $attributes['href'] = $url;
1044 return self::tag('a', $text, $attributes);
1048 * generates a simple checkbox with optional label
1049 * @param string $name
1050 * @param string $value
1051 * @param bool $checked
1052 * @param string $label
1053 * @param array $attributes
1054 * @return string html fragment
1056 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1057 $attributes = (array)$attributes;
1060 if ($label !== '' and !is_null($label)) {
1061 if (empty($attributes['id'])) {
1062 $attributes['id'] = self::random_id('checkbox_');
1065 $attributes['type'] = 'checkbox';
1066 $attributes['value'] = $value;
1067 $attributes['name'] = $name;
1068 $attributes['checked'] = $checked ? 'checked' : null;
1070 $output .= self::empty_tag('input', $attributes);
1072 if ($label !== '' and !is_null($label)) {
1073 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1080 * Generates a simple select yes/no form field
1081 * @param string $name name of select element
1082 * @param bool $selected
1083 * @param array $attributes - html select element attributes
1084 * @return string HRML fragment
1086 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1087 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1088 return self::select($options, $name, $selected, null, $attributes);
1092 * Generates a simple select form field
1093 * @param array $options associative array value=>label ex.:
1094 * array(1=>'One, 2=>Two)
1095 * it is also possible to specify optgroup as complex label array ex.:
1096 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1097 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1098 * @param string $name name of select element
1099 * @param string|array $selected value or array of values depending on multiple attribute
1100 * @param array|bool $nothing, add nothing selected option, or false of not added
1101 * @param array $attributes - html select element attributes
1102 * @return string HTML fragment
1104 public static function select(array $options, $name, $selected = '', $nothing = array(''=>'choosedots'), array $attributes = null) {
1105 $attributes = (array)$attributes;
1106 if (is_array($nothing)) {
1107 foreach ($nothing as $k=>$v) {
1108 if ($v === 'choose' or $v === 'choosedots') {
1109 $nothing[$k] = get_string('choosedots');
1112 $options = $nothing + $options; // keep keys, do not override
1114 } else if (is_string($nothing) and $nothing !== '') {
1116 $options = array(''=>$nothing) + $options;
1119 // we may accept more values if multiple attribute specified
1120 $selected = (array)$selected;
1121 foreach ($selected as $k=>$v) {
1122 $selected[$k] = (string)$v;
1125 if (!isset($attributes['id'])) {
1127 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1128 $id = str_replace('[', '', $id);
1129 $id = str_replace(']', '', $id);
1130 $attributes['id'] = $id;
1133 if (!isset($attributes['class'])) {
1134 $class = 'menu'.$name;
1135 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1136 $class = str_replace('[', '', $class);
1137 $class = str_replace(']', '', $class);
1138 $attributes['class'] = $class;
1140 $attributes['class'] = 'select ' . $attributes['class']; /// Add 'select' selector always
1142 $attributes['name'] = $name;
1145 foreach ($options as $value=>$label) {
1146 if (is_array($label)) {
1147 // ignore key, it just has to be unique
1148 $output .= self::select_optgroup(key($label), current($label), $selected);
1150 $output .= self::select_option($label, $value, $selected);
1153 return self::tag('select', $output, $attributes);
1156 private static function select_option($label, $value, array $selected) {
1157 $attributes = array();
1158 $value = (string)$value;
1159 if (in_array($value, $selected, true)) {
1160 $attributes['selected'] = 'selected';
1162 $attributes['value'] = $value;
1163 return self::tag('option', $label, $attributes);
1166 private static function select_optgroup($groupname, $options, array $selected) {
1167 if (empty($options)) {
1170 $attributes = array('label'=>$groupname);
1172 foreach ($options as $value=>$label) {
1173 $output .= self::select_option($label, $value, $selected);
1175 return self::tag('optgroup', $output, $attributes);
1179 * This is a shortcut for making an hour selector menu.
1180 * @param string $type The type of selector (years, months, days, hours, minutes)
1181 * @param string $name fieldname
1182 * @param int $currenttime A default timestamp in GMT
1183 * @param int $step minute spacing
1184 * @param array $attributes - html select element attributes
1185 * @return HTML fragment
1187 public static function select_time($type, $name, $currenttime=0, $step=5, array $attributes=null) {
1188 if (!$currenttime) {
1189 $currenttime = time();
1191 $currentdate = usergetdate($currenttime);
1192 $userdatetype = $type;
1193 $timeunits = array();
1197 for ($i=1970; $i<=2020; $i++) {
1198 $timeunits[$i] = $i;
1200 $userdatetype = 'year';
1203 for ($i=1; $i<=12; $i++) {
1204 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1206 $userdatetype = 'month';
1207 $currentdate['month'] = $currentdate['mon'];
1210 for ($i=1; $i<=31; $i++) {
1211 $timeunits[$i] = $i;
1213 $userdatetype = 'mday';
1216 for ($i=0; $i<=23; $i++) {
1217 $timeunits[$i] = sprintf("%02d",$i);
1222 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1225 for ($i=0; $i<=59; $i+=$step) {
1226 $timeunits[$i] = sprintf("%02d",$i);
1230 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1233 if (empty($attributes['id'])) {
1234 $attributes['id'] = self::random_id('ts_');
1236 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1237 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1239 return $label.$timerselector;
1243 * Shortcut for quick making of lists
1244 * @param array $items
1245 * @param string $tag ul or ol
1246 * @param array $attributes
1249 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1250 //note: 'list' is a reserved keyword ;-)
1254 foreach ($items as $item) {
1255 $output .= html_writer::start_tag('li') . "\n";
1256 $output .= $item . "\n";
1257 $output .= html_writer::end_tag('li') . "\n";
1260 return html_writer::tag($tag, $output, $attributes);
1264 * Returns hidden input fields created from url parameters.
1265 * @param moodle_url $url
1266 * @param array $exclude list of excluded parameters
1267 * @return string HTML fragment
1269 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1270 $exclude = (array)$exclude;
1271 $params = $url->params();
1272 foreach ($exclude as $key) {
1273 unset($params[$key]);
1277 foreach ($params as $key => $value) {
1278 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1279 $output .= self::empty_tag('input', $attributes)."\n";
1285 * Generate a script tag containing the the specified code.
1287 * @param string $js the JavaScript code
1288 * @param moodle_url|string optional url of the external script, $code ignored if specified
1289 * @return string HTML, the code wrapped in <script> tags.
1291 public static function script($jscode, $url=null) {
1293 $attributes = array('type'=>'text/javascript');
1294 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1297 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1298 return self::tag('script', '', $attributes) . "\n";
1306 * Renders HTML table
1308 * This method may modify the passed instance by adding some default properties if they are not set yet.
1309 * If this is not what you want, you should make a full clone of your data before passing them to this
1310 * method. In most cases this is not an issue at all so we do not clone by default for performance
1311 * and memory consumption reasons.
1313 * @param html_table $table data to be rendered
1314 * @return string HTML code
1316 public static function table(html_table $table) {
1317 // prepare table data and populate missing properties with reasonable defaults
1318 if (!empty($table->align)) {
1319 foreach ($table->align as $key => $aa) {
1321 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1323 $table->align[$key] = null;
1327 if (!empty($table->size)) {
1328 foreach ($table->size as $key => $ss) {
1330 $table->size[$key] = 'width:'. $ss .';';
1332 $table->size[$key] = null;
1336 if (!empty($table->wrap)) {
1337 foreach ($table->wrap as $key => $ww) {
1339 $table->wrap[$key] = 'white-space:nowrap;';
1341 $table->wrap[$key] = '';
1345 if (!empty($table->head)) {
1346 foreach ($table->head as $key => $val) {
1347 if (!isset($table->align[$key])) {
1348 $table->align[$key] = null;
1350 if (!isset($table->size[$key])) {
1351 $table->size[$key] = null;
1353 if (!isset($table->wrap[$key])) {
1354 $table->wrap[$key] = null;
1359 if (empty($table->attributes['class'])) {
1360 $table->attributes['class'] = 'generaltable';
1362 if (!empty($table->tablealign)) {
1363 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1366 // explicitly assigned properties override those defined via $table->attributes
1367 $table->attributes['class'] = trim($table->attributes['class']);
1368 $attributes = array_merge($table->attributes, array(
1370 'width' => $table->width,
1371 'summary' => $table->summary,
1372 'cellpadding' => $table->cellpadding,
1373 'cellspacing' => $table->cellspacing,
1375 $output = html_writer::start_tag('table', $attributes) . "\n";
1379 if (!empty($table->head)) {
1380 $countcols = count($table->head);
1381 $output .= html_writer::start_tag('thead', array()) . "\n";
1382 $output .= html_writer::start_tag('tr', array()) . "\n";
1383 $keys = array_keys($table->head);
1384 $lastkey = end($keys);
1386 foreach ($table->head as $key => $heading) {
1387 // Convert plain string headings into html_table_cell objects
1388 if (!($heading instanceof html_table_cell)) {
1389 $headingtext = $heading;
1390 $heading = new html_table_cell();
1391 $heading->text = $headingtext;
1392 $heading->header = true;
1395 if ($heading->header !== false) {
1396 $heading->header = true;
1399 if ($heading->header && empty($heading->scope)) {
1400 $heading->scope = 'col';
1403 $heading->attributes['class'] .= ' header c' . $key;
1404 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1405 $heading->colspan = $table->headspan[$key];
1406 $countcols += $table->headspan[$key] - 1;
1409 if ($key == $lastkey) {
1410 $heading->attributes['class'] .= ' lastcol';
1412 if (isset($table->colclasses[$key])) {
1413 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1415 $heading->attributes['class'] = trim($heading->attributes['class']);
1416 $attributes = array_merge($heading->attributes, array(
1417 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1418 'scope' => $heading->scope,
1419 'colspan' => $heading->colspan,
1423 if ($heading->header === true) {
1426 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1428 $output .= html_writer::end_tag('tr') . "\n";
1429 $output .= html_writer::end_tag('thead') . "\n";
1431 if (empty($table->data)) {
1432 // For valid XHTML strict every table must contain either a valid tr
1433 // or a valid tbody... both of which must contain a valid td
1434 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1435 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1436 $output .= html_writer::end_tag('tbody');
1440 if (!empty($table->data)) {
1442 $keys = array_keys($table->data);
1443 $lastrowkey = end($keys);
1444 $output .= html_writer::start_tag('tbody', array());
1446 foreach ($table->data as $key => $row) {
1447 if (($row === 'hr') && ($countcols)) {
1448 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1450 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1451 if (!($row instanceof html_table_row)) {
1452 $newrow = new html_table_row();
1454 foreach ($row as $item) {
1455 $cell = new html_table_cell();
1456 $cell->text = $item;
1457 $newrow->cells[] = $cell;
1462 $oddeven = $oddeven ? 0 : 1;
1463 if (isset($table->rowclasses[$key])) {
1464 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1467 $row->attributes['class'] .= ' r' . $oddeven;
1468 if ($key == $lastrowkey) {
1469 $row->attributes['class'] .= ' lastrow';
1472 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1473 $keys2 = array_keys($row->cells);
1474 $lastkey = end($keys2);
1476 foreach ($row->cells as $key => $cell) {
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';
1496 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1497 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1498 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1499 $cell->attributes['class'] = trim($cell->attributes['class']);
1500 $tdattributes = array_merge($cell->attributes, array(
1501 'style' => $tdstyle . $cell->style,
1502 'colspan' => $cell->colspan,
1503 'rowspan' => $cell->rowspan,
1505 'abbr' => $cell->abbr,
1506 'scope' => $cell->scope,
1509 if ($cell->header === true) {
1512 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1515 $output .= html_writer::end_tag('tr') . "\n";
1517 $output .= html_writer::end_tag('tbody') . "\n";
1519 $output .= html_writer::end_tag('table') . "\n";
1526 // ==== JS writer and helper classes, will be probably moved elsewhere ======
1529 * Simple javascript output class
1530 * @copyright 2010 Petr Skoda
1534 * Returns javascript code calling the function
1535 * @param string $function function name, can be complex like Y.Event.purgeElement
1536 * @param array $arguments parameters
1537 * @param int $delay execution delay in seconds
1538 * @return string JS code fragment
1540 public function function_call($function, array $arguments = null, $delay=0) {
1542 $arguments = array_map('json_encode', $arguments);
1543 $arguments = implode(', ', $arguments);
1547 $js = "$function($arguments);";
1550 $delay = $delay * 1000; // in miliseconds
1551 $js = "setTimeout(function() { $js }, $delay);";
1557 * Special function which adds Y as first argument of fucntion call.
1558 * @param string $function
1559 * @param array $extraarguments
1562 public function function_call_with_Y($function, array $extraarguments = null) {
1563 if ($extraarguments) {
1564 $extraarguments = array_map('json_encode', $extraarguments);
1565 $arguments = 'Y, ' . implode(', ', $extraarguments);
1569 return "$function($arguments);\n";
1573 * Returns JavaScript code to initialise a new object
1574 * @param string|null $var If it is null then no var is assigned the new object
1575 * @param string $class
1576 * @param array $arguments
1577 * @param array $requirements
1581 public function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1582 if (is_array($arguments)) {
1583 $arguments = array_map('json_encode', $arguments);
1584 $arguments = implode(', ', $arguments);
1587 if ($var === null) {
1588 $js = "new $class(Y, $arguments);";
1589 } else if (strpos($var, '.')!==false) {
1590 $js = "$var = new $class(Y, $arguments);";
1592 $js = "var $var = new $class(Y, $arguments);";
1596 $delay = $delay * 1000; // in miliseconds
1597 $js = "setTimeout(function() { $js }, $delay);";
1600 if (count($requirements) > 0) {
1601 $requirements = implode("', '", $requirements);
1602 $js = "Y.use('$requirements', function(Y){ $js });";
1608 * Returns code setting value to variable
1609 * @param string $name
1610 * @param mixed $value json serialised value
1611 * @param bool $usevar add var definition, ignored for nested properties
1612 * @return string JS code fragment
1614 public function set_variable($name, $value, $usevar=true) {
1618 if (strpos($name, '.')) {
1625 $output .= "$name = ".json_encode($value).";";
1631 * Writes event handler attaching code
1632 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1633 * @param string $event A valid DOM event (click, mousedown, change etc.)
1634 * @param string $function The name of the function to call
1635 * @param array $arguments An optional array of argument parameters to pass to the function
1636 * @return string JS code fragment
1638 public function event_handler($selector, $event, $function, array $arguments = null) {
1639 $selector = json_encode($selector);
1640 $output = "Y.on('$event', $function, $selector, null";
1641 if (!empty($arguments)) {
1642 $output .= ', ' . json_encode($arguments);
1644 return $output . ");\n";
1649 * Holds all the information required to render a <table> by {@see core_renderer::table()}
1652 * $t = new html_table();
1653 * ... // set various properties of the object $t as described below
1654 * echo html_writer::table($t);
1656 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1657 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1662 * @var string value to use for the id attribute of the table
1666 * @var array attributes of HTML attributes for the <table> element
1668 public $attributes = array();
1670 * For more control over the rendering of the headers, an array of html_table_cell objects
1671 * can be passed instead of an array of strings.
1672 * @var array of headings. The n-th array item is used as a heading of the n-th column.
1675 * $t->head = array('Student', 'Grade');
1679 * @var array can be used to make a heading span multiple columns
1682 * $t->headspan = array(2,1);
1684 * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
1685 * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
1689 * @var array of column alignments. The value is used as CSS 'text-align' property. Therefore, possible
1690 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1691 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1693 * Examples of usage:
1694 * $t->align = array(null, 'right');
1696 * $t->align[1] = 'right';
1701 * @var array of column sizes. The value is used as CSS 'size' property.
1703 * Examples of usage:
1704 * $t->size = array('50%', '50%');
1706 * $t->size[1] = '120px';
1710 * @var array of wrapping information. The only possible value is 'nowrap' that sets the
1711 * CSS property 'white-space' to the value 'nowrap' in the given column.
1714 * $t->wrap = array(null, 'nowrap');
1718 * @var array of arrays or html_table_row objects containing the data. Alternatively, if you have
1719 * $head specified, the string 'hr' (for horizontal ruler) can be used
1720 * instead of an array of cells data resulting in a divider rendered.
1722 * Example of usage with array of arrays:
1723 * $row1 = array('Harry Potter', '76 %');
1724 * $row2 = array('Hermione Granger', '100 %');
1725 * $t->data = array($row1, $row2);
1727 * Example with array of html_table_row objects: (used for more fine-grained control)
1728 * $cell1 = new html_table_cell();
1729 * $cell1->text = 'Harry Potter';
1730 * $cell1->colspan = 2;
1731 * $row1 = new html_table_row();
1732 * $row1->cells[] = $cell1;
1733 * $cell2 = new html_table_cell();
1734 * $cell2->text = 'Hermione Granger';
1735 * $cell3 = new html_table_cell();
1736 * $cell3->text = '100 %';
1737 * $row2 = new html_table_row();
1738 * $row2->cells = array($cell2, $cell3);
1739 * $t->data = array($row1, $row2);
1743 * @var string width of the table, percentage of the page preferred. Defaults to 80%
1744 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1746 public $width = null;
1748 * @var string alignment the whole table. Can be 'right', 'left' or 'center' (default).
1749 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1751 public $tablealign = null;
1753 * @var int padding on each cell, in pixels
1754 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1756 public $cellpadding = null;
1758 * @var int spacing between cells, in pixels
1759 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1761 public $cellspacing = null;
1763 * @var array classes to add to particular rows, space-separated string.
1764 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1765 * respectively. Class 'lastrow' is added automatically for the last row
1769 * $t->rowclasses[9] = 'tenth'
1773 * @var array classes to add to every cell in a particular column,
1774 * space-separated string. Class 'cell' is added automatically by the renderer.
1775 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1776 * respectively. Class 'lastcol' is added automatically for all last cells
1780 * $t->colclasses = array(null, 'grade');
1784 * @var string description of the contents for screen readers.
1791 public function __construct() {
1792 $this->attributes['class'] = '';
1798 * Component representing a table row.
1800 * @copyright 2009 Nicolas Connault
1801 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1804 class html_table_row {
1806 * @var string value to use for the id attribute of the row
1810 * @var array $cells Array of html_table_cell objects
1812 public $cells = array();
1814 * @var string $style value to use for the style attribute of the table row
1816 public $style = null;
1818 * @var array attributes of additional HTML attributes for the <tr> element
1820 public $attributes = array();
1824 * @param array $cells
1826 public function __construct(array $cells=null) {
1827 $this->attributes['class'] = '';
1828 $cells = (array)$cells;
1829 foreach ($cells as $cell) {
1830 if ($cell instanceof html_table_cell) {
1831 $this->cells[] = $cell;
1833 $this->cells[] = new html_table_cell($cell);
1841 * Component representing a table cell.
1843 * @copyright 2009 Nicolas Connault
1844 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1847 class html_table_cell {
1849 * @var string value to use for the id attribute of the cell
1853 * @var string $text The contents of the cell
1857 * @var string $abbr Abbreviated version of the contents of the cell
1859 public $abbr = null;
1861 * @var int $colspan Number of columns this cell should span
1863 public $colspan = null;
1865 * @var int $rowspan Number of rows this cell should span
1867 public $rowspan = null;
1869 * @var string $scope Defines a way to associate header cells and data cells in a table
1871 public $scope = null;
1873 * @var boolean $header Whether or not this cell is a header cell
1875 public $header = null;
1877 * @var string $style value to use for the style attribute of the table cell
1879 public $style = null;
1881 * @var array attributes of additional HTML attributes for the <tr> element
1883 public $attributes = array();
1885 public function __construct($text = null) {
1886 $this->text = $text;
1887 $this->attributes['class'] = '';
1892 /// Complex components aggregating simpler components
1896 * Component representing a paging bar.
1898 * @copyright 2009 Nicolas Connault
1899 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1902 class paging_bar implements renderable {
1904 * @var int $maxdisplay The maximum number of pagelinks to display
1906 public $maxdisplay = 18;
1908 * @var int $totalcount post or get
1912 * @var int $page The page you are currently viewing
1916 * @var int $perpage The number of entries that should be shown per page
1920 * @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.
1921 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
1925 * @var string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
1929 * @var string $previouslink A HTML link representing the "previous" page
1931 public $previouslink = null;
1933 * @var tring $nextlink A HTML link representing the "next" page
1935 public $nextlink = null;
1937 * @var tring $firstlink A HTML link representing the first page
1939 public $firstlink = null;
1941 * @var tring $lastlink A HTML link representing the last page
1943 public $lastlink = null;
1945 * @var array $pagelinks An array of strings. One of them is just a string: the current page
1947 public $pagelinks = array();
1950 * Constructor paging_bar with only the required params.
1952 * @param int $totalcount The total number of entries available to be paged through
1953 * @param int $page The page you are currently viewing
1954 * @param int $perpage The number of entries that should be shown per page
1955 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
1956 * @param string $pagevar name of page parameter that holds the page number
1958 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
1959 $this->totalcount = $totalcount;
1960 $this->page = $page;
1961 $this->perpage = $perpage;
1962 $this->baseurl = $baseurl;
1963 $this->pagevar = $pagevar;
1969 public function prepare(renderer_base $output, moodle_page $page, $target) {
1970 if (!isset($this->totalcount) || is_null($this->totalcount)) {
1971 throw new coding_exception('paging_bar requires a totalcount value.');
1973 if (!isset($this->page) || is_null($this->page)) {
1974 throw new coding_exception('paging_bar requires a page value.');
1976 if (empty($this->perpage)) {
1977 throw new coding_exception('paging_bar requires a perpage value.');
1979 if (empty($this->baseurl)) {
1980 throw new coding_exception('paging_bar requires a baseurl value.');
1983 if ($this->totalcount > $this->perpage) {
1984 $pagenum = $this->page - 1;
1986 if ($this->page > 0) {
1987 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
1990 if ($this->perpage > 0) {
1991 $lastpage = ceil($this->totalcount / $this->perpage);
1996 if ($this->page > 15) {
1997 $startpage = $this->page - 10;
1999 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2004 $currpage = $startpage;
2005 $displaycount = $displaypage = 0;
2007 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2008 $displaypage = $currpage + 1;
2010 if ($this->page == $currpage) {
2011 $this->pagelinks[] = $displaypage;
2013 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2014 $this->pagelinks[] = $pagelink;
2021 if ($currpage < $lastpage) {
2022 $lastpageactual = $lastpage - 1;
2023 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2026 $pagenum = $this->page + 1;
2028 if ($pagenum != $displaypage) {
2029 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2037 * This class represents how a block appears on a page.
2039 * During output, each block instance is asked to return a block_contents object,
2040 * those are then passed to the $OUTPUT->block function for display.
2042 * {@link $contents} should probably be generated using a moodle_block_..._renderer.
2044 * Other block-like things that need to appear on the page, for example the
2045 * add new block UI, are also represented as block_contents objects.
2047 * @copyright 2009 Tim Hunt
2048 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2051 class block_contents {
2052 /** @var int used to set $skipid. */
2053 protected static $idcounter = 1;
2055 const NOT_HIDEABLE = 0;
2060 * @var integer $skipid All the blocks (or things that look like blocks)
2061 * printed on a page are given a unique number that can be used to construct
2062 * id="" attributes. This is set automatically be the {@link prepare()} method.
2063 * Do not try to set it manually.
2068 * @var integer If this is the contents of a real block, this should be set to
2069 * the block_instance.id. Otherwise this should be set to 0.
2071 public $blockinstanceid = 0;
2074 * @var integer if this is a real block instance, and there is a corresponding
2075 * block_position.id for the block on this page, this should be set to that id.
2076 * Otherwise it should be 0.
2078 public $blockpositionid = 0;
2081 * @param array $attributes an array of attribute => value pairs that are put on the
2082 * outer div of this block. {@link $id} and {@link $classes} attributes should be set separately.
2087 * @param string $title The title of this block. If this came from user input,
2088 * it should already have had format_string() processing done on it. This will
2089 * be output inside <h2> tags. Please do not cause invalid XHTML.
2094 * @param string $content HTML for the content
2096 public $content = '';
2099 * @param array $list an alternative to $content, it you want a list of things with optional icons.
2101 public $footer = '';
2104 * Any small print that should appear under the block to explain to the
2105 * teacher about the block, for example 'This is a sticky block that was
2106 * added in the system context.'
2109 public $annotation = '';
2112 * @var integer one of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2113 * the user can toggle whether this block is visible.
2115 public $collapsible = self::NOT_HIDEABLE;
2118 * A (possibly empty) array of editing controls. Each element of this array
2119 * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2120 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2123 public $controls = array();
2127 * Create new instance of block content
2128 * @param array $attributes
2130 public function __construct(array $attributes=null) {
2131 $this->skipid = self::$idcounter;
2132 self::$idcounter += 1;
2136 $this->attributes = $attributes;
2138 // simple "fake" blocks used in some modules and "Add new block" block
2139 $this->attributes = array('class'=>'block');
2144 * Add html class to block
2145 * @param string $class
2148 public function add_class($class) {
2149 $this->attributes['class'] .= ' '.$class;
2155 * This class represents a target for where a block can go when it is being moved.
2157 * This needs to be rendered as a form with the given hidden from fields, and
2158 * clicking anywhere in the form should submit it. The form action should be
2161 * @copyright 2009 Tim Hunt
2162 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2165 class block_move_target {
2179 * @param string $text
2180 * @param moodle_url $url
2182 public function __construct($text, moodle_url $url) {
2183 $this->text = $text;
2191 * This class is used to represent one item within a custom menu that may or may
2192 * not have children.
2194 * @copyright 2010 Sam Hemelryk
2195 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2198 class custom_menu_item implements renderable {
2200 * The text to show for the item
2205 * The link to give the icon if it has no children
2210 * A title to apply to the item. By default the text
2215 * A sort order for the item, not necessary if you order things in the CFG var
2220 * A reference to the parent for this item or NULL if it is a top level item
2221 * @var custom_menu_item
2225 * A array in which to store children this item has.
2228 protected $children = array();
2230 * A reference to the sort var of the last child that was added
2233 protected $lastsort = 0;
2235 * Constructs the new custom menu item
2237 * @param string $text
2238 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2239 * @param string $title A title to apply to this item [Optional]
2240 * @param int $sort A sort or to use if we need to sort differently [Optional]
2241 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2242 * belongs to, only if the child has a parent. [Optional]
2244 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent=null) {
2245 $this->text = $text;
2247 $this->title = $title;
2248 $this->sort = (int)$sort;
2249 $this->parent = $parent;
2253 * Adds a custom menu item as a child of this node given its properties.
2255 * @param string $text
2256 * @param moodle_url $url
2257 * @param string $title
2259 * @return custom_menu_item
2261 public function add($text, moodle_url $url=null, $title=null, $sort = null) {
2262 $key = count($this->children);
2264 $sort = $this->lastsort + 1;
2266 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2267 $this->lastsort = (int)$sort;
2268 return $this->children[$key];
2271 * Returns the text for this item
2274 public function get_text() {
2278 * Returns the url for this item
2279 * @return moodle_url
2281 public function get_url() {
2285 * Returns the title for this item
2288 public function get_title() {
2289 return $this->title;
2292 * Sorts and returns the children for this item
2295 public function get_children() {
2297 return $this->children;
2300 * Gets the sort order for this child
2303 public function get_sort_order() {
2307 * Gets the parent this child belong to
2308 * @return custom_menu_item
2310 public function get_parent() {
2311 return $this->parent;
2314 * Sorts the children this item has
2316 public function sort() {
2317 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2320 * Returns true if this item has any children
2323 public function has_children() {
2324 return (count($this->children) > 0);
2331 * This class is used to operate a custom menu that can be rendered for the page.
2332 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2333 * of custom_menu_item nodes that can be rendered by the core renderer.
2335 * To configure the custom menu:
2336 * Settings: Administration > Appearance > Themes > Theme settings
2338 * @copyright 2010 Sam Hemelryk
2339 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2342 class custom_menu extends custom_menu_item {
2344 * Creates the custom menu
2345 * @param string $text Sets the text for this custom menu, never gets used and is optional
2347 public function __construct($text='base') {
2349 parent::__construct($text);
2350 if (!empty($CFG->custommenuitems)) {
2351 $this->override_children(self::convert_text_to_menu_nodes($CFG->custommenuitems));
2356 * Overrides the children of this custom menu. Useful when getting children
2357 * from $CFG->custommenuitems
2359 public function override_children(array $children) {
2360 $this->children = array();
2361 foreach ($children as $child) {
2362 if ($child instanceof custom_menu_item) {
2363 $this->children[] = $child;
2369 * Converts a string into a structured array of custom_menu_items which can
2370 * then be added to a custom menu.
2374 * The number of hyphens at the start determines the depth of the item
2376 * Example structure:
2377 * First level first item|http://www.moodle.com/
2378 * -Second level first item|http://www.moodle.com/partners/
2379 * -Second level second item|http://www.moodle.com/hq/
2380 * --Third level first item|http://www.moodle.com/jobs/
2381 * -Second level third item|http://www.moodle.com/development/
2382 * First level second item|http://www.moodle.com/feedback/
2383 * First level third item
2386 * @param string $text
2389 public static function convert_text_to_menu_nodes($text) {
2390 $lines = explode("\n", $text);
2391 $children = array();
2395 foreach ($lines as $line) {
2396 $line = trim($line);
2397 $bits = explode('|', $line ,4); // name|url|title|sort
2398 if (!array_key_exists(0, $bits) || empty($bits[0])) {
2399 // Every item must have a name to be valid
2402 $bits[0] = ltrim($bits[0],'-');
2404 if (!array_key_exists(1, $bits)) {
2405 // Set the url to null
2408 // Make sure the url is a moodle url
2409 $bits[1] = new moodle_url($bits[1]);
2411 if (!array_key_exists(2, $bits)) {
2412 // Set the title to null seeing as there isn't one
2413 $bits[2] = $bits[0];
2415 // Set an incremental sort order to keep it simple.
2416 $bits[3] = $lastsort;
2417 $lastsort = $bits[3]+1;
2418 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2419 $depth = strlen($match[1]);
2420 if ($depth < $lastdepth) {
2421 if ($lastdepth > 1) {
2422 $depth = $lastdepth - 1;
2423 $lastchild = $lastchild->get_parent()->get_parent()->add($bits[0], $bits[1], $bits[2], $bits[3]);
2426 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $bits[3]);
2427 $children[] = $lastchild;
2429 } else if ($depth > $lastdepth) {
2430 $depth = $lastdepth + 1;
2431 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $bits[3]);
2434 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $bits[3]);
2435 $children[] = $lastchild;
2437 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $bits[3]);
2442 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $bits[3]);
2443 $children[] = $lastchild;
2445 $lastdepth = $depth;
2451 * Sorts two custom menu items
2453 * This function is designed to be used with the usort method
2454 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2456 * @param custom_menu_item $itema
2457 * @param custom_menu_item $itemb
2460 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2461 $itema = $itema->get_sort_order();
2462 $itemb = $itemb->get_sort_order();
2463 if ($itema == $itemb) {
2466 return ($itema > $itemb) ? +1 : -1;
2471 * Image gallery component
2473 * This is the image gallery component that can be used to display several images
2474 * and if JavaScript is enabled uses the gallery-lightbox YUI module to display
2475 * them within a lightbox with appropriate controls and such.
2477 * Lib / YUI Module location: lib/gallery/20100601/
2479 * @copyright 2010 Sam Hemelryk
2480 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2483 class image_gallery implements renderable {
2486 * Used to ensure we only initialise the lightbox once... it is shared
2489 protected static $jsinit = false;
2491 * An array of images
2494 public $images = array();
2496 * The grouping to apply in the lightbox
2499 public $grouping = null;
2502 * If set to true only the first image is visible.
2504 public $displayfirstimageonly = false;
2507 * Constructs an image gallery component
2508 * @param array $images
2509 * @param string $grouping
2511 public function __construct(array $images=null, $grouping=null) {
2512 $this->grouping = $grouping;
2513 if (is_array($images)) {
2514 foreach ($images as $image) {
2515 $image = (array)$image;
2516 if (!array_key_exists('imageurl', $image)) {
2517 throw new coding_exception('Image gallery images must specify a url for every image');
2519 if (!array_key_exists('thumburl', $image)) {
2520 throw new coding_exception('Image gallery images must specify a url for every image');
2522 if (!array_key_exists('title', $image)) {
2523 throw new coding_exception('Image gallery images must specify a title for every image');
2525 if (!array_key_exists('alt', $image)) {
2526 $image['alt'] = null;
2528 if (!array_key_exists('attributes', $image)) {
2529 $image['attributes'] = null;
2531 $this->add_image($image['thumburl'], $image['imageurl'], $image['title'], $image['alt'], $image['attributes']);
2536 * Adds an image to the gallery
2538 * @param moodle_url|string $thumburl
2539 * @param moodle_url|string $imageurl
2540 * @param string $title
2541 * @param string $alt
2542 * @param array $attributes
2544 public function add_image($thumburl, $imageurl, $title, $alt=null, array $attributes=null) {
2545 $image = new stdClass;
2546 $image->link = array('id'=>'imagelink'.(count($this->images)+1), 'class'=>'imagelink');
2547 $image->thumb = array('id'=>'imagethumb'.(count($this->images)+1), 'class'=>'imagethumb');
2548 if (is_array($attributes)) {
2549 $image->link = $attributes;
2551 $image->link['href'] = new moodle_url($imageurl);
2552 $image->link['title'] = $title;
2553 $image->link['rel'] = 'lightbox';
2554 if ($this->grouping !== null) {
2555 $image->link['rel'] .= "[{$this->grouping}]";
2558 $image->thumb['src'] = new moodle_url($thumburl);
2559 $image->thumb['alt'] = $alt;
2561 $this->images[] = $image;