Merge branch 'MDL-29569' of git://github.com/rwijaya/moodle
[moodle.git] / lib / outputcomponents.php
blob3a1dc0794ba33c7496bdd7918f0505ca566d3de0
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, $FULLME;
275 if (is_null($renderer)) {
276 $renderer = $page->get_renderer('core');
279 if (!empty($CFG->forcelogin) and !isloggedin()) {
280 // protect images if login required and not logged in;
281 // do not use require_login() because it is expensive and not suitable here anyway
282 return $renderer->pix_url('u/f1');
285 // Sort out the filename and size. Size is only required for the gravatar
286 // implementation presently.
287 if (empty($this->size)) {
288 $filename = 'f2';
289 $size = 35;
290 } else if ($this->size === true or $this->size == 1) {
291 $filename = 'f1';
292 $size = 100;
293 } else if ($this->size >= 50) {
294 $filename = 'f1';
295 $size = (int)$this->size;
296 } else {
297 $filename = 'f2';
298 $size = (int)$this->size;
301 // First we need to determine whether the user has uploaded a profile
302 // picture of not.
303 $fs = get_file_storage();
304 $context = get_context_instance(CONTEXT_USER, $this->user->id);
305 $hasuploadedfile = ($fs->file_exists($context->id, 'user', 'icon', 0, '/', $filename.'/.png') || $fs->file_exists($context->id, 'user', 'icon', 0, '/', $filename.'/.jpg'));
307 $imageurl = $renderer->pix_url('u/'.$filename);
308 if ($hasuploadedfile && $this->user->picture == 1) {
309 $path = '/';
310 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
311 // We append the theme name to the file path if we have it so that
312 // in the circumstance that the profile picture is not available
313 // when the user actually requests it they still get the profile
314 // picture for the correct theme.
315 $path .= $page->theme->name.'/';
317 // Set the image URL to the URL for the uploaded file.
318 $imageurl = moodle_url::make_pluginfile_url($context->id, 'user', 'icon', NULL, $path, $filename);
319 } else if (!empty($CFG->enablegravatar)) {
320 // Normalise the size variable to acceptable bounds
321 if ($size < 1 || $size > 512) {
322 $size = 35;
324 // Hash the users email address
325 $md5 = md5(strtolower(trim($this->user->email)));
326 // Build a gravatar URL with what we know.
327 // If the currently requested page is https then we'll return an
328 // https gravatar page.
329 if (strpos($FULLME, 'https://') === 0) {
330 $imageurl = new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $imageurl->out(false)));
331 } else {
332 $imageurl = new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $imageurl->out(false)));
336 // Return the URL that has been generated.
337 return $imageurl;
342 * Data structure representing a help icon.
344 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
345 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
346 * @since Moodle 2.0
348 class old_help_icon implements renderable {
350 * @var string $helpidentifier lang pack identifier
352 public $helpidentifier;
354 * @var string $title A descriptive text for title tooltip
356 public $title = null;
358 * @var string $component Component name, the same as in get_string()
360 public $component = 'moodle';
362 * @var string $linktext Extra descriptive text next to the icon
364 public $linktext = null;
367 * Constructor: sets up the other components in case they are needed
368 * @param string $helpidentifier The keyword that defines a help page
369 * @param string $title A descriptive text for accessibility only
370 * @param string $component
371 * @param bool $linktext add extra text to icon
372 * @return void
374 public function __construct($helpidentifier, $title, $component = 'moodle') {
375 if (empty($title)) {
376 throw new coding_exception('A help_icon object requires a $text parameter');
378 if (empty($helpidentifier)) {
379 throw new coding_exception('A help_icon object requires a $helpidentifier parameter');
382 $this->helpidentifier = $helpidentifier;
383 $this->title = $title;
384 $this->component = $component;
389 * Data structure representing a help icon.
391 * @copyright 2010 Petr Skoda (info@skodak.org)
392 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
393 * @since Moodle 2.0
395 class help_icon implements renderable {
397 * @var string $identifier lang pack identifier (without the "_help" suffix),
398 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
399 * must exist.
401 public $identifier;
403 * @var string $component Component name, the same as in get_string()
405 public $component;
407 * @var string $linktext Extra descriptive text next to the icon
409 public $linktext = null;
412 * Constructor
413 * @param string $identifier string for help page title,
414 * string with _help suffix is used for the actual help text.
415 * string with _link suffix is used to create a link to further info (if it exists)
416 * @param string $component
418 public function __construct($identifier, $component) {
419 $this->identifier = $identifier;
420 $this->component = $component;
424 * Verifies that both help strings exists, shows debug warnings if not
426 public function diag_strings() {
427 $sm = get_string_manager();
428 if (!$sm->string_exists($this->identifier, $this->component)) {
429 debugging("Help title string does not exist: [$this->identifier, $this->component]");
431 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
432 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
439 * Data structure representing an icon.
441 * @copyright 2010 Petr Skoda
442 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
443 * @since Moodle 2.0
445 class pix_icon implements renderable {
446 var $pix;
447 var $component;
448 var $attributes = array();
451 * Constructor
452 * @param string $pix short icon name
453 * @param string $alt The alt text to use for the icon
454 * @param string $component component name
455 * @param array $attributes html attributes
457 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
458 $this->pix = $pix;
459 $this->component = $component;
460 $this->attributes = (array)$attributes;
462 $this->attributes['alt'] = $alt;
463 if (empty($this->attributes['class'])) {
464 $this->attributes['class'] = 'smallicon';
466 if (!isset($this->attributes['title'])) {
467 $this->attributes['title'] = $this->attributes['alt'];
473 * Data structure representing an emoticon image
475 * @since Moodle 2.0
477 class pix_emoticon extends pix_icon implements renderable {
480 * Constructor
481 * @param string $pix short icon name
482 * @param string $alt alternative text
483 * @param string $component emoticon image provider
484 * @param array $attributes explicit HTML attributes
486 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
487 if (empty($attributes['class'])) {
488 $attributes['class'] = 'emoticon';
490 parent::__construct($pix, $alt, $component, $attributes);
495 * Data structure representing a simple form with only one button.
497 * @copyright 2009 Petr Skoda
498 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
499 * @since Moodle 2.0
501 class single_button implements renderable {
503 * Target url
504 * @var moodle_url
506 var $url;
508 * Button label
509 * @var string
511 var $label;
513 * Form submit method
514 * @var string post or get
516 var $method = 'post';
518 * Wrapping div class
519 * @var string
520 * */
521 var $class = 'singlebutton';
523 * True if button disabled, false if normal
524 * @var boolean
526 var $disabled = false;
528 * Button tooltip
529 * @var string
531 var $tooltip = null;
533 * Form id
534 * @var string
536 var $formid;
538 * List of attached actions
539 * @var array of component_action
541 var $actions = array();
544 * Constructor
545 * @param string|moodle_url $url
546 * @param string $label button text
547 * @param string $method get or post submit method
549 public function __construct(moodle_url $url, $label, $method='post') {
550 $this->url = clone($url);
551 $this->label = $label;
552 $this->method = $method;
556 * Shortcut for adding a JS confirm dialog when the button is clicked.
557 * The message must be a yes/no question.
558 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
559 * @return void
561 public function add_confirm_action($confirmmessage) {
562 $this->add_action(new confirm_action($confirmmessage));
566 * Add action to the button.
567 * @param component_action $action
568 * @return void
570 public function add_action(component_action $action) {
571 $this->actions[] = $action;
577 * Simple form with just one select field that gets submitted automatically.
578 * If JS not enabled small go button is printed too.
580 * @copyright 2009 Petr Skoda
581 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
582 * @since Moodle 2.0
584 class single_select implements renderable {
586 * Target url - includes hidden fields
587 * @var moodle_url
589 var $url;
591 * Name of the select element.
592 * @var string
594 var $name;
596 * @var array $options associative array value=>label ex.:
597 * array(1=>'One, 2=>Two)
598 * it is also possible to specify optgroup as complex label array ex.:
599 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
600 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
602 var $options;
604 * Selected option
605 * @var string
607 var $selected;
609 * Nothing selected
610 * @var array
612 var $nothing;
614 * Extra select field attributes
615 * @var array
617 var $attributes = array();
619 * Button label
620 * @var string
622 var $label = '';
624 * Form submit method
625 * @var string post or get
627 var $method = 'get';
629 * Wrapping div class
630 * @var string
631 * */
632 var $class = 'singleselect';
634 * True if button disabled, false if normal
635 * @var boolean
637 var $disabled = false;
639 * Button tooltip
640 * @var string
642 var $tooltip = null;
644 * Form id
645 * @var string
647 var $formid = null;
649 * List of attached actions
650 * @var array of component_action
652 var $helpicon = null;
654 * Constructor
655 * @param moodle_url $url form action target, includes hidden fields
656 * @param string $name name of selection field - the changing parameter in url
657 * @param array $options list of options
658 * @param string $selected selected element
659 * @param array $nothing
660 * @param string $formid
662 public function __construct(moodle_url $url, $name, array $options, $selected='', $nothing=array(''=>'choosedots'), $formid=null) {
663 $this->url = $url;
664 $this->name = $name;
665 $this->options = $options;
666 $this->selected = $selected;
667 $this->nothing = $nothing;
668 $this->formid = $formid;
672 * Shortcut for adding a JS confirm dialog when the button is clicked.
673 * The message must be a yes/no question.
674 * @param string $message The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
675 * @return void
677 public function add_confirm_action($confirmmessage) {
678 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
682 * Add action to the button.
683 * @param component_action $action
684 * @return void
686 public function add_action(component_action $action) {
687 $this->actions[] = $action;
691 * Adds help icon.
692 * @param string $page The keyword that defines a help page
693 * @param string $title A descriptive text for accessibility only
694 * @param string $component
695 * @param bool $linktext add extra text to icon
696 * @return void
698 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
699 $this->helpicon = new old_help_icon($helppage, $title, $component);
703 * Adds help icon.
704 * @param string $identifier The keyword that defines a help page
705 * @param string $component
706 * @param bool $linktext add extra text to icon
707 * @return void
709 public function set_help_icon($identifier, $component = 'moodle') {
710 $this->helpicon = new help_icon($identifier, $component);
714 * Sets select's label
715 * @param string $label
716 * @return void
718 public function set_label($label) {
719 $this->label = $label;
725 * Simple URL selection widget description.
726 * @copyright 2009 Petr Skoda
727 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
728 * @since Moodle 2.0
730 class url_select implements renderable {
732 * @var array $urls associative array value=>label ex.:
733 * array(1=>'One, 2=>Two)
734 * it is also possible to specify optgroup as complex label array ex.:
735 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
736 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
738 var $urls;
740 * Selected option
741 * @var string
743 var $selected;
745 * Nothing selected
746 * @var array
748 var $nothing;
750 * Extra select field attributes
751 * @var array
753 var $attributes = array();
755 * Button label
756 * @var string
758 var $label = '';
760 * Wrapping div class
761 * @var string
762 * */
763 var $class = 'urlselect';
765 * True if button disabled, false if normal
766 * @var boolean
768 var $disabled = false;
770 * Button tooltip
771 * @var string
773 var $tooltip = null;
775 * Form id
776 * @var string
778 var $formid = null;
780 * List of attached actions
781 * @var array of component_action
783 var $helpicon = null;
785 * @var string If set, makes button visible with given name for button
787 var $showbutton = null;
789 * Constructor
790 * @param array $urls list of options
791 * @param string $selected selected element
792 * @param array $nothing
793 * @param string $formid
794 * @param string $showbutton Set to text of button if it should be visible
795 * or null if it should be hidden (hidden version always has text 'go')
797 public function __construct(array $urls, $selected='', $nothing=array(''=>'choosedots'),
798 $formid=null, $showbutton=null) {
799 $this->urls = $urls;
800 $this->selected = $selected;
801 $this->nothing = $nothing;
802 $this->formid = $formid;
803 $this->showbutton = $showbutton;
807 * Adds help icon.
808 * @param string $page The keyword that defines a help page
809 * @param string $title A descriptive text for accessibility only
810 * @param string $component
811 * @param bool $linktext add extra text to icon
812 * @return void
814 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
815 $this->helpicon = new old_help_icon($helppage, $title, $component);
819 * Adds help icon.
820 * @param string $identifier The keyword that defines a help page
821 * @param string $component
822 * @param bool $linktext add extra text to icon
823 * @return void
825 public function set_help_icon($identifier, $component = 'moodle') {
826 $this->helpicon = new help_icon($identifier, $component);
830 * Sets select's label
831 * @param string $label
832 * @return void
834 public function set_label($label) {
835 $this->label = $label;
841 * Data structure describing html link with special action attached.
842 * @copyright 2010 Petr Skoda
843 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
844 * @since Moodle 2.0
846 class action_link implements renderable {
848 * Href url
849 * @var moodle_url
851 var $url;
853 * Link text
854 * @var string HTML fragment
856 var $text;
858 * HTML attributes
859 * @var array
861 var $attributes;
863 * List of actions attached to link
864 * @var array of component_action
866 var $actions;
869 * Constructor
870 * @param string|moodle_url $url
871 * @param string $text HTML fragment
872 * @param component_action $action
873 * @param array $attributes associative array of html link attributes + disabled
875 public function __construct(moodle_url $url, $text, component_action $action=null, array $attributes=null) {
876 $this->url = clone($url);
877 $this->text = $text;
878 $this->attributes = (array)$attributes;
879 if ($action) {
880 $this->add_action($action);
885 * Add action to the link.
886 * @param component_action $action
887 * @return void
889 public function add_action(component_action $action) {
890 $this->actions[] = $action;
893 public function add_class($class) {
894 if (empty($this->attributes['class'])) {
895 $this->attributes['class'] = $class;
896 } else {
897 $this->attributes['class'] .= ' ' . $class;
902 // ==== HTML writer and helper classes, will be probably moved elsewhere ======
905 * Simple html output class
906 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
908 class html_writer {
910 * Outputs a tag with attributes and contents
911 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
912 * @param string $contents What goes between the opening and closing tags
913 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
914 * @return string HTML fragment
916 public static function tag($tagname, $contents, array $attributes = null) {
917 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
921 * Outputs an opening tag with attributes
922 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
923 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
924 * @return string HTML fragment
926 public static function start_tag($tagname, array $attributes = null) {
927 return '<' . $tagname . self::attributes($attributes) . '>';
931 * Outputs a closing tag
932 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
933 * @return string HTML fragment
935 public static function end_tag($tagname) {
936 return '</' . $tagname . '>';
940 * Outputs an empty tag with attributes
941 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
942 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
943 * @return string HTML fragment
945 public static function empty_tag($tagname, array $attributes = null) {
946 return '<' . $tagname . self::attributes($attributes) . ' />';
950 * Outputs a tag, but only if the contents are not empty
951 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
952 * @param string $contents What goes between the opening and closing tags
953 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
954 * @return string HTML fragment
956 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
957 if ($contents === '' || is_null($contents)) {
958 return '';
960 return self::tag($tagname, $contents, $attributes);
964 * Outputs a HTML attribute and value
965 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
966 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
967 * @return string HTML fragment
969 public static function attribute($name, $value) {
970 if (is_array($value)) {
971 debugging("Passed an array for the HTML attribute $name", DEBUG_DEVELOPER);
973 if ($value instanceof moodle_url) {
974 return ' ' . $name . '="' . $value->out() . '"';
977 // special case, we do not want these in output
978 if ($value === null) {
979 return '';
982 // no sloppy trimming here!
983 return ' ' . $name . '="' . s($value) . '"';
987 * Outputs a list of HTML attributes and values
988 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
989 * The values will be escaped with {@link s()}
990 * @return string HTML fragment
992 public static function attributes(array $attributes = null) {
993 $attributes = (array)$attributes;
994 $output = '';
995 foreach ($attributes as $name => $value) {
996 $output .= self::attribute($name, $value);
998 return $output;
1002 * Generates random html element id.
1003 * @param string $base
1004 * @return string
1006 public static function random_id($base='random') {
1007 static $counter = 0;
1008 static $uniq;
1010 if (!isset($uniq)) {
1011 $uniq = uniqid();
1014 $counter++;
1015 return $base.$uniq.$counter;
1019 * Generates a simple html link
1020 * @param string|moodle_url $url
1021 * @param string $text link txt
1022 * @param array $attributes extra html attributes
1023 * @return string HTML fragment
1025 public static function link($url, $text, array $attributes = null) {
1026 $attributes = (array)$attributes;
1027 $attributes['href'] = $url;
1028 return self::tag('a', $text, $attributes);
1032 * generates a simple checkbox with optional label
1033 * @param string $name
1034 * @param string $value
1035 * @param bool $checked
1036 * @param string $label
1037 * @param array $attributes
1038 * @return string html fragment
1040 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1041 $attributes = (array)$attributes;
1042 $output = '';
1044 if ($label !== '' and !is_null($label)) {
1045 if (empty($attributes['id'])) {
1046 $attributes['id'] = self::random_id('checkbox_');
1049 $attributes['type'] = 'checkbox';
1050 $attributes['value'] = $value;
1051 $attributes['name'] = $name;
1052 $attributes['checked'] = $checked ? 'checked' : null;
1054 $output .= self::empty_tag('input', $attributes);
1056 if ($label !== '' and !is_null($label)) {
1057 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1060 return $output;
1064 * Generates a simple select yes/no form field
1065 * @param string $name name of select element
1066 * @param bool $selected
1067 * @param array $attributes - html select element attributes
1068 * @return string HRML fragment
1070 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1071 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1072 return self::select($options, $name, $selected, null, $attributes);
1076 * Generates a simple select form field
1077 * @param array $options associative array value=>label ex.:
1078 * array(1=>'One, 2=>Two)
1079 * it is also possible to specify optgroup as complex label array ex.:
1080 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1081 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1082 * @param string $name name of select element
1083 * @param string|array $selected value or array of values depending on multiple attribute
1084 * @param array|bool $nothing, add nothing selected option, or false of not added
1085 * @param array $attributes - html select element attributes
1086 * @return string HTML fragment
1088 public static function select(array $options, $name, $selected = '', $nothing = array(''=>'choosedots'), array $attributes = null) {
1089 $attributes = (array)$attributes;
1090 if (is_array($nothing)) {
1091 foreach ($nothing as $k=>$v) {
1092 if ($v === 'choose' or $v === 'choosedots') {
1093 $nothing[$k] = get_string('choosedots');
1096 $options = $nothing + $options; // keep keys, do not override
1098 } else if (is_string($nothing) and $nothing !== '') {
1099 // BC
1100 $options = array(''=>$nothing) + $options;
1103 // we may accept more values if multiple attribute specified
1104 $selected = (array)$selected;
1105 foreach ($selected as $k=>$v) {
1106 $selected[$k] = (string)$v;
1109 if (!isset($attributes['id'])) {
1110 $id = 'menu'.$name;
1111 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1112 $id = str_replace('[', '', $id);
1113 $id = str_replace(']', '', $id);
1114 $attributes['id'] = $id;
1117 if (!isset($attributes['class'])) {
1118 $class = 'menu'.$name;
1119 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1120 $class = str_replace('[', '', $class);
1121 $class = str_replace(']', '', $class);
1122 $attributes['class'] = $class;
1124 $attributes['class'] = 'select ' . $attributes['class']; /// Add 'select' selector always
1126 $attributes['name'] = $name;
1128 if (!empty($attributes['disabled'])) {
1129 $attributes['disabled'] = 'disabled';
1130 } else {
1131 unset($attributes['disabled']);
1134 $output = '';
1135 foreach ($options as $value=>$label) {
1136 if (is_array($label)) {
1137 // ignore key, it just has to be unique
1138 $output .= self::select_optgroup(key($label), current($label), $selected);
1139 } else {
1140 $output .= self::select_option($label, $value, $selected);
1143 return self::tag('select', $output, $attributes);
1146 private static function select_option($label, $value, array $selected) {
1147 $attributes = array();
1148 $value = (string)$value;
1149 if (in_array($value, $selected, true)) {
1150 $attributes['selected'] = 'selected';
1152 $attributes['value'] = $value;
1153 return self::tag('option', $label, $attributes);
1156 private static function select_optgroup($groupname, $options, array $selected) {
1157 if (empty($options)) {
1158 return '';
1160 $attributes = array('label'=>$groupname);
1161 $output = '';
1162 foreach ($options as $value=>$label) {
1163 $output .= self::select_option($label, $value, $selected);
1165 return self::tag('optgroup', $output, $attributes);
1169 * This is a shortcut for making an hour selector menu.
1170 * @param string $type The type of selector (years, months, days, hours, minutes)
1171 * @param string $name fieldname
1172 * @param int $currenttime A default timestamp in GMT
1173 * @param int $step minute spacing
1174 * @param array $attributes - html select element attributes
1175 * @return HTML fragment
1177 public static function select_time($type, $name, $currenttime=0, $step=5, array $attributes=null) {
1178 if (!$currenttime) {
1179 $currenttime = time();
1181 $currentdate = usergetdate($currenttime);
1182 $userdatetype = $type;
1183 $timeunits = array();
1185 switch ($type) {
1186 case 'years':
1187 for ($i=1970; $i<=2020; $i++) {
1188 $timeunits[$i] = $i;
1190 $userdatetype = 'year';
1191 break;
1192 case 'months':
1193 for ($i=1; $i<=12; $i++) {
1194 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1196 $userdatetype = 'month';
1197 $currentdate['month'] = $currentdate['mon'];
1198 break;
1199 case 'days':
1200 for ($i=1; $i<=31; $i++) {
1201 $timeunits[$i] = $i;
1203 $userdatetype = 'mday';
1204 break;
1205 case 'hours':
1206 for ($i=0; $i<=23; $i++) {
1207 $timeunits[$i] = sprintf("%02d",$i);
1209 break;
1210 case 'minutes':
1211 if ($step != 1) {
1212 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1215 for ($i=0; $i<=59; $i+=$step) {
1216 $timeunits[$i] = sprintf("%02d",$i);
1218 break;
1219 default:
1220 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1223 if (empty($attributes['id'])) {
1224 $attributes['id'] = self::random_id('ts_');
1226 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1227 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1229 return $label.$timerselector;
1233 * Shortcut for quick making of lists
1234 * @param array $items
1235 * @param string $tag ul or ol
1236 * @param array $attributes
1237 * @return string
1239 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1240 //note: 'list' is a reserved keyword ;-)
1242 $output = '';
1244 foreach ($items as $item) {
1245 $output .= html_writer::start_tag('li') . "\n";
1246 $output .= $item . "\n";
1247 $output .= html_writer::end_tag('li') . "\n";
1250 return html_writer::tag($tag, $output, $attributes);
1254 * Returns hidden input fields created from url parameters.
1255 * @param moodle_url $url
1256 * @param array $exclude list of excluded parameters
1257 * @return string HTML fragment
1259 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1260 $exclude = (array)$exclude;
1261 $params = $url->params();
1262 foreach ($exclude as $key) {
1263 unset($params[$key]);
1266 $output = '';
1267 foreach ($params as $key => $value) {
1268 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1269 $output .= self::empty_tag('input', $attributes)."\n";
1271 return $output;
1275 * Generate a script tag containing the the specified code.
1277 * @param string $js the JavaScript code
1278 * @param moodle_url|string optional url of the external script, $code ignored if specified
1279 * @return string HTML, the code wrapped in <script> tags.
1281 public static function script($jscode, $url=null) {
1282 if ($jscode) {
1283 $attributes = array('type'=>'text/javascript');
1284 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1286 } else if ($url) {
1287 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1288 return self::tag('script', '', $attributes) . "\n";
1290 } else {
1291 return '';
1296 * Renders HTML table
1298 * This method may modify the passed instance by adding some default properties if they are not set yet.
1299 * If this is not what you want, you should make a full clone of your data before passing them to this
1300 * method. In most cases this is not an issue at all so we do not clone by default for performance
1301 * and memory consumption reasons.
1303 * @param html_table $table data to be rendered
1304 * @return string HTML code
1306 public static function table(html_table $table) {
1307 // prepare table data and populate missing properties with reasonable defaults
1308 if (!empty($table->align)) {
1309 foreach ($table->align as $key => $aa) {
1310 if ($aa) {
1311 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1312 } else {
1313 $table->align[$key] = null;
1317 if (!empty($table->size)) {
1318 foreach ($table->size as $key => $ss) {
1319 if ($ss) {
1320 $table->size[$key] = 'width:'. $ss .';';
1321 } else {
1322 $table->size[$key] = null;
1326 if (!empty($table->wrap)) {
1327 foreach ($table->wrap as $key => $ww) {
1328 if ($ww) {
1329 $table->wrap[$key] = 'white-space:nowrap;';
1330 } else {
1331 $table->wrap[$key] = '';
1335 if (!empty($table->head)) {
1336 foreach ($table->head as $key => $val) {
1337 if (!isset($table->align[$key])) {
1338 $table->align[$key] = null;
1340 if (!isset($table->size[$key])) {
1341 $table->size[$key] = null;
1343 if (!isset($table->wrap[$key])) {
1344 $table->wrap[$key] = null;
1349 if (empty($table->attributes['class'])) {
1350 $table->attributes['class'] = 'generaltable';
1352 if (!empty($table->tablealign)) {
1353 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1356 // explicitly assigned properties override those defined via $table->attributes
1357 $table->attributes['class'] = trim($table->attributes['class']);
1358 $attributes = array_merge($table->attributes, array(
1359 'id' => $table->id,
1360 'width' => $table->width,
1361 'summary' => $table->summary,
1362 'cellpadding' => $table->cellpadding,
1363 'cellspacing' => $table->cellspacing,
1365 $output = html_writer::start_tag('table', $attributes) . "\n";
1367 $countcols = 0;
1369 if (!empty($table->head)) {
1370 $countcols = count($table->head);
1372 $output .= html_writer::start_tag('thead', array()) . "\n";
1373 $output .= html_writer::start_tag('tr', array()) . "\n";
1374 $keys = array_keys($table->head);
1375 $lastkey = end($keys);
1377 foreach ($table->head as $key => $heading) {
1378 // Convert plain string headings into html_table_cell objects
1379 if (!($heading instanceof html_table_cell)) {
1380 $headingtext = $heading;
1381 $heading = new html_table_cell();
1382 $heading->text = $headingtext;
1383 $heading->header = true;
1386 if ($heading->header !== false) {
1387 $heading->header = true;
1390 if ($heading->header && empty($heading->scope)) {
1391 $heading->scope = 'col';
1394 $heading->attributes['class'] .= ' header c' . $key;
1395 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1396 $heading->colspan = $table->headspan[$key];
1397 $countcols += $table->headspan[$key] - 1;
1400 if ($key == $lastkey) {
1401 $heading->attributes['class'] .= ' lastcol';
1403 if (isset($table->colclasses[$key])) {
1404 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1406 $heading->attributes['class'] = trim($heading->attributes['class']);
1407 $attributes = array_merge($heading->attributes, array(
1408 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1409 'scope' => $heading->scope,
1410 'colspan' => $heading->colspan,
1413 $tagtype = 'td';
1414 if ($heading->header === true) {
1415 $tagtype = 'th';
1417 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1419 $output .= html_writer::end_tag('tr') . "\n";
1420 $output .= html_writer::end_tag('thead') . "\n";
1422 if (empty($table->data)) {
1423 // For valid XHTML strict every table must contain either a valid tr
1424 // or a valid tbody... both of which must contain a valid td
1425 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1426 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1427 $output .= html_writer::end_tag('tbody');
1431 if (!empty($table->data)) {
1432 $oddeven = 1;
1433 $keys = array_keys($table->data);
1434 $lastrowkey = end($keys);
1435 $output .= html_writer::start_tag('tbody', array());
1437 foreach ($table->data as $key => $row) {
1438 if (($row === 'hr') && ($countcols)) {
1439 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1440 } else {
1441 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1442 if (!($row instanceof html_table_row)) {
1443 $newrow = new html_table_row();
1445 foreach ($row as $item) {
1446 $cell = new html_table_cell();
1447 $cell->text = $item;
1448 $newrow->cells[] = $cell;
1450 $row = $newrow;
1453 $oddeven = $oddeven ? 0 : 1;
1454 if (isset($table->rowclasses[$key])) {
1455 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1458 $row->attributes['class'] .= ' r' . $oddeven;
1459 if ($key == $lastrowkey) {
1460 $row->attributes['class'] .= ' lastrow';
1463 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1464 $keys2 = array_keys($row->cells);
1465 $lastkey = end($keys2);
1467 $gotlastkey = false; //flag for sanity checking
1468 foreach ($row->cells as $key => $cell) {
1469 if ($gotlastkey) {
1470 //This should never happen. Why do we have a cell after the last cell?
1471 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1474 if (!($cell instanceof html_table_cell)) {
1475 $mycell = new html_table_cell();
1476 $mycell->text = $cell;
1477 $cell = $mycell;
1480 if (($cell->header === true) && empty($cell->scope)) {
1481 $cell->scope = 'row';
1484 if (isset($table->colclasses[$key])) {
1485 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1488 $cell->attributes['class'] .= ' cell c' . $key;
1489 if ($key == $lastkey) {
1490 $cell->attributes['class'] .= ' lastcol';
1491 $gotlastkey = true;
1493 $tdstyle = '';
1494 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1495 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1496 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1497 $cell->attributes['class'] = trim($cell->attributes['class']);
1498 $tdattributes = array_merge($cell->attributes, array(
1499 'style' => $tdstyle . $cell->style,
1500 'colspan' => $cell->colspan,
1501 'rowspan' => $cell->rowspan,
1502 'id' => $cell->id,
1503 'abbr' => $cell->abbr,
1504 'scope' => $cell->scope,
1506 $tagtype = 'td';
1507 if ($cell->header === true) {
1508 $tagtype = 'th';
1510 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1513 $output .= html_writer::end_tag('tr') . "\n";
1515 $output .= html_writer::end_tag('tbody') . "\n";
1517 $output .= html_writer::end_tag('table') . "\n";
1519 return $output;
1523 * Renders form element label
1525 * By default, the label is suffixed with a label separator defined in the
1526 * current language pack (colon by default in the English lang pack).
1527 * Adding the colon can be explicitly disabled if needed. Label separators
1528 * are put outside the label tag itself so they are not read by
1529 * screenreaders (accessibility).
1531 * Parameter $for explicitly associates the label with a form control. When
1532 * set, the value of this attribute must be the same as the value of
1533 * the id attribute of the form control in the same document. When null,
1534 * the label being defined is associated with the control inside the label
1535 * element.
1537 * @param string $text content of the label tag
1538 * @param string|null $for id of the element this label is associated with, null for no association
1539 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1540 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1541 * @return string HTML of the label element
1543 public static function label($text, $for, $colonize=true, array $attributes=array()) {
1544 if (!is_null($for)) {
1545 $attributes = array_merge($attributes, array('for' => $for));
1547 $text = trim($text);
1548 $label = self::tag('label', $text, $attributes);
1551 // TODO $colonize disabled for now yet - see MDL-12192 for details
1552 if (!empty($text) and $colonize) {
1553 // the $text may end with the colon already, though it is bad string definition style
1554 $colon = get_string('labelsep', 'langconfig');
1555 if (!empty($colon)) {
1556 $trimmed = trim($colon);
1557 if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1558 //debugging('The label text should not end with colon or other label separator,
1559 // please fix the string definition.', DEBUG_DEVELOPER);
1560 } else {
1561 $label .= $colon;
1567 return $label;
1571 // ==== JS writer and helper classes, will be probably moved elsewhere ======
1574 * Simple javascript output class
1575 * @copyright 2010 Petr Skoda
1577 class js_writer {
1579 * Returns javascript code calling the function
1580 * @param string $function function name, can be complex like Y.Event.purgeElement
1581 * @param array $arguments parameters
1582 * @param int $delay execution delay in seconds
1583 * @return string JS code fragment
1585 public static function function_call($function, array $arguments = null, $delay=0) {
1586 if ($arguments) {
1587 $arguments = array_map('json_encode', $arguments);
1588 $arguments = implode(', ', $arguments);
1589 } else {
1590 $arguments = '';
1592 $js = "$function($arguments);";
1594 if ($delay) {
1595 $delay = $delay * 1000; // in miliseconds
1596 $js = "setTimeout(function() { $js }, $delay);";
1598 return $js . "\n";
1602 * Special function which adds Y as first argument of fucntion call.
1603 * @param string $function
1604 * @param array $extraarguments
1605 * @return string
1607 public static function function_call_with_Y($function, array $extraarguments = null) {
1608 if ($extraarguments) {
1609 $extraarguments = array_map('json_encode', $extraarguments);
1610 $arguments = 'Y, ' . implode(', ', $extraarguments);
1611 } else {
1612 $arguments = 'Y';
1614 return "$function($arguments);\n";
1618 * Returns JavaScript code to initialise a new object
1619 * @param string|null $var If it is null then no var is assigned the new object
1620 * @param string $class
1621 * @param array $arguments
1622 * @param array $requirements
1623 * @param int $delay
1624 * @return string
1626 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1627 if (is_array($arguments)) {
1628 $arguments = array_map('json_encode', $arguments);
1629 $arguments = implode(', ', $arguments);
1632 if ($var === null) {
1633 $js = "new $class(Y, $arguments);";
1634 } else if (strpos($var, '.')!==false) {
1635 $js = "$var = new $class(Y, $arguments);";
1636 } else {
1637 $js = "var $var = new $class(Y, $arguments);";
1640 if ($delay) {
1641 $delay = $delay * 1000; // in miliseconds
1642 $js = "setTimeout(function() { $js }, $delay);";
1645 if (count($requirements) > 0) {
1646 $requirements = implode("', '", $requirements);
1647 $js = "Y.use('$requirements', function(Y){ $js });";
1649 return $js."\n";
1653 * Returns code setting value to variable
1654 * @param string $name
1655 * @param mixed $value json serialised value
1656 * @param bool $usevar add var definition, ignored for nested properties
1657 * @return string JS code fragment
1659 public static function set_variable($name, $value, $usevar=true) {
1660 $output = '';
1662 if ($usevar) {
1663 if (strpos($name, '.')) {
1664 $output .= '';
1665 } else {
1666 $output .= 'var ';
1670 $output .= "$name = ".json_encode($value).";";
1672 return $output;
1676 * Writes event handler attaching code
1677 * @param mixed $selector standard YUI selector for elements, may be array or string, element id is in the form "#idvalue"
1678 * @param string $event A valid DOM event (click, mousedown, change etc.)
1679 * @param string $function The name of the function to call
1680 * @param array $arguments An optional array of argument parameters to pass to the function
1681 * @return string JS code fragment
1683 public static function event_handler($selector, $event, $function, array $arguments = null) {
1684 $selector = json_encode($selector);
1685 $output = "Y.on('$event', $function, $selector, null";
1686 if (!empty($arguments)) {
1687 $output .= ', ' . json_encode($arguments);
1689 return $output . ");\n";
1694 * Holds all the information required to render a <table> by {@see core_renderer::table()}
1696 * Example of usage:
1697 * $t = new html_table();
1698 * ... // set various properties of the object $t as described below
1699 * echo html_writer::table($t);
1701 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1702 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1703 * @since Moodle 2.0
1705 class html_table {
1707 * @var string value to use for the id attribute of the table
1709 public $id = null;
1711 * @var array attributes of HTML attributes for the <table> element
1713 public $attributes = array();
1715 * For more control over the rendering of the headers, an array of html_table_cell objects
1716 * can be passed instead of an array of strings.
1717 * @var array of headings. The n-th array item is used as a heading of the n-th column.
1719 * Example of usage:
1720 * $t->head = array('Student', 'Grade');
1722 public $head;
1724 * @var array can be used to make a heading span multiple columns
1726 * Example of usage:
1727 * $t->headspan = array(2,1);
1729 * In this example, {@see html_table:$data} is supposed to have three columns. For the first two columns,
1730 * the same heading is used. Therefore, {@see html_table::$head} should consist of two items.
1732 public $headspan;
1734 * @var array of column alignments. The value is used as CSS 'text-align' property. Therefore, possible
1735 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1736 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1738 * Examples of usage:
1739 * $t->align = array(null, 'right');
1740 * or
1741 * $t->align[1] = 'right';
1744 public $align;
1746 * @var array of column sizes. The value is used as CSS 'size' property.
1748 * Examples of usage:
1749 * $t->size = array('50%', '50%');
1750 * or
1751 * $t->size[1] = '120px';
1753 public $size;
1755 * @var array of wrapping information. The only possible value is 'nowrap' that sets the
1756 * CSS property 'white-space' to the value 'nowrap' in the given column.
1758 * Example of usage:
1759 * $t->wrap = array(null, 'nowrap');
1761 public $wrap;
1763 * @var array of arrays or html_table_row objects containing the data. Alternatively, if you have
1764 * $head specified, the string 'hr' (for horizontal ruler) can be used
1765 * instead of an array of cells data resulting in a divider rendered.
1767 * Example of usage with array of arrays:
1768 * $row1 = array('Harry Potter', '76 %');
1769 * $row2 = array('Hermione Granger', '100 %');
1770 * $t->data = array($row1, $row2);
1772 * Example with array of html_table_row objects: (used for more fine-grained control)
1773 * $cell1 = new html_table_cell();
1774 * $cell1->text = 'Harry Potter';
1775 * $cell1->colspan = 2;
1776 * $row1 = new html_table_row();
1777 * $row1->cells[] = $cell1;
1778 * $cell2 = new html_table_cell();
1779 * $cell2->text = 'Hermione Granger';
1780 * $cell3 = new html_table_cell();
1781 * $cell3->text = '100 %';
1782 * $row2 = new html_table_row();
1783 * $row2->cells = array($cell2, $cell3);
1784 * $t->data = array($row1, $row2);
1786 public $data;
1788 * @var string width of the table, percentage of the page preferred. Defaults to 80%
1789 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1791 public $width = null;
1793 * @var string alignment the whole table. Can be 'right', 'left' or 'center' (default).
1794 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1796 public $tablealign = null;
1798 * @var int padding on each cell, in pixels
1799 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1801 public $cellpadding = null;
1803 * @var int spacing between cells, in pixels
1804 * @deprecated since Moodle 2.0. Styling should be in the CSS.
1806 public $cellspacing = null;
1808 * @var array classes to add to particular rows, space-separated string.
1809 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
1810 * respectively. Class 'lastrow' is added automatically for the last row
1811 * in the table.
1813 * Example of usage:
1814 * $t->rowclasses[9] = 'tenth'
1816 public $rowclasses;
1818 * @var array classes to add to every cell in a particular column,
1819 * space-separated string. Class 'cell' is added automatically by the renderer.
1820 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
1821 * respectively. Class 'lastcol' is added automatically for all last cells
1822 * in a row.
1824 * Example of usage:
1825 * $t->colclasses = array(null, 'grade');
1827 public $colclasses;
1829 * @var string description of the contents for screen readers.
1831 public $summary;
1834 * Constructor
1836 public function __construct() {
1837 $this->attributes['class'] = '';
1843 * Component representing a table row.
1845 * @copyright 2009 Nicolas Connault
1846 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1847 * @since Moodle 2.0
1849 class html_table_row {
1851 * @var string value to use for the id attribute of the row
1853 public $id = null;
1855 * @var array $cells Array of html_table_cell objects
1857 public $cells = array();
1859 * @var string $style value to use for the style attribute of the table row
1861 public $style = null;
1863 * @var array attributes of additional HTML attributes for the <tr> element
1865 public $attributes = array();
1868 * Constructor
1869 * @param array $cells
1871 public function __construct(array $cells=null) {
1872 $this->attributes['class'] = '';
1873 $cells = (array)$cells;
1874 foreach ($cells as $cell) {
1875 if ($cell instanceof html_table_cell) {
1876 $this->cells[] = $cell;
1877 } else {
1878 $this->cells[] = new html_table_cell($cell);
1886 * Component representing a table cell.
1888 * @copyright 2009 Nicolas Connault
1889 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1890 * @since Moodle 2.0
1892 class html_table_cell {
1894 * @var string value to use for the id attribute of the cell
1896 public $id = null;
1898 * @var string $text The contents of the cell
1900 public $text;
1902 * @var string $abbr Abbreviated version of the contents of the cell
1904 public $abbr = null;
1906 * @var int $colspan Number of columns this cell should span
1908 public $colspan = null;
1910 * @var int $rowspan Number of rows this cell should span
1912 public $rowspan = null;
1914 * @var string $scope Defines a way to associate header cells and data cells in a table
1916 public $scope = null;
1918 * @var boolean $header Whether or not this cell is a header cell
1920 public $header = null;
1922 * @var string $style value to use for the style attribute of the table cell
1924 public $style = null;
1926 * @var array attributes of additional HTML attributes for the <td> element
1928 public $attributes = array();
1930 public function __construct($text = null) {
1931 $this->text = $text;
1932 $this->attributes['class'] = '';
1937 /// Complex components aggregating simpler components
1941 * Component representing a paging bar.
1943 * @copyright 2009 Nicolas Connault
1944 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1945 * @since Moodle 2.0
1947 class paging_bar implements renderable {
1949 * @var int $maxdisplay The maximum number of pagelinks to display
1951 public $maxdisplay = 18;
1953 * @var int $totalcount post or get
1955 public $totalcount;
1957 * @var int $page The page you are currently viewing
1959 public $page;
1961 * @var int $perpage The number of entries that should be shown per page
1963 public $perpage;
1965 * @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.
1966 * If this is a moodle_url object then the pagevar param will be replaced by the page no, for each page.
1968 public $baseurl;
1970 * @var string $pagevar This is the variable name that you use for the page number in your code (ie. 'tablepage', 'blogpage', etc)
1972 public $pagevar;
1974 * @var string $previouslink A HTML link representing the "previous" page
1976 public $previouslink = null;
1978 * @var tring $nextlink A HTML link representing the "next" page
1980 public $nextlink = null;
1982 * @var tring $firstlink A HTML link representing the first page
1984 public $firstlink = null;
1986 * @var tring $lastlink A HTML link representing the last page
1988 public $lastlink = null;
1990 * @var array $pagelinks An array of strings. One of them is just a string: the current page
1992 public $pagelinks = array();
1995 * Constructor paging_bar with only the required params.
1997 * @param int $totalcount The total number of entries available to be paged through
1998 * @param int $page The page you are currently viewing
1999 * @param int $perpage The number of entries that should be shown per page
2000 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2001 * @param string $pagevar name of page parameter that holds the page number
2003 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2004 $this->totalcount = $totalcount;
2005 $this->page = $page;
2006 $this->perpage = $perpage;
2007 $this->baseurl = $baseurl;
2008 $this->pagevar = $pagevar;
2012 * @return void
2014 public function prepare(renderer_base $output, moodle_page $page, $target) {
2015 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2016 throw new coding_exception('paging_bar requires a totalcount value.');
2018 if (!isset($this->page) || is_null($this->page)) {
2019 throw new coding_exception('paging_bar requires a page value.');
2021 if (empty($this->perpage)) {
2022 throw new coding_exception('paging_bar requires a perpage value.');
2024 if (empty($this->baseurl)) {
2025 throw new coding_exception('paging_bar requires a baseurl value.');
2028 if ($this->totalcount > $this->perpage) {
2029 $pagenum = $this->page - 1;
2031 if ($this->page > 0) {
2032 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2035 if ($this->perpage > 0) {
2036 $lastpage = ceil($this->totalcount / $this->perpage);
2037 } else {
2038 $lastpage = 1;
2041 if ($this->page > 15) {
2042 $startpage = $this->page - 10;
2044 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2045 } else {
2046 $startpage = 0;
2049 $currpage = $startpage;
2050 $displaycount = $displaypage = 0;
2052 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2053 $displaypage = $currpage + 1;
2055 if ($this->page == $currpage) {
2056 $this->pagelinks[] = $displaypage;
2057 } else {
2058 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2059 $this->pagelinks[] = $pagelink;
2062 $displaycount++;
2063 $currpage++;
2066 if ($currpage < $lastpage) {
2067 $lastpageactual = $lastpage - 1;
2068 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2071 $pagenum = $this->page + 1;
2073 if ($pagenum != $displaypage) {
2074 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2082 * This class represents how a block appears on a page.
2084 * During output, each block instance is asked to return a block_contents object,
2085 * those are then passed to the $OUTPUT->block function for display.
2087 * {@link $contents} should probably be generated using a moodle_block_..._renderer.
2089 * Other block-like things that need to appear on the page, for example the
2090 * add new block UI, are also represented as block_contents objects.
2092 * @copyright 2009 Tim Hunt
2093 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2094 * @since Moodle 2.0
2096 class block_contents {
2097 /** @var int used to set $skipid. */
2098 protected static $idcounter = 1;
2100 const NOT_HIDEABLE = 0;
2101 const VISIBLE = 1;
2102 const HIDDEN = 2;
2105 * @var integer $skipid All the blocks (or things that look like blocks)
2106 * printed on a page are given a unique number that can be used to construct
2107 * id="" attributes. This is set automatically be the {@link prepare()} method.
2108 * Do not try to set it manually.
2110 public $skipid;
2113 * @var integer If this is the contents of a real block, this should be set to
2114 * the block_instance.id. Otherwise this should be set to 0.
2116 public $blockinstanceid = 0;
2119 * @var integer if this is a real block instance, and there is a corresponding
2120 * block_position.id for the block on this page, this should be set to that id.
2121 * Otherwise it should be 0.
2123 public $blockpositionid = 0;
2126 * @param array $attributes an array of attribute => value pairs that are put on the
2127 * outer div of this block. {@link $id} and {@link $classes} attributes should be set separately.
2129 public $attributes;
2132 * @param string $title The title of this block. If this came from user input,
2133 * it should already have had format_string() processing done on it. This will
2134 * be output inside <h2> tags. Please do not cause invalid XHTML.
2136 public $title = '';
2139 * @param string $content HTML for the content
2141 public $content = '';
2144 * @param array $list an alternative to $content, it you want a list of things with optional icons.
2146 public $footer = '';
2149 * Any small print that should appear under the block to explain to the
2150 * teacher about the block, for example 'This is a sticky block that was
2151 * added in the system context.'
2152 * @var string
2154 public $annotation = '';
2157 * @var integer one of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2158 * the user can toggle whether this block is visible.
2160 public $collapsible = self::NOT_HIDEABLE;
2163 * A (possibly empty) array of editing controls. Each element of this array
2164 * should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2165 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2166 * @var array
2168 public $controls = array();
2172 * Create new instance of block content
2173 * @param array $attributes
2175 public function __construct(array $attributes=null) {
2176 $this->skipid = self::$idcounter;
2177 self::$idcounter += 1;
2179 if ($attributes) {
2180 // standard block
2181 $this->attributes = $attributes;
2182 } else {
2183 // simple "fake" blocks used in some modules and "Add new block" block
2184 $this->attributes = array('class'=>'block');
2189 * Add html class to block
2190 * @param string $class
2191 * @return void
2193 public function add_class($class) {
2194 $this->attributes['class'] .= ' '.$class;
2200 * This class represents a target for where a block can go when it is being moved.
2202 * This needs to be rendered as a form with the given hidden from fields, and
2203 * clicking anywhere in the form should submit it. The form action should be
2204 * $PAGE->url.
2206 * @copyright 2009 Tim Hunt
2207 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2208 * @since Moodle 2.0
2210 class block_move_target {
2212 * Move url
2213 * @var moodle_url
2215 public $url;
2217 * label
2218 * @var string
2220 public $text;
2223 * Constructor
2224 * @param string $text
2225 * @param moodle_url $url
2227 public function __construct($text, moodle_url $url) {
2228 $this->text = $text;
2229 $this->url = $url;
2234 * Custom menu item
2236 * This class is used to represent one item within a custom menu that may or may
2237 * not have children.
2239 * @copyright 2010 Sam Hemelryk
2240 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2241 * @since Moodle 2.0
2243 class custom_menu_item implements renderable {
2245 * The text to show for the item
2246 * @var string
2248 protected $text;
2250 * The link to give the icon if it has no children
2251 * @var moodle_url
2253 protected $url;
2255 * A title to apply to the item. By default the text
2256 * @var string
2258 protected $title;
2260 * A sort order for the item, not necessary if you order things in the CFG var
2261 * @var int
2263 protected $sort;
2265 * A reference to the parent for this item or NULL if it is a top level item
2266 * @var custom_menu_item
2268 protected $parent;
2270 * A array in which to store children this item has.
2271 * @var array
2273 protected $children = array();
2275 * A reference to the sort var of the last child that was added
2276 * @var int
2278 protected $lastsort = 0;
2280 * Constructs the new custom menu item
2282 * @param string $text
2283 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2284 * @param string $title A title to apply to this item [Optional]
2285 * @param int $sort A sort or to use if we need to sort differently [Optional]
2286 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2287 * belongs to, only if the child has a parent. [Optional]
2289 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent=null) {
2290 $this->text = $text;
2291 $this->url = $url;
2292 $this->title = $title;
2293 $this->sort = (int)$sort;
2294 $this->parent = $parent;
2298 * Adds a custom menu item as a child of this node given its properties.
2300 * @param string $text
2301 * @param moodle_url $url
2302 * @param string $title
2303 * @param int $sort
2304 * @return custom_menu_item
2306 public function add($text, moodle_url $url=null, $title=null, $sort = null) {
2307 $key = count($this->children);
2308 if (empty($sort)) {
2309 $sort = $this->lastsort + 1;
2311 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2312 $this->lastsort = (int)$sort;
2313 return $this->children[$key];
2316 * Returns the text for this item
2317 * @return string
2319 public function get_text() {
2320 return $this->text;
2323 * Returns the url for this item
2324 * @return moodle_url
2326 public function get_url() {
2327 return $this->url;
2330 * Returns the title for this item
2331 * @return string
2333 public function get_title() {
2334 return $this->title;
2337 * Sorts and returns the children for this item
2338 * @return array
2340 public function get_children() {
2341 $this->sort();
2342 return $this->children;
2345 * Gets the sort order for this child
2346 * @return int
2348 public function get_sort_order() {
2349 return $this->sort;
2352 * Gets the parent this child belong to
2353 * @return custom_menu_item
2355 public function get_parent() {
2356 return $this->parent;
2359 * Sorts the children this item has
2361 public function sort() {
2362 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2365 * Returns true if this item has any children
2366 * @return bool
2368 public function has_children() {
2369 return (count($this->children) > 0);
2373 * Sets the text for the node
2374 * @param string $text
2376 public function set_text($text) {
2377 $this->text = (string)$text;
2381 * Sets the title for the node
2382 * @param string $title
2384 public function set_title($title) {
2385 $this->title = (string)$title;
2389 * Sets the url for the node
2390 * @param moodle_url $url
2392 public function set_url(moodle_url $url) {
2393 $this->url = $url;
2398 * Custom menu class
2400 * This class is used to operate a custom menu that can be rendered for the page.
2401 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2402 * of custom_menu_item nodes that can be rendered by the core renderer.
2404 * To configure the custom menu:
2405 * Settings: Administration > Appearance > Themes > Theme settings
2407 * @copyright 2010 Sam Hemelryk
2408 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2409 * @since Moodle 2.0
2411 class custom_menu extends custom_menu_item {
2413 /** @var string the language we should render for, null disables multilang support */
2414 protected $currentlanguage = null;
2417 * Creates the custom menu
2419 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2420 * @param string $language the current language code, null disables multilang support
2422 public function __construct($definition = '', $currentlanguage = null) {
2424 $this->currentlanguage = $currentlanguage;
2425 parent::__construct('root'); // create virtual root element of the menu
2426 if (!empty($definition)) {
2427 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2432 * Overrides the children of this custom menu. Useful when getting children
2433 * from $CFG->custommenuitems
2435 public function override_children(array $children) {
2436 $this->children = array();
2437 foreach ($children as $child) {
2438 if ($child instanceof custom_menu_item) {
2439 $this->children[] = $child;
2445 * Converts a string into a structured array of custom_menu_items which can
2446 * then be added to a custom menu.
2448 * Structure:
2449 * text|url|title|langs
2450 * The number of hyphens at the start determines the depth of the item. The
2451 * languages are optional, comma separated list of languages the line is for.
2453 * Example structure:
2454 * First level first item|http://www.moodle.com/
2455 * -Second level first item|http://www.moodle.com/partners/
2456 * -Second level second item|http://www.moodle.com/hq/
2457 * --Third level first item|http://www.moodle.com/jobs/
2458 * -Second level third item|http://www.moodle.com/development/
2459 * First level second item|http://www.moodle.com/feedback/
2460 * First level third item
2461 * English only|http://moodle.com|English only item|en
2462 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2465 * @static
2466 * @param string $text the menu items definition
2467 * @param string $language the language code, null disables multilang support
2468 * @return array
2470 public static function convert_text_to_menu_nodes($text, $language = null) {
2471 $lines = explode("\n", $text);
2472 $children = array();
2473 $lastchild = null;
2474 $lastdepth = null;
2475 $lastsort = 0;
2476 foreach ($lines as $line) {
2477 $line = trim($line);
2478 $bits = explode('|', $line, 4); // name|url|title|langs
2479 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2480 // Every item must have a name to be valid
2481 continue;
2482 } else {
2483 $bits[0] = ltrim($bits[0],'-');
2485 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2486 // Set the url to null
2487 $bits[1] = null;
2488 } else {
2489 // Make sure the url is a moodle url
2490 $bits[1] = new moodle_url(trim($bits[1]));
2492 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2493 // Set the title to null seeing as there isn't one
2494 $bits[2] = $bits[0];
2496 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2497 // The item is valid for all languages
2498 $itemlangs = null;
2499 } else {
2500 $itemlangs = array_map('trim', explode(',', $bits[3]));
2502 if (!empty($language) and !empty($itemlangs)) {
2503 // check that the item is intended for the current language
2504 if (!in_array($language, $itemlangs)) {
2505 continue;
2508 // Set an incremental sort order to keep it simple.
2509 $lastsort++;
2510 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2511 $depth = strlen($match[1]);
2512 if ($depth < $lastdepth) {
2513 $difference = $lastdepth - $depth;
2514 if ($lastdepth > 1 && $lastdepth != $difference) {
2515 $tempchild = $lastchild->get_parent();
2516 for ($i =0; $i < $difference; $i++) {
2517 $tempchild = $tempchild->get_parent();
2519 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2520 } else {
2521 $depth = 0;
2522 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2523 $children[] = $lastchild;
2525 } else if ($depth > $lastdepth) {
2526 $depth = $lastdepth + 1;
2527 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2528 } else {
2529 if ($depth == 0) {
2530 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2531 $children[] = $lastchild;
2532 } else {
2533 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2536 } else {
2537 $depth = 0;
2538 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2539 $children[] = $lastchild;
2541 $lastdepth = $depth;
2543 return $children;
2547 * Sorts two custom menu items
2549 * This function is designed to be used with the usort method
2550 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2552 * @param custom_menu_item $itema
2553 * @param custom_menu_item $itemb
2554 * @return int
2556 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2557 $itema = $itema->get_sort_order();
2558 $itemb = $itemb->get_sort_order();
2559 if ($itema == $itemb) {
2560 return 0;
2562 return ($itema > $itemb) ? +1 : -1;