weekly release 2.1.7+
[moodle.git] / lib / outputcomponents.php
blobd71bdfc0afda5872ad7f4531adab087f919f7340
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
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.
9 //
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/>.
18 /**
19 * Classes representing HTML elements, used by $OUTPUT methods
21 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
22 * for an overview.
24 * @package core
25 * @subpackage lib
26 * @copyright 2009 Tim Hunt
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 defined('MOODLE_INTERNAL') || die();
32 /**
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
40 /**
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
45 * @since Moodle 2.0
47 class file_picker implements renderable {
48 public $options;
49 public function __construct(stdClass $options) {
50 global $CFG, $USER, $PAGE;
51 require_once($CFG->dirroot. '/repository/lib.php');
52 $defaults = array(
53 'accepted_types'=>'*',
54 'return_types'=>FILE_INTERNAL,
55 'env' => 'filepicker',
56 'client_id' => uniqid(),
57 'itemid' => 0,
58 'maxbytes'=>-1,
59 'maxfiles'=>1,
60 'buttonname'=>false
62 foreach ($defaults as $key=>$value) {
63 if (empty($options->$key)) {
64 $options->$key = $value;
68 $options->currentfile = '';
69 if (!empty($options->itemid)) {
70 $fs = get_file_storage();
71 $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
72 if (empty($options->filename)) {
73 if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
74 $file = reset($files);
76 } else {
77 $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
79 if (!empty($file)) {
80 $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
84 // initilise options, getting files in root path
85 $this->options = initialise_filepicker($options);
87 // copying other options
88 foreach ($options as $name=>$value) {
89 if (!isset($this->options->$name)) {
90 $this->options->$name = $value;
96 /**
97 * Data structure representing a user picture.
99 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
100 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
101 * @since Moodle 2.0
103 class user_picture implements renderable {
105 * @var array List of mandatory fields in user record here. (do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
107 protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'imagealt', 'email');
110 * @var object $user A user object with at least fields all columns specified in $fields array constant set.
112 public $user;
114 * @var int $courseid The course id. Used when constructing the link to the user's profile,
115 * page course id used if not specified.
117 public $courseid;
119 * @var bool $link add course profile link to image
121 public $link = true;
123 * @var int $size Size in pixels. Special values are (true/1 = 100px) and (false/0 = 35px) for backward compatibility
125 public $size = 35;
127 * @var boolean $alttext add non-blank alt-text to the image.
128 * Default true, set to false when image alt just duplicates text in screenreaders.
130 public $alttext = true;
132 * @var boolean $popup Whether or not to open the link in a popup window.
134 public $popup = false;
136 * @var string Image class attribute
138 public $class = 'userpicture';
141 * User picture constructor.
143 * @param object $user user record with at least id, picture, imagealt, firstname and lastname set.
144 * @param array $options such as link, size, link, ...
146 public function __construct(stdClass $user) {
147 global $DB;
149 if (empty($user->id)) {
150 throw new coding_exception('User id is required when printing user avatar image.');
153 // only touch the DB if we are missing data and complain loudly...
154 $needrec = false;
155 foreach (self::$fields as $field) {
156 if (!array_key_exists($field, $user)) {
157 $needrec = true;
158 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
159 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
160 break;
164 if ($needrec) {
165 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
166 } else {
167 $this->user = clone($user);
172 * Returns a list of required user fields, useful when fetching required user info from db.
174 * In some cases we have to fetch the user data together with some other information,
175 * the idalias is useful there because the id would otherwise override the main
176 * id of the result record. Please note it has to be converted back to id before rendering.
178 * @param string $tableprefix name of database table prefix in query
179 * @param array $extrafields extra fields to be included in result (do not include TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
180 * @param string $idalias alias of id field
181 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
182 * @return string
184 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
185 if (!$tableprefix and !$extrafields and !$idalias) {
186 return implode(',', self::$fields);
188 if ($tableprefix) {
189 $tableprefix .= '.';
191 $fields = array();
192 foreach (self::$fields as $field) {
193 if ($field === 'id' and $idalias and $idalias !== 'id') {
194 $fields[$field] = "$tableprefix$field AS $idalias";
195 } else {
196 if ($fieldprefix and $field !== 'id') {
197 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
198 } else {
199 $fields[$field] = "$tableprefix$field";
203 // add extra fields if not already there
204 if ($extrafields) {
205 foreach ($extrafields as $e) {
206 if ($e === 'id' or isset($fields[$e])) {
207 continue;
209 if ($fieldprefix) {
210 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
211 } else {
212 $fields[$e] = "$tableprefix$e";
216 return implode(',', $fields);
220 * Extract the aliased user fields from a given record
222 * Given a record that was previously obtained using {@link self::fields()} with aliases,
223 * this method extracts user related unaliased fields.
225 * @param stdClass $record containing user picture fields
226 * @param array $extrafields extra fields included in the $record
227 * @param string $idalias alias of the id field
228 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
229 * @return stdClass object with unaliased user fields
231 public static function unalias(stdClass $record, array $extrafields=null, $idalias='id', $fieldprefix='') {
233 if (empty($idalias)) {
234 $idalias = 'id';
237 $return = new stdClass();
239 foreach (self::$fields as $field) {
240 if ($field === 'id') {
241 if (property_exists($record, $idalias)) {
242 $return->id = $record->{$idalias};
244 } else {
245 if (property_exists($record, $fieldprefix.$field)) {
246 $return->{$field} = $record->{$fieldprefix.$field};
250 // add extra fields if not already there
251 if ($extrafields) {
252 foreach ($extrafields as $e) {
253 if ($e === 'id' or property_exists($return, $e)) {
254 continue;
256 $return->{$e} = $record->{$fieldprefix.$e};
260 return $return;
264 * Works out the URL for the users picture.
266 * This method is recommended as it avoids costly redirects of user pictures
267 * if requests are made for non-existent files etc.
269 * @param renderer_base $renderer
270 * @return moodle_url
272 public function get_url(moodle_page $page, renderer_base $renderer = null) {
273 global $CFG;
275 if (is_null($renderer)) {
276 $renderer = $page->get_renderer('core');
279 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
280 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
281 // protect images if login required and not logged in;
282 // also if login is required for profile images and is not logged in or guest
283 // do not use require_login() because it is expensive and not suitable here anyway
284 return $renderer->pix_url('u/f1');
287 // Sort out the filename and size. Size is only required for the gravatar
288 // implementation presently.
289 if (empty($this->size)) {
290 $filename = 'f2';
291 $size = 35;
292 } else if ($this->size === true or $this->size == 1) {
293 $filename = 'f1';
294 $size = 100;
295 } else if ($this->size >= 50) {
296 $filename = 'f1';
297 $size = (int)$this->size;
298 } else {
299 $filename = 'f2';
300 $size = (int)$this->size;
303 if ($this->user->picture == 1) {
304 // The user has uploaded their own profile pic. In this case we will
305 // check that a profile pic file does actually exist
306 $fs = get_file_storage();
307 $context = get_context_instance(CONTEXT_USER, $this->user->id);
308 if (!$fs->file_exists($context->id, 'user', 'icon', 0, '/', $filename.'/.png')) {
309 if (!$fs->file_exists($context->id, 'user', 'icon', 0, '/', $filename.'/.jpg')) {
310 return $renderer->pix_url('u/'.$filename);
313 $path = '/';
314 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
315 // We append the theme name to the file path if we have it so that
316 // in the circumstance that the profile picture is not available
317 // when the user actually requests it they still get the profile
318 // picture for the correct theme.
319 $path .= $page->theme->name.'/';
321 return moodle_url::make_pluginfile_url($context->id, 'user', 'icon', NULL, $path, $filename);
323 } else if ($this->user->picture == 2) {
324 // This is just VERY basic support for gravatar to give the actual
325 // implementor a headstart in what to do.
326 if ($size < 1 || $size > 500) {
327 $size = 35;
329 $md5 = md5(strtolower(trim($this->user->email)));
330 $default = urlencode($this->pix_url('u/'.$filename)->out(false));
331 return "http://www.gravatar.com/avatar/{$md5}?s={$size}&d={$default}";
334 return $renderer->pix_url('u/'.$filename);
339 * Data structure representing a help icon.
341 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
342 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
343 * @since Moodle 2.0
345 class old_help_icon implements renderable {
347 * @var string $helpidentifier lang pack identifier
349 public $helpidentifier;
351 * @var string $title A descriptive text for title tooltip
353 public $title = null;
355 * @var string $component Component name, the same as in get_string()
357 public $component = 'moodle';
359 * @var string $linktext Extra descriptive text next to the icon
361 public $linktext = null;
364 * Constructor: sets up the other components in case they are needed
365 * @param string $helpidentifier The keyword that defines a help page
366 * @param string $title A descriptive text for accessibility only
367 * @param string $component
368 * @param bool $linktext add extra text to icon
369 * @return void
371 public function __construct($helpidentifier, $title, $component = 'moodle') {
372 if (empty($title)) {
373 throw new coding_exception('A help_icon object requires a $text parameter');
375 if (empty($helpidentifier)) {
376 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
379 $this->helpidentifier = $helpidentifier;
380 $this->title = $title;
381 $this->component = $component;
386 * Data structure representing a help icon.
388 * @copyright 2010 Petr Skoda (info@skodak.org)
389 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
390 * @since Moodle 2.0
392 class help_icon implements renderable {
394 * @var string $identifier lang pack identifier (without the "_help" suffix),
395 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
396 * must exist.
398 public $identifier;
400 * @var string $component Component name, the same as in get_string()
402 public $component;
404 * @var string $linktext Extra descriptive text next to the icon
406 public $linktext = null;
409 * Constructor
410 * @param string $identifier string for help page title,
411 * string with _help suffix is used for the actual help text.
412 * string with _link suffix is used to create a link to further info (if it exists)
413 * @param string $component
415 public function __construct($identifier, $component) {
416 $this->identifier = $identifier;
417 $this->component = $component;
421 * Verifies that both help strings exists, shows debug warnings if not
423 public function diag_strings() {
424 $sm = get_string_manager();
425 if (!$sm->string_exists($this->identifier, $this->component)) {
426 debugging("Help title string does not exist: [$this->identifier, $this->component]");
428 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
429 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
436 * Data structure representing an icon.
438 * @copyright 2010 Petr Skoda
439 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
440 * @since Moodle 2.0
442 class pix_icon implements renderable {
443 var $pix;
444 var $component;
445 var $attributes = array();
448 * Constructor
449 * @param string $pix short icon name
450 * @param string $component component name
451 * @param array $attributes html attributes
453 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
454 $this->pix = $pix;
455 $this->component = $component;
456 $this->attributes = (array)$attributes;
458 $this->attributes['alt'] = $alt;
459 if (empty($this->attributes['class'])) {
460 $this->attributes['class'] = 'smallicon';
462 if (!isset($this->attributes['title'])) {
463 $this->attributes['title'] = $this->attributes['alt'];
469 * Data structure representing an emoticon image
471 * @since Moodle 2.0
473 class pix_emoticon extends pix_icon implements renderable {
476 * Constructor
477 * @param string $pix short icon name
478 * @param string $alt alternative text
479 * @param string $component emoticon image provider
480 * @param array $attributes explicit HTML attributes
482 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
483 if (empty($attributes['class'])) {
484 $attributes['class'] = 'emoticon';
486 parent::__construct($pix, $alt, $component, $attributes);
491 * Data structure representing a simple form with only one button.
493 * @copyright 2009 Petr Skoda
494 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
495 * @since Moodle 2.0
497 class single_button implements renderable {
499 * Target url
500 * @var moodle_url
502 var $url;
504 * Button label
505 * @var string
507 var $label;
509 * Form submit method
510 * @var string post or get
512 var $method = 'post';
514 * Wrapping div class
515 * @var string
516 * */
517 var $class = 'singlebutton';
519 * True if button disabled, false if normal
520 * @var boolean
522 var $disabled = false;
524 * Button tooltip
525 * @var string
527 var $tooltip = null;
529 * Form id
530 * @var string
532 var $formid;
534 * List of attached actions
535 * @var array of component_action
537 var $actions = array();
540 * Constructor
541 * @param string|moodle_url $url
542 * @param string $label button text
543 * @param string $method get or post submit method
545 public function __construct(moodle_url $url, $label, $method='post') {
546 $this->url = clone($url);
547 $this->label = $label;
548 $this->method = $method;
552 * Shortcut for adding a JS confirm dialog when the button is clicked.
553 * The message must be a yes/no question.
554 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
555 * @return void
557 public function add_confirm_action($confirmmessage) {
558 $this->add_action(new confirm_action($confirmmessage));
562 * Add action to the button.
563 * @param component_action $action
564 * @return void
566 public function add_action(component_action $action) {
567 $this->actions[] = $action;
573 * Simple form with just one select field that gets submitted automatically.
574 * If JS not enabled small go button is printed too.
576 * @copyright 2009 Petr Skoda
577 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
578 * @since Moodle 2.0
580 class single_select implements renderable {
582 * Target url - includes hidden fields
583 * @var moodle_url
585 var $url;
587 * Name of the select element.
588 * @var string
590 var $name;
592 * @var array $options associative array value=>label ex.:
593 * array(1=>'One, 2=>Two)
594 * it is also possible to specify optgroup as complex label array ex.:
595 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
596 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
598 var $options;
600 * Selected option
601 * @var string
603 var $selected;
605 * Nothing selected
606 * @var array
608 var $nothing;
610 * Extra select field attributes
611 * @var array
613 var $attributes = array();
615 * Button label
616 * @var string
618 var $label = '';
620 * Form submit method
621 * @var string post or get
623 var $method = 'get';
625 * Wrapping div class
626 * @var string
627 * */
628 var $class = 'singleselect';
630 * True if button disabled, false if normal
631 * @var boolean
633 var $disabled = false;
635 * Button tooltip
636 * @var string
638 var $tooltip = null;
640 * Form id
641 * @var string
643 var $formid = null;
645 * List of attached actions
646 * @var array of component_action
648 var $helpicon = null;
650 * Constructor
651 * @param moodle_url $url form action target, includes hidden fields
652 * @param string $name name of selection field - the changing parameter in url
653 * @param array $options list of options
654 * @param string $selected selected element
655 * @param array $nothing
656 * @param string $formid
658 public function __construct(moodle_url $url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
659 $this->url = $url;
660 $this->name = $name;
661 $this->options = $options;
662 $this->selected = $selected;
663 $this->nothing = $nothing;
664 $this->formid = $formid;
668 * Shortcut for adding a JS confirm dialog when the button is clicked.
669 * The message must be a yes/no question.
670 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
671 * @return void
673 public function add_confirm_action($confirmmessage) {
674 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
678 * Add action to the button.
679 * @param component_action $action
680 * @return void
682 public function add_action(component_action $action) {
683 $this->actions[] = $action;
687 * Adds help icon.
688 * @param string $page The keyword that defines a help page
689 * @param string $title A descriptive text for accessibility only
690 * @param string $component
691 * @param bool $linktext add extra text to icon
692 * @return void
694 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
695 $this->helpicon = new old_help_icon($helppage, $title, $component);
699 * Adds help icon.
700 * @param string $identifier The keyword that defines a help page
701 * @param string $component
702 * @param bool $linktext add extra text to icon
703 * @return void
705 public function set_help_icon($identifier, $component = 'moodle') {
706 $this->helpicon = new help_icon($identifier, $component);
710 * Sets select's label
711 * @param string $label
712 * @return void
714 public function set_label($label) {
715 $this->label = $label;
721 * Simple URL selection widget description.
722 * @copyright 2009 Petr Skoda
723 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
724 * @since Moodle 2.0
726 class url_select implements renderable {
728 * @var array $urls associative array value=>label ex.:
729 * array(1=>'One, 2=>Two)
730 * it is also possible to specify optgroup as complex label array ex.:
731 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
732 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
734 var $urls;
736 * Selected option
737 * @var string
739 var $selected;
741 * Nothing selected
742 * @var array
744 var $nothing;
746 * Extra select field attributes
747 * @var array
749 var $attributes = array();
751 * Button label
752 * @var string
754 var $label = '';
756 * Wrapping div class
757 * @var string
758 * */
759 var $class = 'urlselect';
761 * True if button disabled, false if normal
762 * @var boolean
764 var $disabled = false;
766 * Button tooltip
767 * @var string
769 var $tooltip = null;
771 * Form id
772 * @var string
774 var $formid = null;
776 * List of attached actions
777 * @var array of component_action
779 var $helpicon = null;
781 * @var string If set, makes button visible with given name for button
783 var $showbutton = null;
785 * Constructor
786 * @param array $urls list of options
787 * @param string $selected selected element
788 * @param array $nothing
789 * @param string $formid
790 * @param string $showbutton Set to text of button if it should be visible
791 * or null if it should be hidden (hidden version always has text 'go')
793 public function __construct(array $urls, $selected='', $nothing=array(''=>'choosedots'),
794 $formid=null, $showbutton=null) {
795 $this->urls = $urls;
796 $this->selected = $selected;
797 $this->nothing = $nothing;
798 $this->formid = $formid;
799 $this->showbutton = $showbutton;
803 * Adds help icon.
804 * @param string $page The keyword that defines a help page
805 * @param string $title A descriptive text for accessibility only
806 * @param string $component
807 * @param bool $linktext add extra text to icon
808 * @return void
810 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
811 $this->helpicon = new old_help_icon($helppage, $title, $component);
815 * Adds help icon.
816 * @param string $identifier The keyword that defines a help page
817 * @param string $component
818 * @param bool $linktext add extra text to icon
819 * @return void
821 public function set_help_icon($identifier, $component = 'moodle') {
822 $this->helpicon = new help_icon($identifier, $component);
826 * Sets select's label
827 * @param string $label
828 * @return void
830 public function set_label($label) {
831 $this->label = $label;
837 * Data structure describing html link with special action attached.
838 * @copyright 2010 Petr Skoda
839 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
840 * @since Moodle 2.0
842 class action_link implements renderable {
844 * Href url
845 * @var moodle_url
847 var $url;
849 * Link text
850 * @var string HTML fragment
852 var $text;
854 * HTML attributes
855 * @var array
857 var $attributes;
859 * List of actions attached to link
860 * @var array of component_action
862 var $actions;
865 * Constructor
866 * @param string|moodle_url $url
867 * @param string $text HTML fragment
868 * @param component_action $action
869 * @param array $attributes associative array of html link attributes + disabled
871 public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null) {
872 $this->url = clone($url);
873 $this->text = $text;
874 $this->attributes = (array)$attributes;
875 if ($action) {
876 $this->add_action($action);
881 * Add action to the link.
882 * @param component_action $action
883 * @return void
885 public function add_action(component_action $action) {
886 $this->actions[] = $action;
889 public function add_class($class) {
890 if (empty($this->attributes['class'])) {
891 $this->attributes['class'] = $class;
892 } else {
893 $this->attributes['class'] .= ' ' . $class;
898 // ==== HTML writer and helper classes, will be probably moved elsewhere ======
901 * Simple html output class
902 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
904 class html_writer {
906 * Outputs a tag with attributes and contents
907 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
908 * @param string $contents What goes between the opening and closing tags
909 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
910 * @return string HTML fragment
912 public static function tag($tagname, $contents, array $attributes = null) {
913 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
917 * Outputs an opening tag with attributes
918 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
919 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
920 * @return string HTML fragment
922 public static function start_tag($tagname, array $attributes = null) {
923 return '<' . $tagname . self::attributes($attributes) . '>';
927 * Outputs a closing tag
928 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
929 * @return string HTML fragment
931 public static function end_tag($tagname) {
932 return '</' . $tagname . '>';
936 * Outputs an empty tag with attributes
937 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
938 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
939 * @return string HTML fragment
941 public static function empty_tag($tagname, array $attributes = null) {
942 return '<' . $tagname . self::attributes($attributes) . ' />';
946 * Outputs a tag, but only if the contents are not empty
947 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
948 * @param string $contents What goes between the opening and closing tags
949 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
950 * @return string HTML fragment
952 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
953 if ($contents === '' || is_null($contents)) {
954 return '';
956 return self::tag($tagname, $contents, $attributes);
960 * Outputs a HTML attribute and value
961 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
962 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
963 * @return string HTML fragment
965 public static function attribute($name, $value) {
966 if (is_array($value)) {
967 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
969 if ($value instanceof moodle_url) {
970 return ' ' . $name . '="' . $value->out() . '"';
973 // special case, we do not want these in output
974 if ($value === null) {
975 return '';
978 // no sloppy trimming here!
979 return ' ' . $name . '="' . s($value) . '"';
983 * Outputs a list of HTML attributes and values
984 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
985 * The values will be escaped with {@link s()}
986 * @return string HTML fragment
988 public static function attributes(array $attributes = null) {
989 $attributes = (array)$attributes;
990 $output = '';
991 foreach ($attributes as $name => $value) {
992 $output .= self::attribute($name, $value);
994 return $output;
998 * Generates random html element id.
999 * @param string $base
1000 * @return string
1002 public static function random_id($base='random') {
1003 return uniqid($base);
1007 * Generates a simple html link
1008 * @param string|moodle_url $url
1009 * @param string $text link txt
1010 * @param array $attributes extra html attributes
1011 * @return string HTML fragment
1013 public static function link($url, $text, array $attributes = null) {
1014 $attributes = (array)$attributes;
1015 $attributes['href'] = $url;
1016 return self::tag('a', $text, $attributes);
1020 * generates a simple checkbox with optional label
1021 * @param string $name
1022 * @param string $value
1023 * @param bool $checked
1024 * @param string $label
1025 * @param array $attributes
1026 * @return string html fragment
1028 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1029 $attributes = (array)$attributes;
1030 $output = '';
1032 if ($label !== '' and !is_null($label)) {
1033 if (empty($attributes['id'])) {
1034 $attributes['id'] = self::random_id('checkbox_');
1037 $attributes['type'] = 'checkbox';
1038 $attributes['value'] = $value;
1039 $attributes['name'] = $name;
1040 $attributes['checked'] = $checked ? 'checked' : null;
1042 $output .= self::empty_tag('input', $attributes);
1044 if ($label !== '' and !is_null($label)) {
1045 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1048 return $output;
1052 * Generates a simple select yes/no form field
1053 * @param string $name name of select element
1054 * @param bool $selected
1055 * @param array $attributes - html select element attributes
1056 * @return string HRML fragment
1058 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1059 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1060 return self::select($options, $name, $selected, null, $attributes);
1064 * Generates a simple select form field
1065 * @param array $options associative array value=>label ex.:
1066 * array(1=>'One, 2=>Two)
1067 * it is also possible to specify optgroup as complex label array ex.:
1068 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1069 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1070 * @param string $name name of select element
1071 * @param string|array $selected value or array of values depending on multiple attribute
1072 * @param array|bool $nothing, add nothing selected option, or false of not added
1073 * @param array $attributes - html select element attributes
1074 * @return string HTML fragment
1076 public static function select(array $options, $name, $selected = '', $nothing = array(''=>'choosedots'), array $attributes = null) {
1077 $attributes = (array)$attributes;
1078 if (is_array($nothing)) {
1079 foreach ($nothing as $k=>$v) {
1080 if ($v === 'choose' or $v === 'choosedots') {
1081 $nothing[$k] = get_string('choosedots');
1084 $options = $nothing + $options; // keep keys, do not override
1086 } else if (is_string($nothing) and $nothing !== '') {
1087 // BC
1088 $options = array(''=>$nothing) + $options;
1091 // we may accept more values if multiple attribute specified
1092 $selected = (array)$selected;
1093 foreach ($selected as $k=>$v) {
1094 $selected[$k] = (string)$v;
1097 if (!isset($attributes['id'])) {
1098 $id = 'menu'.$name;
1099 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1100 $id = str_replace('[', '', $id);
1101 $id = str_replace(']', '', $id);
1102 $attributes['id'] = $id;
1105 if (!isset($attributes['class'])) {
1106 $class = 'menu'.$name;
1107 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1108 $class = str_replace('[', '', $class);
1109 $class = str_replace(']', '', $class);
1110 $attributes['class'] = $class;
1112 $attributes['class'] = 'select ' . $attributes['class']; /// Add 'select' selector always
1114 $attributes['name'] = $name;
1116 if (!empty($attributes['disabled'])) {
1117 $attributes['disabled'] = 'disabled';
1118 } else {
1119 unset($attributes['disabled']);
1122 $output = '';
1123 foreach ($options as $value=>$label) {
1124 if (is_array($label)) {
1125 // ignore key, it just has to be unique
1126 $output .= self::select_optgroup(key($label), current($label), $selected);
1127 } else {
1128 $output .= self::select_option($label, $value, $selected);
1131 return self::tag('select', $output, $attributes);
1134 private static function select_option($label, $value, array $selected) {
1135 $attributes = array();
1136 $value = (string)$value;
1137 if (in_array($value, $selected, true)) {
1138 $attributes['selected'] = 'selected';
1140 $attributes['value'] = $value;
1141 return self::tag('option', $label, $attributes);
1144 private static function select_optgroup($groupname, $options, array $selected) {
1145 if (empty($options)) {
1146 return '';
1148 $attributes = array('label'=>$groupname);
1149 $output = '';
1150 foreach ($options as $value=>$label) {
1151 $output .= self::select_option($label, $value, $selected);
1153 return self::tag('optgroup', $output, $attributes);
1157 * This is a shortcut for making an hour selector menu.
1158 * @param string $type The type of selector (years, months, days, hours, minutes)
1159 * @param string $name fieldname
1160 * @param int $currenttime A default timestamp in GMT
1161 * @param int $step minute spacing
1162 * @param array $attributes - html select element attributes
1163 * @return HTML fragment
1165 public static function select_time($type, $name, $currenttime=0, $step=5, array $attributes=null) {
1166 if (!$currenttime) {
1167 $currenttime = time();
1169 $currentdate = usergetdate($currenttime);
1170 $userdatetype = $type;
1171 $timeunits = array();
1173 switch ($type) {
1174 case 'years':
1175 for ($i=1970; $i<=2020; $i++) {
1176 $timeunits[$i] = $i;
1178 $userdatetype = 'year';
1179 break;
1180 case 'months':
1181 for ($i=1; $i<=12; $i++) {
1182 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1184 $userdatetype = 'month';
1185 $currentdate['month'] = (int)$currentdate['mon'];
1186 break;
1187 case 'days':
1188 for ($i=1; $i<=31; $i++) {
1189 $timeunits[$i] = $i;
1191 $userdatetype = 'mday';
1192 break;
1193 case 'hours':
1194 for ($i=0; $i<=23; $i++) {
1195 $timeunits[$i] = sprintf("%02d",$i);
1197 break;
1198 case 'minutes':
1199 if ($step != 1) {
1200 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1203 for ($i=0; $i<=59; $i+=$step) {
1204 $timeunits[$i] = sprintf("%02d",$i);
1206 break;
1207 default:
1208 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1211 if (empty($attributes['id'])) {
1212 $attributes['id'] = self::random_id('ts_');
1214 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1215 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1217 return $label.$timerselector;
1221 * Shortcut for quick making of lists
1222 * @param array $items
1223 * @param string $tag ul or ol
1224 * @param array $attributes
1225 * @return string
1227 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1228 //note: 'list' is a reserved keyword ;-)
1230 $output = '';
1232 foreach ($items as $item) {
1233 $output .= html_writer::start_tag('li') . "\n";
1234 $output .= $item . "\n";
1235 $output .= html_writer::end_tag('li') . "\n";
1238 return html_writer::tag($tag, $output, $attributes);
1242 * Returns hidden input fields created from url parameters.
1243 * @param moodle_url $url
1244 * @param array $exclude list of excluded parameters
1245 * @return string HTML fragment
1247 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1248 $exclude = (array)$exclude;
1249 $params = $url->params();
1250 foreach ($exclude as $key) {
1251 unset($params[$key]);
1254 $output = '';
1255 foreach ($params as $key => $value) {
1256 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1257 $output .= self::empty_tag('input', $attributes)."\n";
1259 return $output;
1263 * Generate a script tag containing the the specified code.
1265 * @param string $js the JavaScript code
1266 * @param moodle_url|string optional url of the external script, $code ignored if specified
1267 * @return string HTML, the code wrapped in <script> tags.
1269 public static function script($jscode, $url=null) {
1270 if ($jscode) {
1271 $attributes = array('type'=>'text/javascript');
1272 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1274 } else if ($url) {
1275 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1276 return self::tag('script', '', $attributes) . "\n";
1278 } else {
1279 return '';
1284 * Renders HTML table
1286 * This method may modify the passed instance by adding some default properties if they are not set yet.
1287 * If this is not what you want, you should make a full clone of your data before passing them to this
1288 * method. In most cases this is not an issue at all so we do not clone by default for performance
1289 * and memory consumption reasons.
1291 * @param html_table $table data to be rendered
1292 * @return string HTML code
1294 public static function table(html_table $table) {
1295 // prepare table data and populate missing properties with reasonable defaults
1296 if (!empty($table->align)) {
1297 foreach ($table->align as $key => $aa) {
1298 if ($aa) {
1299 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1300 } else {
1301 $table->align[$key] = null;
1305 if (!empty($table->size)) {
1306 foreach ($table->size as $key => $ss) {
1307 if ($ss) {
1308 $table->size[$key] = 'width:'. $ss .';';
1309 } else {
1310 $table->size[$key] = null;
1314 if (!empty($table->wrap)) {
1315 foreach ($table->wrap as $key => $ww) {
1316 if ($ww) {
1317 $table->wrap[$key] = 'white-space:nowrap;';
1318 } else {
1319 $table->wrap[$key] = '';
1323 if (!empty($table->head)) {
1324 foreach ($table->head as $key => $val) {
1325 if (!isset($table->align[$key])) {
1326 $table->align[$key] = null;
1328 if (!isset($table->size[$key])) {
1329 $table->size[$key] = null;
1331 if (!isset($table->wrap[$key])) {
1332 $table->wrap[$key] = null;
1337 if (empty($table->attributes['class'])) {
1338 $table->attributes['class'] = 'generaltable';
1340 if (!empty($table->tablealign)) {
1341 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1344 // explicitly assigned properties override those defined via $table->attributes
1345 $table->attributes['class'] = trim($table->attributes['class']);
1346 $attributes = array_merge($table->attributes, array(
1347 'id' => $table->id,
1348 'width' => $table->width,
1349 'summary' => $table->summary,
1350 'cellpadding' => $table->cellpadding,
1351 'cellspacing' => $table->cellspacing,
1353 $output = html_writer::start_tag('table', $attributes) . "\n";
1355 $countcols = 0;
1357 if (!empty($table->head)) {
1358 $countcols = count($table->head);
1360 $output .= html_writer::start_tag('thead', array()) . "\n";
1361 $output .= html_writer::start_tag('tr', array()) . "\n";
1362 $keys = array_keys($table->head);
1363 $lastkey = end($keys);
1365 foreach ($table->head as $key => $heading) {
1366 // Convert plain string headings into html_table_cell objects
1367 if (!($heading instanceof html_table_cell)) {
1368 $headingtext = $heading;
1369 $heading = new html_table_cell();
1370 $heading->text = $headingtext;
1371 $heading->header = true;
1374 if ($heading->header !== false) {
1375 $heading->header = true;
1378 if ($heading->header && empty($heading->scope)) {
1379 $heading->scope = 'col';
1382 $heading->attributes['class'] .= ' header c' . $key;
1383 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1384 $heading->colspan = $table->headspan[$key];
1385 $countcols += $table->headspan[$key] - 1;
1388 if ($key == $lastkey) {
1389 $heading->attributes['class'] .= ' lastcol';
1391 if (isset($table->colclasses[$key])) {
1392 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1394 $heading->attributes['class'] = trim($heading->attributes['class']);
1395 $attributes = array_merge($heading->attributes, array(
1396 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1397 'scope' => $heading->scope,
1398 'colspan' => $heading->colspan,
1401 $tagtype = 'td';
1402 if ($heading->header === true) {
1403 $tagtype = 'th';
1405 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1407 $output .= html_writer::end_tag('tr') . "\n";
1408 $output .= html_writer::end_tag('thead') . "\n";
1410 if (empty($table->data)) {
1411 // For valid XHTML strict every table must contain either a valid tr
1412 // or a valid tbody... both of which must contain a valid td
1413 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1414 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1415 $output .= html_writer::end_tag('tbody');
1419 if (!empty($table->data)) {
1420 $oddeven = 1;
1421 $keys = array_keys($table->data);
1422 $lastrowkey = end($keys);
1423 $output .= html_writer::start_tag('tbody', array());
1425 foreach ($table->data as $key => $row) {
1426 if (($row === 'hr') && ($countcols)) {
1427 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1428 } else {
1429 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1430 if (!($row instanceof html_table_row)) {
1431 $newrow = new html_table_row();
1433 foreach ($row as $item) {
1434 $cell = new html_table_cell();
1435 $cell->text = $item;
1436 $newrow->cells[] = $cell;
1438 $row = $newrow;
1441 $oddeven = $oddeven ? 0 : 1;
1442 if (isset($table->rowclasses[$key])) {
1443 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1446 $row->attributes['class'] .= ' r' . $oddeven;
1447 if ($key == $lastrowkey) {
1448 $row->attributes['class'] .= ' lastrow';
1451 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1452 $keys2 = array_keys($row->cells);
1453 $lastkey = end($keys2);
1455 $gotlastkey = false; //flag for sanity checking
1456 foreach ($row->cells as $key => $cell) {
1457 if ($gotlastkey) {
1458 //This should never happen. Why do we have a cell after the last cell?
1459 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1462 if (!($cell instanceof html_table_cell)) {
1463 $mycell = new html_table_cell();
1464 $mycell->text = $cell;
1465 $cell = $mycell;
1468 if (($cell->header === true) && empty($cell->scope)) {
1469 $cell->scope = 'row';
1472 if (isset($table->colclasses[$key])) {
1473 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1476 $cell->attributes['class'] .= ' cell c' . $key;
1477 if ($key == $lastkey) {
1478 $cell->attributes['class'] .= ' lastcol';
1479 $gotlastkey = true;
1481 $tdstyle = '';
1482 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1483 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1484 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1485 $cell->attributes['class'] = trim($cell->attributes['class']);
1486 $tdattributes = array_merge($cell->attributes, array(
1487 'style' => $tdstyle . $cell->style,
1488 'colspan' => $cell->colspan,
1489 'rowspan' => $cell->rowspan,
1490 'id' => $cell->id,
1491 'abbr' => $cell->abbr,
1492 'scope' => $cell->scope,
1494 $tagtype = 'td';
1495 if ($cell->header === true) {
1496 $tagtype = 'th';
1498 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1501 $output .= html_writer::end_tag('tr') . "\n";
1503 $output .= html_writer::end_tag('tbody') . "\n";
1505 $output .= html_writer::end_tag('table') . "\n";
1507 return $output;
1511 * Renders form element label
1513 * By default, the label is suffixed with a label separator defined in the
1514 * current language pack (colon by default in the English lang pack).
1515 * Adding the colon can be explicitly disabled if needed. Label separators
1516 * are put outside the label tag itself so they are not read by
1517 * screenreaders (accessibility).
1519 * Parameter $for explicitly associates the label with a form control. When
1520 * set, the value of this attribute must be the same as the value of
1521 * the id attribute of the form control in the same document. When null,
1522 * the label being defined is associated with the control inside the label
1523 * element.
1525 * @param string $text content of the label tag
1526 * @param string|null $for id of the element this label is associated with, null for no association
1527 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1528 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1529 * @return string HTML of the label element
1531 public static function label($text, $for, $colonize=true, array $attributes=array()) {
1532 if (!is_null($for)) {
1533 $attributes = array_merge($attributes, array('for' => $for));
1535 $text = trim($text);
1536 $label = self::tag('label', $text, $attributes);
1539 // TODO $colonize disabled for now yet - see MDL-12192 for details
1540 if (!empty($text) and $colonize) {
1541 // the $text may end with the colon already, though it is bad string definition style
1542 $colon = get_string('labelsep', 'langconfig');
1543 if (!empty($colon)) {
1544 $trimmed = trim($colon);
1545 if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1546 //debugging('The label text should not end with colon or other label separator,
1547 // please fix the string definition.', DEBUG_DEVELOPER);
1548 } else {
1549 $label .= $colon;
1555 return $label;
1559 // ==== JS writer and helper classes, will be probably moved elsewhere ======
1562 * Simple javascript output class
1563 * @copyright 2010 Petr Skoda
1565 class js_writer {
1567 * Returns javascript code calling the function
1568 * @param string $function function name, can be complex like Y.Event.purgeElement
1569 * @param array $arguments parameters
1570 * @param int $delay execution delay in seconds
1571 * @return string JS code fragment
1573 public static function function_call($function, array $arguments = null, $delay=0) {
1574 if ($arguments) {
1575 $arguments = array_map('json_encode', $arguments);
1576 $arguments = implode(', ', $arguments);
1577 } else {
1578 $arguments = '';
1580 $js = "$function($arguments);";
1582 if ($delay) {
1583 $delay = $delay * 1000; // in miliseconds
1584 $js = "setTimeout(function() { $js }, $delay);";
1586 return $js . "\n";
1590 * Special function which adds Y as first argument of fucntion call.
1591 * @param string $function
1592 * @param array $extraarguments
1593 * @return string
1595 public static function function_call_with_Y($function, array $extraarguments = null) {
1596 if ($extraarguments) {
1597 $extraarguments = array_map('json_encode', $extraarguments);
1598 $arguments = 'Y, ' . implode(', ', $extraarguments);
1599 } else {
1600 $arguments = 'Y';
1602 return "$function($arguments);\n";
1606 * Returns JavaScript code to initialise a new object
1607 * @param string|null $var If it is null then no var is assigned the new object
1608 * @param string $class
1609 * @param array $arguments
1610 * @param array $requirements
1611 * @param int $delay
1612 * @return string
1614 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1615 if (is_array($arguments)) {
1616 $arguments = array_map('json_encode', $arguments);
1617 $arguments = implode(', ', $arguments);
1620 if ($var === null) {
1621 $js = "new $class(Y, $arguments);";
1622 } else if (strpos($var, '.')!==false) {
1623 $js = "$var = new $class(Y, $arguments);";
1624 } else {
1625 $js = "var $var = new $class(Y, $arguments);";
1628 if ($delay) {
1629 $delay = $delay * 1000; // in miliseconds
1630 $js = "setTimeout(function() { $js }, $delay);";
1633 if (count($requirements) > 0) {
1634 $requirements = implode("', '", $requirements);
1635 $js = "Y.use('$requirements', function(Y){ $js });";
1637 return $js."\n";
1641 * Returns code setting value to variable
1642 * @param string $name
1643 * @param mixed $value json serialised value
1644 * @param bool $usevar add var definition, ignored for nested properties
1645 * @return string JS code fragment
1647 public static function set_variable($name, $value, $usevar=true) {
1648 $output = '';
1650 if ($usevar) {
1651 if (strpos($name, '.')) {
1652 $output .= '';
1653 } else {
1654 $output .= 'var ';
1658 $output .= "$name = ".json_encode($value).";";
1660 return $output;
1664 * Writes event handler attaching code
1665 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1666 * @param string $event A valid DOM event (click, mousedown, change etc.)
1667 * @param string $function The name of the function to call
1668 * @param array $arguments An optional array of argument parameters to pass to the function
1669 * @return string JS code fragment
1671 public static function event_handler($selector, $event, $function, array $arguments = null) {
1672 $selector = json_encode($selector);
1673 $output = "Y.on('$event', $function, $selector, null";
1674 if (!empty($arguments)) {
1675 $output .= ', ' . json_encode($arguments);
1677 return $output . ");\n";
1682 * Holds all the information required to render a <table> by {@see core_renderer::table()}
1684 * Example of usage:
1685 * $t = new html_table();
1686 * ... // set various properties of the object $t as described below
1687 * echo html_writer::table($t);
1689 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1690 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1691 * @since Moodle 2.0
1693 class html_table {
1695 * @var string value to use for the id attribute of the table
1697 public $id = null;
1699 * @var array attributes of HTML attributes for the <table> element
1701 public $attributes = array();
1703 * For more control over the rendering of the headers, an array of html_table_cell objects
1704 * can be passed instead of an array of strings.
1705 * @var array of headings. The n-th array item is used as a heading of the n-th column.
1707 * Example of usage:
1708 * $t->head = array('Student', 'Grade');
1710 public $head;
1712 * @var array can be used to make a heading span multiple columns
1714 * Example of usage:
1715 * $t->headspan = array(2,1);
1717 * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
1718 * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
1720 public $headspan;
1722 * @var array of column alignments. The value is used as CSS 'text-align' property. Therefore, possible
1723 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1724 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1726 * Examples of usage:
1727 * $t->align = array(null, 'right');
1728 * or
1729 * $t->align[1] = 'right';
1732 public $align;
1734 * @var array of column sizes. The value is used as CSS 'size' property.
1736 * Examples of usage:
1737 * $t->size = array('50%', '50%');
1738 * or
1739 * $t->size[1] = '120px';
1741 public $size;
1743 * @var array of wrapping information. The only possible value is 'nowrap' that sets the
1744 * CSS property 'white-space' to the value 'nowrap' in the given column.
1746 * Example of usage:
1747 * $t->wrap = array(null, 'nowrap');
1749 public $wrap;
1751 * @var array of arrays or html_table_row objects containing the data. Alternatively, if you have
1752 * $head specified, the string 'hr' (for horizontal ruler) can be used
1753 * instead of an array of cells data resulting in a divider rendered.
1755 * Example of usage with array of arrays:
1756 * $row1 = array('Harry Potter', '76 %');
1757 * $row2 = array('Hermione Granger', '100 %');
1758 * $t->data = array($row1, $row2);
1760 * Example with array of html_table_row objects: (used for more fine-grained control)
1761 * $cell1 = new html_table_cell();
1762 * $cell1->text = 'Harry Potter';
1763 * $cell1->colspan = 2;
1764 * $row1 = new html_table_row();
1765 * $row1->cells[] = $cell1;
1766 * $cell2 = new html_table_cell();
1767 * $cell2->text = 'Hermione Granger';
1768 * $cell3 = new html_table_cell();
1769 * $cell3->text = '100 %';
1770 * $row2 = new html_table_row();
1771 * $row2->cells = array($cell2, $cell3);
1772 * $t->data = array($row1, $row2);
1774 public $data;
1776 * @var string width of the table, percentage of the page preferred. Defaults to 80%
1777 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1779 public $width = null;
1781 * @var string alignment the whole table. Can be 'right', 'left' or 'center' (default).
1782 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1784 public $tablealign = null;
1786 * @var int padding on each cell, in pixels
1787 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1789 public $cellpadding = null;
1791 * @var int spacing between cells, in pixels
1792 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1794 public $cellspacing = null;
1796 * @var array classes to add to particular rows, space-separated string.
1797 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1798 * respectively. Class 'lastrow' is added automatically for the last row
1799 * in the table.
1801 * Example of usage:
1802 * $t->rowclasses[9] = 'tenth'
1804 public $rowclasses;
1806 * @var array classes to add to every cell in a particular column,
1807 * space-separated string. Class 'cell' is added automatically by the renderer.
1808 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1809 * respectively. Class 'lastcol' is added automatically for all last cells
1810 * in a row.
1812 * Example of usage:
1813 * $t->colclasses = array(null, 'grade');
1815 public $colclasses;
1817 * @var string description of the contents for screen readers.
1819 public $summary;
1822 * Constructor
1824 public function __construct() {
1825 $this->attributes['class'] = '';
1831 * Component representing a table row.
1833 * @copyright 2009 Nicolas Connault
1834 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1835 * @since Moodle 2.0
1837 class html_table_row {
1839 * @var string value to use for the id attribute of the row
1841 public $id = null;
1843 * @var array $cells Array of html_table_cell objects
1845 public $cells = array();
1847 * @var string $style value to use for the style attribute of the table row
1849 public $style = null;
1851 * @var array attributes of additional HTML attributes for the <tr> element
1853 public $attributes = array();
1856 * Constructor
1857 * @param array $cells
1859 public function __construct(array $cells=null) {
1860 $this->attributes['class'] = '';
1861 $cells = (array)$cells;
1862 foreach ($cells as $cell) {
1863 if ($cell instanceof html_table_cell) {
1864 $this->cells[] = $cell;
1865 } else {
1866 $this->cells[] = new html_table_cell($cell);
1874 * Component representing a table cell.
1876 * @copyright 2009 Nicolas Connault
1877 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1878 * @since Moodle 2.0
1880 class html_table_cell {
1882 * @var string value to use for the id attribute of the cell
1884 public $id = null;
1886 * @var string $text The contents of the cell
1888 public $text;
1890 * @var string $abbr Abbreviated version of the contents of the cell
1892 public $abbr = null;
1894 * @var int $colspan Number of columns this cell should span
1896 public $colspan = null;
1898 * @var int $rowspan Number of rows this cell should span
1900 public $rowspan = null;
1902 * @var string $scope Defines a way to associate header cells and data cells in a table
1904 public $scope = null;
1906 * @var boolean $header Whether or not this cell is a header cell
1908 public $header = null;
1910 * @var string $style value to use for the style attribute of the table cell
1912 public $style = null;
1914 * @var array attributes of additional HTML attributes for the <td> element
1916 public $attributes = array();
1918 public function __construct($text = null) {
1919 $this->text = $text;
1920 $this->attributes['class'] = '';
1925 /// Complex components aggregating simpler components
1929 * Component representing a paging bar.
1931 * @copyright 2009 Nicolas Connault
1932 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1933 * @since Moodle 2.0
1935 class paging_bar implements renderable {
1937 * @var int $maxdisplay The maximum number of pagelinks to display
1939 public $maxdisplay = 18;
1941 * @var int $totalcount post or get
1943 public $totalcount;
1945 * @var int $page The page you are currently viewing
1947 public $page;
1949 * @var int $perpage The number of entries that should be shown per page
1951 public $perpage;
1953 * @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.
1954 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
1956 public $baseurl;
1958 * @var string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
1960 public $pagevar;
1962 * @var string $previouslink A HTML link representing the "previous" page
1964 public $previouslink = null;
1966 * @var tring $nextlink A HTML link representing the "next" page
1968 public $nextlink = null;
1970 * @var tring $firstlink A HTML link representing the first page
1972 public $firstlink = null;
1974 * @var tring $lastlink A HTML link representing the last page
1976 public $lastlink = null;
1978 * @var array $pagelinks An array of strings. One of them is just a string: the current page
1980 public $pagelinks = array();
1983 * Constructor paging_bar with only the required params.
1985 * @param int $totalcount The total number of entries available to be paged through
1986 * @param int $page The page you are currently viewing
1987 * @param int $perpage The number of entries that should be shown per page
1988 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
1989 * @param string $pagevar name of page parameter that holds the page number
1991 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
1992 $this->totalcount = $totalcount;
1993 $this->page = $page;
1994 $this->perpage = $perpage;
1995 $this->baseurl = $baseurl;
1996 $this->pagevar = $pagevar;
2000 * @return void
2002 public function prepare(renderer_base $output, moodle_page $page, $target) {
2003 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2004 throw new coding_exception('paging_bar requires a totalcount value.');
2006 if (!isset($this->page) || is_null($this->page)) {
2007 throw new coding_exception('paging_bar requires a page value.');
2009 if (empty($this->perpage)) {
2010 throw new coding_exception('paging_bar requires a perpage value.');
2012 if (empty($this->baseurl)) {
2013 throw new coding_exception('paging_bar requires a baseurl value.');
2016 if ($this->totalcount > $this->perpage) {
2017 $pagenum = $this->page - 1;
2019 if ($this->page > 0) {
2020 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2023 if ($this->perpage > 0) {
2024 $lastpage = ceil($this->totalcount / $this->perpage);
2025 } else {
2026 $lastpage = 1;
2029 if ($this->page > 15) {
2030 $startpage = $this->page - 10;
2032 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2033 } else {
2034 $startpage = 0;
2037 $currpage = $startpage;
2038 $displaycount = $displaypage = 0;
2040 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2041 $displaypage = $currpage + 1;
2043 if ($this->page == $currpage) {
2044 $this->pagelinks[] = $displaypage;
2045 } else {
2046 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2047 $this->pagelinks[] = $pagelink;
2050 $displaycount++;
2051 $currpage++;
2054 if ($currpage < $lastpage) {
2055 $lastpageactual = $lastpage - 1;
2056 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2059 $pagenum = $this->page + 1;
2061 if ($pagenum != $displaypage) {
2062 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2070 * This class represents how a block appears on a page.
2072 * During output, each block instance is asked to return a block_contents object,
2073 * those are then passed to the $OUTPUT->block function for display.
2075 * {@link $contents} should probably be generated using a moodle_block_..._renderer.
2077 * Other block-like things that need to appear on the page, for example the
2078 * add new block UI, are also represented as block_contents objects.
2080 * @copyright 2009 Tim Hunt
2081 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2082 * @since Moodle 2.0
2084 class block_contents {
2085 /** @var int used to set $skipid. */
2086 protected static $idcounter = 1;
2088 const NOT_HIDEABLE = 0;
2089 const VISIBLE = 1;
2090 const HIDDEN = 2;
2093 * @var integer $skipid All the blocks (or things that look like blocks)
2094 * printed on a page are given a unique number that can be used to construct
2095 * id="" attributes. This is set automatically be the {@link prepare()} method.
2096 * Do not try to set it manually.
2098 public $skipid;
2101 * @var integer If this is the contents of a real block, this should be set to
2102 * the block_instance.id. Otherwise this should be set to 0.
2104 public $blockinstanceid = 0;
2107 * @var integer if this is a real block instance, and there is a corresponding
2108 * block_position.id for the block on this page, this should be set to that id.
2109 * Otherwise it should be 0.
2111 public $blockpositionid = 0;
2114 * @param array $attributes an array of attribute => value pairs that are put on the
2115 * outer div of this block. {@link $id} and {@link $classes} attributes should be set separately.
2117 public $attributes;
2120 * @param string $title The title of this block. If this came from user input,
2121 * it should already have had format_string() processing done on it. This will
2122 * be output inside <h2> tags. Please do not cause invalid XHTML.
2124 public $title = '';
2127 * @param string $content HTML for the content
2129 public $content = '';
2132 * @param array $list an alternative to $content, it you want a list of things with optional icons.
2134 public $footer = '';
2137 * Any small print that should appear under the block to explain to the
2138 * teacher about the block, for example 'This is a sticky block that was
2139 * added in the system context.'
2140 * @var string
2142 public $annotation = '';
2145 * @var integer one of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2146 * the user can toggle whether this block is visible.
2148 public $collapsible = self::NOT_HIDEABLE;
2151 * A (possibly empty) array of editing controls. Each element of this array
2152 * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2153 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2154 * @var array
2156 public $controls = array();
2160 * Create new instance of block content
2161 * @param array $attributes
2163 public function __construct(array $attributes=null) {
2164 $this->skipid = self::$idcounter;
2165 self::$idcounter += 1;
2167 if ($attributes) {
2168 // standard block
2169 $this->attributes = $attributes;
2170 } else {
2171 // simple "fake" blocks used in some modules and "Add new block" block
2172 $this->attributes = array('class'=>'block');
2177 * Add html class to block
2178 * @param string $class
2179 * @return void
2181 public function add_class($class) {
2182 $this->attributes['class'] .= ' '.$class;
2188 * This class represents a target for where a block can go when it is being moved.
2190 * This needs to be rendered as a form with the given hidden from fields, and
2191 * clicking anywhere in the form should submit it. The form action should be
2192 * $PAGE->url.
2194 * @copyright 2009 Tim Hunt
2195 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2196 * @since Moodle 2.0
2198 class block_move_target {
2200 * Move url
2201 * @var moodle_url
2203 public $url;
2205 * label
2206 * @var string
2208 public $text;
2211 * Constructor
2212 * @param string $text
2213 * @param moodle_url $url
2215 public function __construct($text, moodle_url $url) {
2216 $this->text = $text;
2217 $this->url = $url;
2222 * Custom menu item
2224 * This class is used to represent one item within a custom menu that may or may
2225 * not have children.
2227 * @copyright 2010 Sam Hemelryk
2228 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2229 * @since Moodle 2.0
2231 class custom_menu_item implements renderable {
2233 * The text to show for the item
2234 * @var string
2236 protected $text;
2238 * The link to give the icon if it has no children
2239 * @var moodle_url
2241 protected $url;
2243 * A title to apply to the item. By default the text
2244 * @var string
2246 protected $title;
2248 * A sort order for the item, not necessary if you order things in the CFG var
2249 * @var int
2251 protected $sort;
2253 * A reference to the parent for this item or NULL if it is a top level item
2254 * @var custom_menu_item
2256 protected $parent;
2258 * A array in which to store children this item has.
2259 * @var array
2261 protected $children = array();
2263 * A reference to the sort var of the last child that was added
2264 * @var int
2266 protected $lastsort = 0;
2268 * Constructs the new custom menu item
2270 * @param string $text
2271 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2272 * @param string $title A title to apply to this item [Optional]
2273 * @param int $sort A sort or to use if we need to sort differently [Optional]
2274 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2275 * belongs to, only if the child has a parent. [Optional]
2277 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent=null) {
2278 $this->text = $text;
2279 $this->url = $url;
2280 $this->title = $title;
2281 $this->sort = (int)$sort;
2282 $this->parent = $parent;
2286 * Adds a custom menu item as a child of this node given its properties.
2288 * @param string $text
2289 * @param moodle_url $url
2290 * @param string $title
2291 * @param int $sort
2292 * @return custom_menu_item
2294 public function add($text, moodle_url $url=null, $title=null, $sort = null) {
2295 $key = count($this->children);
2296 if (empty($sort)) {
2297 $sort = $this->lastsort + 1;
2299 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2300 $this->lastsort = (int)$sort;
2301 return $this->children[$key];
2304 * Returns the text for this item
2305 * @return string
2307 public function get_text() {
2308 return $this->text;
2311 * Returns the url for this item
2312 * @return moodle_url
2314 public function get_url() {
2315 return $this->url;
2318 * Returns the title for this item
2319 * @return string
2321 public function get_title() {
2322 return $this->title;
2325 * Sorts and returns the children for this item
2326 * @return array
2328 public function get_children() {
2329 $this->sort();
2330 return $this->children;
2333 * Gets the sort order for this child
2334 * @return int
2336 public function get_sort_order() {
2337 return $this->sort;
2340 * Gets the parent this child belong to
2341 * @return custom_menu_item
2343 public function get_parent() {
2344 return $this->parent;
2347 * Sorts the children this item has
2349 public function sort() {
2350 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2353 * Returns true if this item has any children
2354 * @return bool
2356 public function has_children() {
2357 return (count($this->children) > 0);
2361 * Sets the text for the node
2362 * @param string $text
2364 public function set_text($text) {
2365 $this->text = (string)$text;
2369 * Sets the title for the node
2370 * @param string $title
2372 public function set_title($title) {
2373 $this->title = (string)$title;
2377 * Sets the url for the node
2378 * @param moodle_url $url
2380 public function set_url(moodle_url $url) {
2381 $this->url = $url;
2386 * Custom menu class
2388 * This class is used to operate a custom menu that can be rendered for the page.
2389 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2390 * of custom_menu_item nodes that can be rendered by the core renderer.
2392 * To configure the custom menu:
2393 * Settings: Administration > Appearance > Themes > Theme settings
2395 * @copyright 2010 Sam Hemelryk
2396 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2397 * @since Moodle 2.0
2399 class custom_menu extends custom_menu_item {
2401 /** @var string the language we should render for, null disables multilang support */
2402 protected $currentlanguage = null;
2405 * Creates the custom menu
2407 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2408 * @param string $language the current language code, null disables multilang support
2410 public function __construct($definition = '', $currentlanguage = null) {
2412 $this->currentlanguage = $currentlanguage;
2413 parent::__construct('root'); // create virtual root element of the menu
2414 if (!empty($definition)) {
2415 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2420 * Overrides the children of this custom menu. Useful when getting children
2421 * from $CFG->custommenuitems
2423 public function override_children(array $children) {
2424 $this->children = array();
2425 foreach ($children as $child) {
2426 if ($child instanceof custom_menu_item) {
2427 $this->children[] = $child;
2433 * Converts a string into a structured array of custom_menu_items which can
2434 * then be added to a custom menu.
2436 * Structure:
2437 * text|url|title|langs
2438 * The number of hyphens at the start determines the depth of the item. The
2439 * languages are optional, comma separated list of languages the line is for.
2441 * Example structure:
2442 * First level first item|http://www.moodle.com/
2443 * -Second level first item|http://www.moodle.com/partners/
2444 * -Second level second item|http://www.moodle.com/hq/
2445 * --Third level first item|http://www.moodle.com/jobs/
2446 * -Second level third item|http://www.moodle.com/development/
2447 * First level second item|http://www.moodle.com/feedback/
2448 * First level third item
2449 * English only|http://moodle.com|English only item|en
2450 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2453 * @static
2454 * @param string $text the menu items definition
2455 * @param string $language the language code, null disables multilang support
2456 * @return array
2458 public static function convert_text_to_menu_nodes($text, $language = null) {
2459 $lines = explode("\n", $text);
2460 $children = array();
2461 $lastchild = null;
2462 $lastdepth = null;
2463 $lastsort = 0;
2464 foreach ($lines as $line) {
2465 $line = trim($line);
2466 $bits = explode('|', $line, 4); // name|url|title|langs
2467 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2468 // Every item must have a name to be valid
2469 continue;
2470 } else {
2471 $bits[0] = ltrim($bits[0],'-');
2473 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2474 // Set the url to null
2475 $bits[1] = null;
2476 } else {
2477 // Make sure the url is a moodle url
2478 $bits[1] = new moodle_url(trim($bits[1]));
2480 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2481 // Set the title to null seeing as there isn't one
2482 $bits[2] = $bits[0];
2484 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2485 // The item is valid for all languages
2486 $itemlangs = null;
2487 } else {
2488 $itemlangs = array_map('trim', explode(',', $bits[3]));
2490 if (!empty($language) and !empty($itemlangs)) {
2491 // check that the item is intended for the current language
2492 if (!in_array($language, $itemlangs)) {
2493 continue;
2496 // Set an incremental sort order to keep it simple.
2497 $lastsort++;
2498 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2499 $depth = strlen($match[1]);
2500 if ($depth < $lastdepth) {
2501 $difference = $lastdepth - $depth;
2502 if ($lastdepth > 1 && $lastdepth != $difference) {
2503 $tempchild = $lastchild->get_parent();
2504 for ($i =0; $i < $difference; $i++) {
2505 $tempchild = $tempchild->get_parent();
2507 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2508 } else {
2509 $depth = 0;
2510 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2511 $children[] = $lastchild;
2513 } else if ($depth > $lastdepth) {
2514 $depth = $lastdepth + 1;
2515 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2516 } else {
2517 if ($depth == 0) {
2518 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2519 $children[] = $lastchild;
2520 } else {
2521 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2524 } else {
2525 $depth = 0;
2526 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2527 $children[] = $lastchild;
2529 $lastdepth = $depth;
2531 return $children;
2535 * Sorts two custom menu items
2537 * This function is designed to be used with the usort method
2538 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2540 * @param custom_menu_item $itema
2541 * @param custom_menu_item $itemb
2542 * @return int
2544 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2545 $itema = $itema->get_sort_order();
2546 $itemb = $itemb->get_sort_order();
2547 if ($itema == $itemb) {
2548 return 0;
2550 return ($itema > $itemb) ? +1 : -1;