2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Classes representing HTML elements, used by $OUTPUT methods
20 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
25 * @copyright 2009 Tim Hunt
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') ||
die();
32 * Interface marking other classes as suitable for renderer_base::render()
34 * @copyright 2010 Petr Skoda (skodak) info@skodak.org
38 interface renderable
{
39 // intentionally empty
43 * Interface marking other classes having the ability to export their data for use by templates.
45 * @copyright 2015 Damyon Wiese
50 interface templatable
{
53 * Function to export the renderer data in a format that is suitable for a
54 * mustache template. This means:
55 * 1. No complex types - only stdClass, array, int, string, float, bool
56 * 2. Any additional info that is required for the template is pre-calculated (e.g. capability checks).
58 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
59 * @return stdClass|array
61 public function export_for_template(renderer_base
$output);
65 * Data structure representing a file picker.
67 * @copyright 2010 Dongsheng Cai
68 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
73 class file_picker
implements renderable
{
76 * @var stdClass An object containing options for the file picker
81 * Constructs a file picker object.
83 * The following are possible options for the filepicker:
84 * - accepted_types (*)
85 * - return_types (FILE_INTERNAL)
87 * - client_id (uniqid)
91 * - buttonname (false)
93 * @param stdClass $options An object containing options for the file picker.
95 public function __construct(stdClass
$options) {
96 global $CFG, $USER, $PAGE;
97 require_once($CFG->dirroot
. '/repository/lib.php');
99 'accepted_types'=>'*',
100 'return_types'=>FILE_INTERNAL
,
101 'env' => 'filepicker',
102 'client_id' => uniqid(),
108 foreach ($defaults as $key=>$value) {
109 if (empty($options->$key)) {
110 $options->$key = $value;
114 $options->currentfile
= '';
115 if (!empty($options->itemid
)) {
116 $fs = get_file_storage();
117 $usercontext = context_user
::instance($USER->id
);
118 if (empty($options->filename
)) {
119 if ($files = $fs->get_area_files($usercontext->id
, 'user', 'draft', $options->itemid
, 'id DESC', false)) {
120 $file = reset($files);
123 $file = $fs->get_file($usercontext->id
, 'user', 'draft', $options->itemid
, $options->filepath
, $options->filename
);
126 $options->currentfile
= html_writer
::link(moodle_url
::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
130 // initilise options, getting files in root path
131 $this->options
= initialise_filepicker($options);
133 // copying other options
134 foreach ($options as $name=>$value) {
135 if (!isset($this->options
->$name)) {
136 $this->options
->$name = $value;
143 * Data structure representing a user picture.
145 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
146 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
151 class user_picture
implements renderable
{
153 * @var array List of mandatory fields in user record here. (do not include
154 * TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
156 protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'firstnamephonetic', 'lastnamephonetic',
157 'middlename', 'alternatename', 'imagealt', 'email');
160 * @var stdClass A user object with at least fields all columns specified
161 * in $fields array constant set.
166 * @var int The course id. Used when constructing the link to the user's
167 * profile, page course id used if not specified.
172 * @var bool Add course profile link to image
177 * @var int Size in pixels. Special values are (true/1 = 100px) and
179 * for backward compatibility.
184 * @var bool Add non-blank alt-text to the image.
185 * Default true, set to false when image alt just duplicates text in screenreaders.
187 public $alttext = true;
190 * @var bool Whether or not to open the link in a popup window.
192 public $popup = false;
195 * @var string Image class attribute
197 public $class = 'userpicture';
200 * @var bool Whether to be visible to screen readers.
202 public $visibletoscreenreaders = true;
205 * User picture constructor.
207 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
208 * It is recommended to add also contextid of the user for performance reasons.
210 public function __construct(stdClass
$user) {
213 if (empty($user->id
)) {
214 throw new coding_exception('User id is required when printing user avatar image.');
217 // only touch the DB if we are missing data and complain loudly...
219 foreach (self
::$fields as $field) {
220 if (!array_key_exists($field, $user)) {
222 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
223 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER
);
229 $this->user
= $DB->get_record('user', array('id'=>$user->id
), self
::fields(), MUST_EXIST
);
231 $this->user
= clone($user);
236 * Returns a list of required user fields, useful when fetching required user info from db.
238 * In some cases we have to fetch the user data together with some other information,
239 * the idalias is useful there because the id would otherwise override the main
240 * id of the result record. Please note it has to be converted back to id before rendering.
242 * @param string $tableprefix name of database table prefix in query
243 * @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)
244 * @param string $idalias alias of id field
245 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
248 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
249 if (!$tableprefix and !$extrafields and !$idalias) {
250 return implode(',', self
::$fields);
255 foreach (self
::$fields as $field) {
256 if ($field === 'id' and $idalias and $idalias !== 'id') {
257 $fields[$field] = "$tableprefix$field AS $idalias";
259 if ($fieldprefix and $field !== 'id') {
260 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
262 $fields[$field] = "$tableprefix$field";
266 // add extra fields if not already there
268 foreach ($extrafields as $e) {
269 if ($e === 'id' or isset($fields[$e])) {
273 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
275 $fields[$e] = "$tableprefix$e";
279 return implode(',', $fields);
283 * Extract the aliased user fields from a given record
285 * Given a record that was previously obtained using {@link self::fields()} with aliases,
286 * this method extracts user related unaliased fields.
288 * @param stdClass $record containing user picture fields
289 * @param array $extrafields extra fields included in the $record
290 * @param string $idalias alias of the id field
291 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
292 * @return stdClass object with unaliased user fields
294 public static function unalias(stdClass
$record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
296 if (empty($idalias)) {
300 $return = new stdClass();
302 foreach (self
::$fields as $field) {
303 if ($field === 'id') {
304 if (property_exists($record, $idalias)) {
305 $return->id
= $record->{$idalias};
308 if (property_exists($record, $fieldprefix.$field)) {
309 $return->{$field} = $record->{$fieldprefix.$field};
313 // add extra fields if not already there
315 foreach ($extrafields as $e) {
316 if ($e === 'id' or property_exists($return, $e)) {
319 $return->{$e} = $record->{$fieldprefix.$e};
327 * Works out the URL for the users picture.
329 * This method is recommended as it avoids costly redirects of user pictures
330 * if requests are made for non-existent files etc.
332 * @param moodle_page $page
333 * @param renderer_base $renderer
336 public function get_url(moodle_page
$page, renderer_base
$renderer = null) {
339 if (is_null($renderer)) {
340 $renderer = $page->get_renderer('core');
343 // Sort out the filename and size. Size is only required for the gravatar
344 // implementation presently.
345 if (empty($this->size
)) {
348 } else if ($this->size
=== true or $this->size
== 1) {
351 } else if ($this->size
> 100) {
353 $size = (int)$this->size
;
354 } else if ($this->size
>= 50) {
356 $size = (int)$this->size
;
359 $size = (int)$this->size
;
362 $defaulturl = $renderer->pix_url('u/'.$filename); // default image
364 if ((!empty($CFG->forcelogin
) and !isloggedin()) ||
365 (!empty($CFG->forceloginforprofileimage
) && (!isloggedin() ||
isguestuser()))) {
366 // Protect images if login required and not logged in;
367 // also if login is required for profile images and is not logged in or guest
368 // do not use require_login() because it is expensive and not suitable here anyway.
372 // First try to detect deleted users - but do not read from database for performance reasons!
373 if (!empty($this->user
->deleted
) or strpos($this->user
->email
, '@') === false) {
374 // All deleted users should have email replaced by md5 hash,
375 // all active users are expected to have valid email.
379 // Did the user upload a picture?
380 if ($this->user
->picture
> 0) {
381 if (!empty($this->user
->contextid
)) {
382 $contextid = $this->user
->contextid
;
384 $context = context_user
::instance($this->user
->id
, IGNORE_MISSING
);
386 // This must be an incorrectly deleted user, all other users have context.
389 $contextid = $context->id
;
393 if (clean_param($page->theme
->name
, PARAM_THEME
) == $page->theme
->name
) {
394 // We append the theme name to the file path if we have it so that
395 // in the circumstance that the profile picture is not available
396 // when the user actually requests it they still get the profile
397 // picture for the correct theme.
398 $path .= $page->theme
->name
.'/';
400 // Set the image URL to the URL for the uploaded file and return.
401 $url = moodle_url
::make_pluginfile_url($contextid, 'user', 'icon', NULL, $path, $filename);
402 $url->param('rev', $this->user
->picture
);
406 if ($this->user
->picture
== 0 and !empty($CFG->enablegravatar
)) {
407 // Normalise the size variable to acceptable bounds
408 if ($size < 1 ||
$size > 512) {
411 // Hash the users email address
412 $md5 = md5(strtolower(trim($this->user
->email
)));
413 // Build a gravatar URL with what we know.
415 // Find the best default image URL we can (MDL-35669)
416 if (empty($CFG->gravatardefaulturl
)) {
417 $absoluteimagepath = $page->theme
->resolve_image_location('u/'.$filename, 'core');
418 if (strpos($absoluteimagepath, $CFG->dirroot
) === 0) {
419 $gravatardefault = $CFG->wwwroot
. substr($absoluteimagepath, strlen($CFG->dirroot
));
421 $gravatardefault = $CFG->wwwroot
. '/pix/u/' . $filename . '.png';
424 $gravatardefault = $CFG->gravatardefaulturl
;
427 // If the currently requested page is https then we'll return an
428 // https gravatar page.
430 $gravatardefault = str_replace($CFG->wwwroot
, $CFG->httpswwwroot
, $gravatardefault); // Replace by secure url.
431 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
433 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
442 * Data structure representing a help icon.
444 * @copyright 2010 Petr Skoda (info@skodak.org)
445 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
450 class help_icon
implements renderable
{
453 * @var string lang pack identifier (without the "_help" suffix),
454 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
460 * @var string Component name, the same as in get_string()
465 * @var string Extra descriptive text next to the icon
467 public $linktext = null;
472 * @param string $identifier string for help page title,
473 * string with _help suffix is used for the actual help text.
474 * string with _link suffix is used to create a link to further info (if it exists)
475 * @param string $component
477 public function __construct($identifier, $component) {
478 $this->identifier
= $identifier;
479 $this->component
= $component;
483 * Verifies that both help strings exists, shows debug warnings if not
485 public function diag_strings() {
486 $sm = get_string_manager();
487 if (!$sm->string_exists($this->identifier
, $this->component
)) {
488 debugging("Help title string does not exist: [$this->identifier, $this->component]");
490 if (!$sm->string_exists($this->identifier
.'_help', $this->component
)) {
491 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
498 * Data structure representing an icon.
500 * @copyright 2010 Petr Skoda
501 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
506 class pix_icon
implements renderable
{
509 * @var string The icon name
514 * @var string The component the icon belongs to.
519 * @var array An array of attributes to use on the icon
521 var $attributes = array();
526 * @param string $pix short icon name
527 * @param string $alt The alt text to use for the icon
528 * @param string $component component name
529 * @param array $attributes html attributes
531 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
533 $this->component
= $component;
534 $this->attributes
= (array)$attributes;
536 $this->attributes
['alt'] = $alt;
537 if (empty($this->attributes
['class'])) {
538 $this->attributes
['class'] = 'smallicon';
540 if (!isset($this->attributes
['title'])) {
541 $this->attributes
['title'] = $this->attributes
['alt'];
542 } else if (empty($this->attributes
['title'])) {
543 // Remove the title attribute if empty, we probably want to use the parent node's title
544 // and some browsers might overwrite it with an empty title.
545 unset($this->attributes
['title']);
551 * Data structure representing an emoticon image
553 * @copyright 2010 David Mudrak
554 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
559 class pix_emoticon
extends pix_icon
implements renderable
{
563 * @param string $pix short icon name
564 * @param string $alt alternative text
565 * @param string $component emoticon image provider
566 * @param array $attributes explicit HTML attributes
568 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
569 if (empty($attributes['class'])) {
570 $attributes['class'] = 'emoticon';
572 parent
::__construct($pix, $alt, $component, $attributes);
577 * Data structure representing a simple form with only one button.
579 * @copyright 2009 Petr Skoda
580 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
585 class single_button
implements renderable
{
588 * @var moodle_url Target url
593 * @var string Button label
598 * @var string Form submit method post or get
600 var $method = 'post';
603 * @var string Wrapping div class
605 var $class = 'singlebutton';
608 * @var bool True if button disabled, false if normal
610 var $disabled = false;
613 * @var string Button tooltip
618 * @var string Form id
623 * @var array List of attached actions
625 var $actions = array();
628 * @var array $params URL Params
633 * @var string Action id
639 * @param moodle_url $url
640 * @param string $label button text
641 * @param string $method get or post submit method
643 public function __construct(moodle_url
$url, $label, $method='post') {
644 $this->url
= clone($url);
645 $this->label
= $label;
646 $this->method
= $method;
650 * Shortcut for adding a JS confirm dialog when the button is clicked.
651 * The message must be a yes/no question.
653 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
655 public function add_confirm_action($confirmmessage) {
656 $this->add_action(new confirm_action($confirmmessage));
660 * Add action to the button.
661 * @param component_action $action
663 public function add_action(component_action
$action) {
664 $this->actions
[] = $action;
670 * Simple form with just one select field that gets submitted automatically.
672 * If JS not enabled small go button is printed too.
674 * @copyright 2009 Petr Skoda
675 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
680 class single_select
implements renderable
{
683 * @var moodle_url Target url - includes hidden fields
688 * @var string Name of the select element.
693 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
694 * it is also possible to specify optgroup as complex label array ex.:
695 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
696 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
701 * @var string Selected option
706 * @var array Nothing selected
711 * @var array Extra select field attributes
713 var $attributes = array();
716 * @var string Button label
721 * @var array Button label's attributes
723 var $labelattributes = array();
726 * @var string Form submit method post or get
731 * @var string Wrapping div class
733 var $class = 'singleselect';
736 * @var bool True if button disabled, false if normal
738 var $disabled = false;
741 * @var string Button tooltip
746 * @var string Form id
751 * @var array List of attached actions
753 var $helpicon = null;
757 * @param moodle_url $url form action target, includes hidden fields
758 * @param string $name name of selection field - the changing parameter in url
759 * @param array $options list of options
760 * @param string $selected selected element
761 * @param array $nothing
762 * @param string $formid
764 public function __construct(moodle_url
$url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
767 $this->options
= $options;
768 $this->selected
= $selected;
769 $this->nothing
= $nothing;
770 $this->formid
= $formid;
774 * Shortcut for adding a JS confirm dialog when the button is clicked.
775 * The message must be a yes/no question.
777 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
779 public function add_confirm_action($confirmmessage) {
780 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
784 * Add action to the button.
786 * @param component_action $action
788 public function add_action(component_action
$action) {
789 $this->actions
[] = $action;
795 * @deprecated since Moodle 2.0
797 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
798 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
804 * @param string $identifier The keyword that defines a help page
805 * @param string $component
807 public function set_help_icon($identifier, $component = 'moodle') {
808 $this->helpicon
= new help_icon($identifier, $component);
812 * Sets select's label
814 * @param string $label
815 * @param array $attributes (optional)
817 public function set_label($label, $attributes = array()) {
818 $this->label
= $label;
819 $this->labelattributes
= $attributes;
825 * Simple URL selection widget description.
827 * @copyright 2009 Petr Skoda
828 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
833 class url_select
implements renderable
{
835 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
836 * it is also possible to specify optgroup as complex label array ex.:
837 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
838 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
843 * @var string Selected option
848 * @var array Nothing selected
853 * @var array Extra select field attributes
855 var $attributes = array();
858 * @var string Button label
863 * @var array Button label's attributes
865 var $labelattributes = array();
868 * @var string Wrapping div class
870 var $class = 'urlselect';
873 * @var bool True if button disabled, false if normal
875 var $disabled = false;
878 * @var string Button tooltip
883 * @var string Form id
888 * @var array List of attached actions
890 var $helpicon = null;
893 * @var string If set, makes button visible with given name for button
895 var $showbutton = null;
899 * @param array $urls list of options
900 * @param string $selected selected element
901 * @param array $nothing
902 * @param string $formid
903 * @param string $showbutton Set to text of button if it should be visible
904 * or null if it should be hidden (hidden version always has text 'go')
906 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
908 $this->selected
= $selected;
909 $this->nothing
= $nothing;
910 $this->formid
= $formid;
911 $this->showbutton
= $showbutton;
917 * @deprecated since Moodle 2.0
919 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
920 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
926 * @param string $identifier The keyword that defines a help page
927 * @param string $component
929 public function set_help_icon($identifier, $component = 'moodle') {
930 $this->helpicon
= new help_icon($identifier, $component);
934 * Sets select's label
936 * @param string $label
937 * @param array $attributes (optional)
939 public function set_label($label, $attributes = array()) {
940 $this->label
= $label;
941 $this->labelattributes
= $attributes;
946 * Data structure describing html link with special action attached.
948 * @copyright 2010 Petr Skoda
949 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
954 class action_link
implements renderable
{
957 * @var moodle_url Href url
962 * @var string Link text HTML fragment
967 * @var array HTML attributes
972 * @var array List of actions attached to link
977 * @var pix_icon Optional pix icon to render with the link
983 * @param moodle_url $url
984 * @param string $text HTML fragment
985 * @param component_action $action
986 * @param array $attributes associative array of html link attributes + disabled
987 * @param pix_icon $icon optional pix_icon to render with the link text
989 public function __construct(moodle_url
$url,
991 component_action
$action=null,
992 array $attributes=null,
993 pix_icon
$icon=null) {
994 $this->url
= clone($url);
996 $this->attributes
= (array)$attributes;
998 $this->add_action($action);
1000 $this->icon
= $icon;
1004 * Add action to the link.
1006 * @param component_action $action
1008 public function add_action(component_action
$action) {
1009 $this->actions
[] = $action;
1013 * Adds a CSS class to this action link object
1014 * @param string $class
1016 public function add_class($class) {
1017 if (empty($this->attributes
['class'])) {
1018 $this->attributes
['class'] = $class;
1020 $this->attributes
['class'] .= ' ' . $class;
1025 * Returns true if the specified class has been added to this link.
1026 * @param string $class
1029 public function has_class($class) {
1030 return strpos(' ' . $this->attributes
['class'] . ' ', ' ' . $class . ' ') !== false;
1035 * Simple html output class
1037 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1038 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1046 * Outputs a tag with attributes and contents
1048 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1049 * @param string $contents What goes between the opening and closing tags
1050 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1051 * @return string HTML fragment
1053 public static function tag($tagname, $contents, array $attributes = null) {
1054 return self
::start_tag($tagname, $attributes) . $contents . self
::end_tag($tagname);
1058 * Outputs an opening tag with attributes
1060 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1061 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1062 * @return string HTML fragment
1064 public static function start_tag($tagname, array $attributes = null) {
1065 return '<' . $tagname . self
::attributes($attributes) . '>';
1069 * Outputs a closing tag
1071 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1072 * @return string HTML fragment
1074 public static function end_tag($tagname) {
1075 return '</' . $tagname . '>';
1079 * Outputs an empty tag with attributes
1081 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1082 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1083 * @return string HTML fragment
1085 public static function empty_tag($tagname, array $attributes = null) {
1086 return '<' . $tagname . self
::attributes($attributes) . ' />';
1090 * Outputs a tag, but only if the contents are not empty
1092 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1093 * @param string $contents What goes between the opening and closing tags
1094 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1095 * @return string HTML fragment
1097 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1098 if ($contents === '' ||
is_null($contents)) {
1101 return self
::tag($tagname, $contents, $attributes);
1105 * Outputs a HTML attribute and value
1107 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1108 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1109 * @return string HTML fragment
1111 public static function attribute($name, $value) {
1112 if ($value instanceof moodle_url
) {
1113 return ' ' . $name . '="' . $value->out() . '"';
1116 // special case, we do not want these in output
1117 if ($value === null) {
1121 // no sloppy trimming here!
1122 return ' ' . $name . '="' . s($value) . '"';
1126 * Outputs a list of HTML attributes and values
1128 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1129 * The values will be escaped with {@link s()}
1130 * @return string HTML fragment
1132 public static function attributes(array $attributes = null) {
1133 $attributes = (array)$attributes;
1135 foreach ($attributes as $name => $value) {
1136 $output .= self
::attribute($name, $value);
1142 * Generates a simple image tag with attributes.
1144 * @param string $src The source of image
1145 * @param string $alt The alternate text for image
1146 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1147 * @return string HTML fragment
1149 public static function img($src, $alt, array $attributes = null) {
1150 $attributes = (array)$attributes;
1151 $attributes['src'] = $src;
1152 $attributes['alt'] = $alt;
1154 return self
::empty_tag('img', $attributes);
1158 * Generates random html element id.
1160 * @staticvar int $counter
1161 * @staticvar type $uniq
1162 * @param string $base A string fragment that will be included in the random ID.
1163 * @return string A unique ID
1165 public static function random_id($base='random') {
1166 static $counter = 0;
1169 if (!isset($uniq)) {
1174 return $base.$uniq.$counter;
1178 * Generates a simple html link
1180 * @param string|moodle_url $url The URL
1181 * @param string $text The text
1182 * @param array $attributes HTML attributes
1183 * @return string HTML fragment
1185 public static function link($url, $text, array $attributes = null) {
1186 $attributes = (array)$attributes;
1187 $attributes['href'] = $url;
1188 return self
::tag('a', $text, $attributes);
1192 * Generates a simple checkbox with optional label
1194 * @param string $name The name of the checkbox
1195 * @param string $value The value of the checkbox
1196 * @param bool $checked Whether the checkbox is checked
1197 * @param string $label The label for the checkbox
1198 * @param array $attributes Any attributes to apply to the checkbox
1199 * @return string html fragment
1201 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1202 $attributes = (array)$attributes;
1205 if ($label !== '' and !is_null($label)) {
1206 if (empty($attributes['id'])) {
1207 $attributes['id'] = self
::random_id('checkbox_');
1210 $attributes['type'] = 'checkbox';
1211 $attributes['value'] = $value;
1212 $attributes['name'] = $name;
1213 $attributes['checked'] = $checked ?
'checked' : null;
1215 $output .= self
::empty_tag('input', $attributes);
1217 if ($label !== '' and !is_null($label)) {
1218 $output .= self
::tag('label', $label, array('for'=>$attributes['id']));
1225 * Generates a simple select yes/no form field
1227 * @param string $name name of select element
1228 * @param bool $selected
1229 * @param array $attributes - html select element attributes
1230 * @return string HTML fragment
1232 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1233 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1234 return self
::select($options, $name, $selected, null, $attributes);
1238 * Generates a simple select form field
1240 * @param array $options associative array value=>label ex.:
1241 * array(1=>'One, 2=>Two)
1242 * it is also possible to specify optgroup as complex label array ex.:
1243 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1244 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1245 * @param string $name name of select element
1246 * @param string|array $selected value or array of values depending on multiple attribute
1247 * @param array|bool $nothing add nothing selected option, or false of not added
1248 * @param array $attributes html select element attributes
1249 * @return string HTML fragment
1251 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1252 $attributes = (array)$attributes;
1253 if (is_array($nothing)) {
1254 foreach ($nothing as $k=>$v) {
1255 if ($v === 'choose' or $v === 'choosedots') {
1256 $nothing[$k] = get_string('choosedots');
1259 $options = $nothing +
$options; // keep keys, do not override
1261 } else if (is_string($nothing) and $nothing !== '') {
1263 $options = array(''=>$nothing) +
$options;
1266 // we may accept more values if multiple attribute specified
1267 $selected = (array)$selected;
1268 foreach ($selected as $k=>$v) {
1269 $selected[$k] = (string)$v;
1272 if (!isset($attributes['id'])) {
1274 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1275 $id = str_replace('[', '', $id);
1276 $id = str_replace(']', '', $id);
1277 $attributes['id'] = $id;
1280 if (!isset($attributes['class'])) {
1281 $class = 'menu'.$name;
1282 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1283 $class = str_replace('[', '', $class);
1284 $class = str_replace(']', '', $class);
1285 $attributes['class'] = $class;
1287 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
1289 $attributes['name'] = $name;
1291 if (!empty($attributes['disabled'])) {
1292 $attributes['disabled'] = 'disabled';
1294 unset($attributes['disabled']);
1298 foreach ($options as $value=>$label) {
1299 if (is_array($label)) {
1300 // ignore key, it just has to be unique
1301 $output .= self
::select_optgroup(key($label), current($label), $selected);
1303 $output .= self
::select_option($label, $value, $selected);
1306 return self
::tag('select', $output, $attributes);
1310 * Returns HTML to display a select box option.
1312 * @param string $label The label to display as the option.
1313 * @param string|int $value The value the option represents
1314 * @param array $selected An array of selected options
1315 * @return string HTML fragment
1317 private static function select_option($label, $value, array $selected) {
1318 $attributes = array();
1319 $value = (string)$value;
1320 if (in_array($value, $selected, true)) {
1321 $attributes['selected'] = 'selected';
1323 $attributes['value'] = $value;
1324 return self
::tag('option', $label, $attributes);
1328 * Returns HTML to display a select box option group.
1330 * @param string $groupname The label to use for the group
1331 * @param array $options The options in the group
1332 * @param array $selected An array of selected values.
1333 * @return string HTML fragment.
1335 private static function select_optgroup($groupname, $options, array $selected) {
1336 if (empty($options)) {
1339 $attributes = array('label'=>$groupname);
1341 foreach ($options as $value=>$label) {
1342 $output .= self
::select_option($label, $value, $selected);
1344 return self
::tag('optgroup', $output, $attributes);
1348 * This is a shortcut for making an hour selector menu.
1350 * @param string $type The type of selector (years, months, days, hours, minutes)
1351 * @param string $name fieldname
1352 * @param int $currenttime A default timestamp in GMT
1353 * @param int $step minute spacing
1354 * @param array $attributes - html select element attributes
1355 * @return HTML fragment
1357 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1358 if (!$currenttime) {
1359 $currenttime = time();
1361 $currentdate = usergetdate($currenttime);
1362 $userdatetype = $type;
1363 $timeunits = array();
1367 for ($i=1970; $i<=2020; $i++
) {
1368 $timeunits[$i] = $i;
1370 $userdatetype = 'year';
1373 for ($i=1; $i<=12; $i++
) {
1374 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1376 $userdatetype = 'month';
1377 $currentdate['month'] = (int)$currentdate['mon'];
1380 for ($i=1; $i<=31; $i++
) {
1381 $timeunits[$i] = $i;
1383 $userdatetype = 'mday';
1386 for ($i=0; $i<=23; $i++
) {
1387 $timeunits[$i] = sprintf("%02d",$i);
1392 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1395 for ($i=0; $i<=59; $i+
=$step) {
1396 $timeunits[$i] = sprintf("%02d",$i);
1400 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1403 if (empty($attributes['id'])) {
1404 $attributes['id'] = self
::random_id('ts_');
1406 $timerselector = self
::select($timeunits, $name, $currentdate[$userdatetype], null, $attributes);
1407 $label = self
::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1409 return $label.$timerselector;
1413 * Shortcut for quick making of lists
1415 * Note: 'list' is a reserved keyword ;-)
1417 * @param array $items
1418 * @param array $attributes
1419 * @param string $tag ul or ol
1422 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1423 $output = html_writer
::start_tag($tag, $attributes)."\n";
1424 foreach ($items as $item) {
1425 $output .= html_writer
::tag('li', $item)."\n";
1427 $output .= html_writer
::end_tag($tag);
1432 * Returns hidden input fields created from url parameters.
1434 * @param moodle_url $url
1435 * @param array $exclude list of excluded parameters
1436 * @return string HTML fragment
1438 public static function input_hidden_params(moodle_url
$url, array $exclude = null) {
1439 $exclude = (array)$exclude;
1440 $params = $url->params();
1441 foreach ($exclude as $key) {
1442 unset($params[$key]);
1446 foreach ($params as $key => $value) {
1447 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1448 $output .= self
::empty_tag('input', $attributes)."\n";
1454 * Generate a script tag containing the the specified code.
1456 * @param string $jscode the JavaScript code
1457 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
1458 * @return string HTML, the code wrapped in <script> tags.
1460 public static function script($jscode, $url=null) {
1462 $attributes = array('type'=>'text/javascript');
1463 return self
::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1466 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1467 return self
::tag('script', '', $attributes) . "\n";
1475 * Renders HTML table
1477 * This method may modify the passed instance by adding some default properties if they are not set yet.
1478 * If this is not what you want, you should make a full clone of your data before passing them to this
1479 * method. In most cases this is not an issue at all so we do not clone by default for performance
1480 * and memory consumption reasons.
1482 * @param html_table $table data to be rendered
1483 * @return string HTML code
1485 public static function table(html_table
$table) {
1486 // prepare table data and populate missing properties with reasonable defaults
1487 if (!empty($table->align
)) {
1488 foreach ($table->align
as $key => $aa) {
1490 $table->align
[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1492 $table->align
[$key] = null;
1496 if (!empty($table->size
)) {
1497 foreach ($table->size
as $key => $ss) {
1499 $table->size
[$key] = 'width:'. $ss .';';
1501 $table->size
[$key] = null;
1505 if (!empty($table->wrap
)) {
1506 foreach ($table->wrap
as $key => $ww) {
1508 $table->wrap
[$key] = 'white-space:nowrap;';
1510 $table->wrap
[$key] = '';
1514 if (!empty($table->head
)) {
1515 foreach ($table->head
as $key => $val) {
1516 if (!isset($table->align
[$key])) {
1517 $table->align
[$key] = null;
1519 if (!isset($table->size
[$key])) {
1520 $table->size
[$key] = null;
1522 if (!isset($table->wrap
[$key])) {
1523 $table->wrap
[$key] = null;
1528 if (empty($table->attributes
['class'])) {
1529 $table->attributes
['class'] = 'generaltable';
1531 if (!empty($table->tablealign
)) {
1532 $table->attributes
['class'] .= ' boxalign' . $table->tablealign
;
1535 // explicitly assigned properties override those defined via $table->attributes
1536 $table->attributes
['class'] = trim($table->attributes
['class']);
1537 $attributes = array_merge($table->attributes
, array(
1539 'width' => $table->width
,
1540 'summary' => $table->summary
,
1541 'cellpadding' => $table->cellpadding
,
1542 'cellspacing' => $table->cellspacing
,
1544 $output = html_writer
::start_tag('table', $attributes) . "\n";
1548 // Output a caption if present.
1549 if (!empty($table->caption
)) {
1550 $captionattributes = array();
1551 if ($table->captionhide
) {
1552 $captionattributes['class'] = 'accesshide';
1554 $output .= html_writer
::tag(
1561 if (!empty($table->head
)) {
1562 $countcols = count($table->head
);
1564 $output .= html_writer
::start_tag('thead', array()) . "\n";
1565 $output .= html_writer
::start_tag('tr', array()) . "\n";
1566 $keys = array_keys($table->head
);
1567 $lastkey = end($keys);
1569 foreach ($table->head
as $key => $heading) {
1570 // Convert plain string headings into html_table_cell objects
1571 if (!($heading instanceof html_table_cell
)) {
1572 $headingtext = $heading;
1573 $heading = new html_table_cell();
1574 $heading->text
= $headingtext;
1575 $heading->header
= true;
1578 if ($heading->header
!== false) {
1579 $heading->header
= true;
1582 if ($heading->header
&& empty($heading->scope
)) {
1583 $heading->scope
= 'col';
1586 $heading->attributes
['class'] .= ' header c' . $key;
1587 if (isset($table->headspan
[$key]) && $table->headspan
[$key] > 1) {
1588 $heading->colspan
= $table->headspan
[$key];
1589 $countcols +
= $table->headspan
[$key] - 1;
1592 if ($key == $lastkey) {
1593 $heading->attributes
['class'] .= ' lastcol';
1595 if (isset($table->colclasses
[$key])) {
1596 $heading->attributes
['class'] .= ' ' . $table->colclasses
[$key];
1598 $heading->attributes
['class'] = trim($heading->attributes
['class']);
1599 $attributes = array_merge($heading->attributes
, array(
1600 'style' => $table->align
[$key] . $table->size
[$key] . $heading->style
,
1601 'scope' => $heading->scope
,
1602 'colspan' => $heading->colspan
,
1606 if ($heading->header
=== true) {
1609 $output .= html_writer
::tag($tagtype, $heading->text
, $attributes) . "\n";
1611 $output .= html_writer
::end_tag('tr') . "\n";
1612 $output .= html_writer
::end_tag('thead') . "\n";
1614 if (empty($table->data
)) {
1615 // For valid XHTML strict every table must contain either a valid tr
1616 // or a valid tbody... both of which must contain a valid td
1617 $output .= html_writer
::start_tag('tbody', array('class' => 'empty'));
1618 $output .= html_writer
::tag('tr', html_writer
::tag('td', '', array('colspan'=>count($table->head
))));
1619 $output .= html_writer
::end_tag('tbody');
1623 if (!empty($table->data
)) {
1624 $keys = array_keys($table->data
);
1625 $lastrowkey = end($keys);
1626 $output .= html_writer
::start_tag('tbody', array());
1628 foreach ($table->data
as $key => $row) {
1629 if (($row === 'hr') && ($countcols)) {
1630 $output .= html_writer
::tag('td', html_writer
::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1632 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1633 if (!($row instanceof html_table_row
)) {
1634 $newrow = new html_table_row();
1636 foreach ($row as $cell) {
1637 if (!($cell instanceof html_table_cell
)) {
1638 $cell = new html_table_cell($cell);
1640 $newrow->cells
[] = $cell;
1645 if (isset($table->rowclasses
[$key])) {
1646 $row->attributes
['class'] .= ' ' . $table->rowclasses
[$key];
1649 if ($key == $lastrowkey) {
1650 $row->attributes
['class'] .= ' lastrow';
1653 // Explicitly assigned properties should override those defined in the attributes.
1654 $row->attributes
['class'] = trim($row->attributes
['class']);
1655 $trattributes = array_merge($row->attributes
, array(
1657 'style' => $row->style
,
1659 $output .= html_writer
::start_tag('tr', $trattributes) . "\n";
1660 $keys2 = array_keys($row->cells
);
1661 $lastkey = end($keys2);
1663 $gotlastkey = false; //flag for sanity checking
1664 foreach ($row->cells
as $key => $cell) {
1666 //This should never happen. Why do we have a cell after the last cell?
1667 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1670 if (!($cell instanceof html_table_cell
)) {
1671 $mycell = new html_table_cell();
1672 $mycell->text
= $cell;
1676 if (($cell->header
=== true) && empty($cell->scope
)) {
1677 $cell->scope
= 'row';
1680 if (isset($table->colclasses
[$key])) {
1681 $cell->attributes
['class'] .= ' ' . $table->colclasses
[$key];
1684 $cell->attributes
['class'] .= ' cell c' . $key;
1685 if ($key == $lastkey) {
1686 $cell->attributes
['class'] .= ' lastcol';
1690 $tdstyle .= isset($table->align
[$key]) ?
$table->align
[$key] : '';
1691 $tdstyle .= isset($table->size
[$key]) ?
$table->size
[$key] : '';
1692 $tdstyle .= isset($table->wrap
[$key]) ?
$table->wrap
[$key] : '';
1693 $cell->attributes
['class'] = trim($cell->attributes
['class']);
1694 $tdattributes = array_merge($cell->attributes
, array(
1695 'style' => $tdstyle . $cell->style
,
1696 'colspan' => $cell->colspan
,
1697 'rowspan' => $cell->rowspan
,
1699 'abbr' => $cell->abbr
,
1700 'scope' => $cell->scope
,
1703 if ($cell->header
=== true) {
1706 $output .= html_writer
::tag($tagtype, $cell->text
, $tdattributes) . "\n";
1709 $output .= html_writer
::end_tag('tr') . "\n";
1711 $output .= html_writer
::end_tag('tbody') . "\n";
1713 $output .= html_writer
::end_tag('table') . "\n";
1719 * Renders form element label
1721 * By default, the label is suffixed with a label separator defined in the
1722 * current language pack (colon by default in the English lang pack).
1723 * Adding the colon can be explicitly disabled if needed. Label separators
1724 * are put outside the label tag itself so they are not read by
1725 * screenreaders (accessibility).
1727 * Parameter $for explicitly associates the label with a form control. When
1728 * set, the value of this attribute must be the same as the value of
1729 * the id attribute of the form control in the same document. When null,
1730 * the label being defined is associated with the control inside the label
1733 * @param string $text content of the label tag
1734 * @param string|null $for id of the element this label is associated with, null for no association
1735 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1736 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1737 * @return string HTML of the label element
1739 public static function label($text, $for, $colonize = true, array $attributes=array()) {
1740 if (!is_null($for)) {
1741 $attributes = array_merge($attributes, array('for' => $for));
1743 $text = trim($text);
1744 $label = self
::tag('label', $text, $attributes);
1746 // TODO MDL-12192 $colonize disabled for now yet
1747 // if (!empty($text) and $colonize) {
1748 // // the $text may end with the colon already, though it is bad string definition style
1749 // $colon = get_string('labelsep', 'langconfig');
1750 // if (!empty($colon)) {
1751 // $trimmed = trim($colon);
1752 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1753 // //debugging('The label text should not end with colon or other label separator,
1754 // // please fix the string definition.', DEBUG_DEVELOPER);
1756 // $label .= $colon;
1765 * Combines a class parameter with other attributes. Aids in code reduction
1766 * because the class parameter is very frequently used.
1768 * If the class attribute is specified both in the attributes and in the
1769 * class parameter, the two values are combined with a space between.
1771 * @param string $class Optional CSS class (or classes as space-separated list)
1772 * @param array $attributes Optional other attributes as array
1773 * @return array Attributes (or null if still none)
1775 private static function add_class($class = '', array $attributes = null) {
1776 if ($class !== '') {
1777 $classattribute = array('class' => $class);
1779 if (array_key_exists('class', $attributes)) {
1780 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
1782 $attributes = $classattribute +
$attributes;
1785 $attributes = $classattribute;
1792 * Creates a <div> tag. (Shortcut function.)
1794 * @param string $content HTML content of tag
1795 * @param string $class Optional CSS class (or classes as space-separated list)
1796 * @param array $attributes Optional other attributes as array
1797 * @return string HTML code for div
1799 public static function div($content, $class = '', array $attributes = null) {
1800 return self
::tag('div', $content, self
::add_class($class, $attributes));
1804 * Starts a <div> tag. (Shortcut function.)
1806 * @param string $class Optional CSS class (or classes as space-separated list)
1807 * @param array $attributes Optional other attributes as array
1808 * @return string HTML code for open div tag
1810 public static function start_div($class = '', array $attributes = null) {
1811 return self
::start_tag('div', self
::add_class($class, $attributes));
1815 * Ends a <div> tag. (Shortcut function.)
1817 * @return string HTML code for close div tag
1819 public static function end_div() {
1820 return self
::end_tag('div');
1824 * Creates a <span> tag. (Shortcut function.)
1826 * @param string $content HTML content of tag
1827 * @param string $class Optional CSS class (or classes as space-separated list)
1828 * @param array $attributes Optional other attributes as array
1829 * @return string HTML code for span
1831 public static function span($content, $class = '', array $attributes = null) {
1832 return self
::tag('span', $content, self
::add_class($class, $attributes));
1836 * Starts a <span> tag. (Shortcut function.)
1838 * @param string $class Optional CSS class (or classes as space-separated list)
1839 * @param array $attributes Optional other attributes as array
1840 * @return string HTML code for open span tag
1842 public static function start_span($class = '', array $attributes = null) {
1843 return self
::start_tag('span', self
::add_class($class, $attributes));
1847 * Ends a <span> tag. (Shortcut function.)
1849 * @return string HTML code for close span tag
1851 public static function end_span() {
1852 return self
::end_tag('span');
1857 * Simple javascript output class
1859 * @copyright 2010 Petr Skoda
1860 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1868 * Returns javascript code calling the function
1870 * @param string $function function name, can be complex like Y.Event.purgeElement
1871 * @param array $arguments parameters
1872 * @param int $delay execution delay in seconds
1873 * @return string JS code fragment
1875 public static function function_call($function, array $arguments = null, $delay=0) {
1877 $arguments = array_map('json_encode', convert_to_array($arguments));
1878 $arguments = implode(', ', $arguments);
1882 $js = "$function($arguments);";
1885 $delay = $delay * 1000; // in miliseconds
1886 $js = "setTimeout(function() { $js }, $delay);";
1892 * Special function which adds Y as first argument of function call.
1894 * @param string $function The function to call
1895 * @param array $extraarguments Any arguments to pass to it
1896 * @return string Some JS code
1898 public static function function_call_with_Y($function, array $extraarguments = null) {
1899 if ($extraarguments) {
1900 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1901 $arguments = 'Y, ' . implode(', ', $extraarguments);
1905 return "$function($arguments);\n";
1909 * Returns JavaScript code to initialise a new object
1911 * @param string $var If it is null then no var is assigned the new object.
1912 * @param string $class The class to initialise an object for.
1913 * @param array $arguments An array of args to pass to the init method.
1914 * @param array $requirements Any modules required for this class.
1915 * @param int $delay The delay before initialisation. 0 = no delay.
1916 * @return string Some JS code
1918 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1919 if (is_array($arguments)) {
1920 $arguments = array_map('json_encode', convert_to_array($arguments));
1921 $arguments = implode(', ', $arguments);
1924 if ($var === null) {
1925 $js = "new $class(Y, $arguments);";
1926 } else if (strpos($var, '.')!==false) {
1927 $js = "$var = new $class(Y, $arguments);";
1929 $js = "var $var = new $class(Y, $arguments);";
1933 $delay = $delay * 1000; // in miliseconds
1934 $js = "setTimeout(function() { $js }, $delay);";
1937 if (count($requirements) > 0) {
1938 $requirements = implode("', '", $requirements);
1939 $js = "Y.use('$requirements', function(Y){ $js });";
1945 * Returns code setting value to variable
1947 * @param string $name
1948 * @param mixed $value json serialised value
1949 * @param bool $usevar add var definition, ignored for nested properties
1950 * @return string JS code fragment
1952 public static function set_variable($name, $value, $usevar = true) {
1956 if (strpos($name, '.')) {
1963 $output .= "$name = ".json_encode($value).";";
1969 * Writes event handler attaching code
1971 * @param array|string $selector standard YUI selector for elements, may be
1972 * array or string, element id is in the form "#idvalue"
1973 * @param string $event A valid DOM event (click, mousedown, change etc.)
1974 * @param string $function The name of the function to call
1975 * @param array $arguments An optional array of argument parameters to pass to the function
1976 * @return string JS code fragment
1978 public static function event_handler($selector, $event, $function, array $arguments = null) {
1979 $selector = json_encode($selector);
1980 $output = "Y.on('$event', $function, $selector, null";
1981 if (!empty($arguments)) {
1982 $output .= ', ' . json_encode($arguments);
1984 return $output . ");\n";
1989 * Holds all the information required to render a <table> by {@link core_renderer::table()}
1992 * $t = new html_table();
1993 * ... // set various properties of the object $t as described below
1994 * echo html_writer::table($t);
1996 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1997 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2005 * @var string Value to use for the id attribute of the table
2010 * @var array Attributes of HTML attributes for the <table> element
2012 public $attributes = array();
2015 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
2016 * For more control over the rendering of the headers, an array of html_table_cell objects
2017 * can be passed instead of an array of strings.
2020 * $t->head = array('Student', 'Grade');
2025 * @var array An array that can be used to make a heading span multiple columns.
2026 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
2027 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
2030 * $t->headspan = array(2,1);
2035 * @var array An array of column alignments.
2036 * The value is used as CSS 'text-align' property. Therefore, possible
2037 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
2038 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
2040 * Examples of usage:
2041 * $t->align = array(null, 'right');
2043 * $t->align[1] = 'right';
2048 * @var array The value is used as CSS 'size' property.
2050 * Examples of usage:
2051 * $t->size = array('50%', '50%');
2053 * $t->size[1] = '120px';
2058 * @var array An array of wrapping information.
2059 * The only possible value is 'nowrap' that sets the
2060 * CSS property 'white-space' to the value 'nowrap' in the given column.
2063 * $t->wrap = array(null, 'nowrap');
2068 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2069 * $head specified, the string 'hr' (for horizontal ruler) can be used
2070 * instead of an array of cells data resulting in a divider rendered.
2072 * Example of usage with array of arrays:
2073 * $row1 = array('Harry Potter', '76 %');
2074 * $row2 = array('Hermione Granger', '100 %');
2075 * $t->data = array($row1, $row2);
2077 * Example with array of html_table_row objects: (used for more fine-grained control)
2078 * $cell1 = new html_table_cell();
2079 * $cell1->text = 'Harry Potter';
2080 * $cell1->colspan = 2;
2081 * $row1 = new html_table_row();
2082 * $row1->cells[] = $cell1;
2083 * $cell2 = new html_table_cell();
2084 * $cell2->text = 'Hermione Granger';
2085 * $cell3 = new html_table_cell();
2086 * $cell3->text = '100 %';
2087 * $row2 = new html_table_row();
2088 * $row2->cells = array($cell2, $cell3);
2089 * $t->data = array($row1, $row2);
2094 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2095 * @var string Width of the table, percentage of the page preferred.
2097 public $width = null;
2100 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2101 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2103 public $tablealign = null;
2106 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2107 * @var int Padding on each cell, in pixels
2109 public $cellpadding = null;
2112 * @var int Spacing between cells, in pixels
2113 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2115 public $cellspacing = null;
2118 * @var array Array of classes to add to particular rows, space-separated string.
2119 * Class 'lastrow' is added automatically for the last row in the table.
2122 * $t->rowclasses[9] = 'tenth'
2127 * @var array An array of classes to add to every cell in a particular column,
2128 * space-separated string. Class 'cell' is added automatically by the renderer.
2129 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2130 * respectively. Class 'lastcol' is added automatically for all last cells
2134 * $t->colclasses = array(null, 'grade');
2139 * @var string Description of the contents for screen readers.
2144 * @var string Caption for the table, typically a title.
2147 * $t->caption = "TV Guide";
2152 * @var bool Whether to hide the table's caption from sighted users.
2155 * $t->caption = "TV Guide";
2156 * $t->captionhide = true;
2158 public $captionhide = false;
2163 public function __construct() {
2164 $this->attributes
['class'] = '';
2169 * Component representing a table row.
2171 * @copyright 2009 Nicolas Connault
2172 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2177 class html_table_row
{
2180 * @var string Value to use for the id attribute of the row.
2185 * @var array Array of html_table_cell objects
2187 public $cells = array();
2190 * @var string Value to use for the style attribute of the table row
2192 public $style = null;
2195 * @var array Attributes of additional HTML attributes for the <tr> element
2197 public $attributes = array();
2201 * @param array $cells
2203 public function __construct(array $cells=null) {
2204 $this->attributes
['class'] = '';
2205 $cells = (array)$cells;
2206 foreach ($cells as $cell) {
2207 if ($cell instanceof html_table_cell
) {
2208 $this->cells
[] = $cell;
2210 $this->cells
[] = new html_table_cell($cell);
2217 * Component representing a table cell.
2219 * @copyright 2009 Nicolas Connault
2220 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2225 class html_table_cell
{
2228 * @var string Value to use for the id attribute of the cell.
2233 * @var string The contents of the cell.
2238 * @var string Abbreviated version of the contents of the cell.
2240 public $abbr = null;
2243 * @var int Number of columns this cell should span.
2245 public $colspan = null;
2248 * @var int Number of rows this cell should span.
2250 public $rowspan = null;
2253 * @var string Defines a way to associate header cells and data cells in a table.
2255 public $scope = null;
2258 * @var bool Whether or not this cell is a header cell.
2260 public $header = null;
2263 * @var string Value to use for the style attribute of the table cell
2265 public $style = null;
2268 * @var array Attributes of additional HTML attributes for the <td> element
2270 public $attributes = array();
2273 * Constructs a table cell
2275 * @param string $text
2277 public function __construct($text = null) {
2278 $this->text
= $text;
2279 $this->attributes
['class'] = '';
2284 * Component representing a paging bar.
2286 * @copyright 2009 Nicolas Connault
2287 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2292 class paging_bar
implements renderable
{
2295 * @var int The maximum number of pagelinks to display.
2297 public $maxdisplay = 18;
2300 * @var int The total number of entries to be pages through..
2305 * @var int The page you are currently viewing.
2310 * @var int The number of entries that should be shown per page.
2315 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2316 * an equals sign and the page number.
2317 * If this is a moodle_url object then the pagevar param will be replaced by
2318 * the page no, for each page.
2323 * @var string This is the variable name that you use for the pagenumber in your
2324 * code (ie. 'tablepage', 'blogpage', etc)
2329 * @var string A HTML link representing the "previous" page.
2331 public $previouslink = null;
2334 * @var string A HTML link representing the "next" page.
2336 public $nextlink = null;
2339 * @var string A HTML link representing the first page.
2341 public $firstlink = null;
2344 * @var string A HTML link representing the last page.
2346 public $lastlink = null;
2349 * @var array An array of strings. One of them is just a string: the current page
2351 public $pagelinks = array();
2354 * Constructor paging_bar with only the required params.
2356 * @param int $totalcount The total number of entries available to be paged through
2357 * @param int $page The page you are currently viewing
2358 * @param int $perpage The number of entries that should be shown per page
2359 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2360 * @param string $pagevar name of page parameter that holds the page number
2362 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2363 $this->totalcount
= $totalcount;
2364 $this->page
= $page;
2365 $this->perpage
= $perpage;
2366 $this->baseurl
= $baseurl;
2367 $this->pagevar
= $pagevar;
2371 * Prepares the paging bar for output.
2373 * This method validates the arguments set up for the paging bar and then
2374 * produces fragments of HTML to assist display later on.
2376 * @param renderer_base $output
2377 * @param moodle_page $page
2378 * @param string $target
2379 * @throws coding_exception
2381 public function prepare(renderer_base
$output, moodle_page
$page, $target) {
2382 if (!isset($this->totalcount
) ||
is_null($this->totalcount
)) {
2383 throw new coding_exception('paging_bar requires a totalcount value.');
2385 if (!isset($this->page
) ||
is_null($this->page
)) {
2386 throw new coding_exception('paging_bar requires a page value.');
2388 if (empty($this->perpage
)) {
2389 throw new coding_exception('paging_bar requires a perpage value.');
2391 if (empty($this->baseurl
)) {
2392 throw new coding_exception('paging_bar requires a baseurl value.');
2395 if ($this->totalcount
> $this->perpage
) {
2396 $pagenum = $this->page
- 1;
2398 if ($this->page
> 0) {
2399 $this->previouslink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2402 if ($this->perpage
> 0) {
2403 $lastpage = ceil($this->totalcount
/ $this->perpage
);
2408 if ($this->page
> round(($this->maxdisplay
/3)*2)) {
2409 $currpage = $this->page
- round($this->maxdisplay
/3);
2411 $this->firstlink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>0)), '1', array('class'=>'first'));
2416 $displaycount = $displaypage = 0;
2418 while ($displaycount < $this->maxdisplay
and $currpage < $lastpage) {
2419 $displaypage = $currpage +
1;
2421 if ($this->page
== $currpage) {
2422 $this->pagelinks
[] = html_writer
::span($displaypage, 'current-page');
2424 $pagelink = html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$currpage)), $displaypage);
2425 $this->pagelinks
[] = $pagelink;
2432 if ($currpage < $lastpage) {
2433 $lastpageactual = $lastpage - 1;
2434 $this->lastlink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$lastpageactual)), $lastpage, array('class'=>'last'));
2437 $pagenum = $this->page +
1;
2439 if ($pagenum != $displaypage) {
2440 $this->nextlink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$pagenum)), get_string('next'), array('class'=>'next'));
2447 * This class represents how a block appears on a page.
2449 * During output, each block instance is asked to return a block_contents object,
2450 * those are then passed to the $OUTPUT->block function for display.
2452 * contents should probably be generated using a moodle_block_..._renderer.
2454 * Other block-like things that need to appear on the page, for example the
2455 * add new block UI, are also represented as block_contents objects.
2457 * @copyright 2009 Tim Hunt
2458 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2463 class block_contents
{
2465 /** Used when the block cannot be collapsed **/
2466 const NOT_HIDEABLE
= 0;
2468 /** Used when the block can be collapsed but currently is not **/
2471 /** Used when the block has been collapsed **/
2475 * @var int Used to set $skipid.
2477 protected static $idcounter = 1;
2480 * @var int All the blocks (or things that look like blocks) printed on
2481 * a page are given a unique number that can be used to construct id="" attributes.
2482 * This is set automatically be the {@link prepare()} method.
2483 * Do not try to set it manually.
2488 * @var int If this is the contents of a real block, this should be set
2489 * to the block_instance.id. Otherwise this should be set to 0.
2491 public $blockinstanceid = 0;
2494 * @var int If this is a real block instance, and there is a corresponding
2495 * block_position.id for the block on this page, this should be set to that id.
2496 * Otherwise it should be 0.
2498 public $blockpositionid = 0;
2501 * @var array An array of attribute => value pairs that are put on the outer div of this
2502 * block. {@link $id} and {@link $classes} attributes should be set separately.
2507 * @var string The title of this block. If this came from user input, it should already
2508 * have had format_string() processing done on it. This will be output inside
2509 * <h2> tags. Please do not cause invalid XHTML.
2514 * @var string The label to use when the block does not, or will not have a visible title.
2515 * You should never set this as well as title... it will just be ignored.
2517 public $arialabel = '';
2520 * @var string HTML for the content
2522 public $content = '';
2525 * @var array An alternative to $content, it you want a list of things with optional icons.
2527 public $footer = '';
2530 * @var string Any small print that should appear under the block to explain
2531 * to the teacher about the block, for example 'This is a sticky block that was
2532 * added in the system context.'
2534 public $annotation = '';
2537 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2538 * the user can toggle whether this block is visible.
2540 public $collapsible = self
::NOT_HIDEABLE
;
2543 * Set this to true if the block is dockable.
2546 public $dockable = false;
2549 * @var array A (possibly empty) array of editing controls. Each element of
2550 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2551 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2553 public $controls = array();
2557 * Create new instance of block content
2558 * @param array $attributes
2560 public function __construct(array $attributes = null) {
2561 $this->skipid
= self
::$idcounter;
2562 self
::$idcounter +
= 1;
2566 $this->attributes
= $attributes;
2568 // simple "fake" blocks used in some modules and "Add new block" block
2569 $this->attributes
= array('class'=>'block');
2574 * Add html class to block
2576 * @param string $class
2578 public function add_class($class) {
2579 $this->attributes
['class'] .= ' '.$class;
2585 * This class represents a target for where a block can go when it is being moved.
2587 * This needs to be rendered as a form with the given hidden from fields, and
2588 * clicking anywhere in the form should submit it. The form action should be
2591 * @copyright 2009 Tim Hunt
2592 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2597 class block_move_target
{
2600 * @var moodle_url Move url
2606 * @param moodle_url $url
2608 public function __construct(moodle_url
$url) {
2616 * This class is used to represent one item within a custom menu that may or may
2617 * not have children.
2619 * @copyright 2010 Sam Hemelryk
2620 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2625 class custom_menu_item
implements renderable
{
2628 * @var string The text to show for the item
2633 * @var moodle_url The link to give the icon if it has no children
2638 * @var string A title to apply to the item. By default the text
2643 * @var int A sort order for the item, not necessary if you order things in
2649 * @var custom_menu_item A reference to the parent for this item or NULL if
2650 * it is a top level item
2655 * @var array A array in which to store children this item has.
2657 protected $children = array();
2660 * @var int A reference to the sort var of the last child that was added
2662 protected $lastsort = 0;
2665 * Constructs the new custom menu item
2667 * @param string $text
2668 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2669 * @param string $title A title to apply to this item [Optional]
2670 * @param int $sort A sort or to use if we need to sort differently [Optional]
2671 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2672 * belongs to, only if the child has a parent. [Optional]
2674 public function __construct($text, moodle_url
$url=null, $title=null, $sort = null, custom_menu_item
$parent = null) {
2675 $this->text
= $text;
2677 $this->title
= $title;
2678 $this->sort
= (int)$sort;
2679 $this->parent
= $parent;
2683 * Adds a custom menu item as a child of this node given its properties.
2685 * @param string $text
2686 * @param moodle_url $url
2687 * @param string $title
2689 * @return custom_menu_item
2691 public function add($text, moodle_url
$url = null, $title = null, $sort = null) {
2692 $key = count($this->children
);
2694 $sort = $this->lastsort +
1;
2696 $this->children
[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2697 $this->lastsort
= (int)$sort;
2698 return $this->children
[$key];
2702 * Removes a custom menu item that is a child or descendant to the current menu.
2704 * Returns true if child was found and removed.
2706 * @param custom_menu_item $menuitem
2709 public function remove_child(custom_menu_item
$menuitem) {
2711 if (($key = array_search($menuitem, $this->children
)) !== false) {
2712 unset($this->children
[$key]);
2713 $this->children
= array_values($this->children
);
2716 foreach ($this->children
as $child) {
2717 if ($removed = $child->remove_child($menuitem)) {
2726 * Returns the text for this item
2729 public function get_text() {
2734 * Returns the url for this item
2735 * @return moodle_url
2737 public function get_url() {
2742 * Returns the title for this item
2745 public function get_title() {
2746 return $this->title
;
2750 * Sorts and returns the children for this item
2753 public function get_children() {
2755 return $this->children
;
2759 * Gets the sort order for this child
2762 public function get_sort_order() {
2767 * Gets the parent this child belong to
2768 * @return custom_menu_item
2770 public function get_parent() {
2771 return $this->parent
;
2775 * Sorts the children this item has
2777 public function sort() {
2778 usort($this->children
, array('custom_menu','sort_custom_menu_items'));
2782 * Returns true if this item has any children
2785 public function has_children() {
2786 return (count($this->children
) > 0);
2790 * Sets the text for the node
2791 * @param string $text
2793 public function set_text($text) {
2794 $this->text
= (string)$text;
2798 * Sets the title for the node
2799 * @param string $title
2801 public function set_title($title) {
2802 $this->title
= (string)$title;
2806 * Sets the url for the node
2807 * @param moodle_url $url
2809 public function set_url(moodle_url
$url) {
2817 * This class is used to operate a custom menu that can be rendered for the page.
2818 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2819 * of custom_menu_item nodes that can be rendered by the core renderer.
2821 * To configure the custom menu:
2822 * Settings: Administration > Appearance > Themes > Theme settings
2824 * @copyright 2010 Sam Hemelryk
2825 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2830 class custom_menu
extends custom_menu_item
{
2833 * @var string The language we should render for, null disables multilang support.
2835 protected $currentlanguage = null;
2838 * Creates the custom menu
2840 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2841 * @param string $currentlanguage the current language code, null disables multilang support
2843 public function __construct($definition = '', $currentlanguage = null) {
2844 $this->currentlanguage
= $currentlanguage;
2845 parent
::__construct('root'); // create virtual root element of the menu
2846 if (!empty($definition)) {
2847 $this->override_children(self
::convert_text_to_menu_nodes($definition, $currentlanguage));
2852 * Overrides the children of this custom menu. Useful when getting children
2853 * from $CFG->custommenuitems
2855 * @param array $children
2857 public function override_children(array $children) {
2858 $this->children
= array();
2859 foreach ($children as $child) {
2860 if ($child instanceof custom_menu_item
) {
2861 $this->children
[] = $child;
2867 * Converts a string into a structured array of custom_menu_items which can
2868 * then be added to a custom menu.
2871 * text|url|title|langs
2872 * The number of hyphens at the start determines the depth of the item. The
2873 * languages are optional, comma separated list of languages the line is for.
2875 * Example structure:
2876 * First level first item|http://www.moodle.com/
2877 * -Second level first item|http://www.moodle.com/partners/
2878 * -Second level second item|http://www.moodle.com/hq/
2879 * --Third level first item|http://www.moodle.com/jobs/
2880 * -Second level third item|http://www.moodle.com/development/
2881 * First level second item|http://www.moodle.com/feedback/
2882 * First level third item
2883 * English only|http://moodle.com|English only item|en
2884 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2888 * @param string $text the menu items definition
2889 * @param string $language the language code, null disables multilang support
2892 public static function convert_text_to_menu_nodes($text, $language = null) {
2893 $root = new custom_menu();
2896 $hiddenitems = array();
2897 $lines = explode("\n", $text);
2898 foreach ($lines as $linenumber => $line) {
2899 $line = trim($line);
2900 if (strlen($line) == 0) {
2903 // Parse item settings.
2907 $itemvisible = true;
2908 $settings = explode('|', $line);
2909 foreach ($settings as $i => $setting) {
2910 $setting = trim($setting);
2911 if (!empty($setting)) {
2914 $itemtext = ltrim($setting, '-');
2915 $itemtitle = $itemtext;
2919 $itemurl = new moodle_url($setting);
2920 } catch (moodle_exception
$exception) {
2921 // We're not actually worried about this, we don't want to mess up the display
2922 // just for a wrongly entered URL.
2927 $itemtitle = $setting;
2930 if (!empty($language)) {
2931 $itemlanguages = array_map('trim', explode(',', $setting));
2932 $itemvisible &= in_array($language, $itemlanguages);
2938 // Get depth of new item.
2939 preg_match('/^(\-*)/', $line, $match);
2940 $itemdepth = strlen($match[1]) +
1;
2941 // Find parent item for new item.
2942 while (($lastdepth - $itemdepth) >= 0) {
2943 $lastitem = $lastitem->get_parent();
2946 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber +
1);
2948 if (!$itemvisible) {
2949 $hiddenitems[] = $lastitem;
2952 foreach ($hiddenitems as $item) {
2953 $item->parent
->remove_child($item);
2955 return $root->get_children();
2959 * Sorts two custom menu items
2961 * This function is designed to be used with the usort method
2962 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2965 * @param custom_menu_item $itema
2966 * @param custom_menu_item $itemb
2969 public static function sort_custom_menu_items(custom_menu_item
$itema, custom_menu_item
$itemb) {
2970 $itema = $itema->get_sort_order();
2971 $itemb = $itemb->get_sort_order();
2972 if ($itema == $itemb) {
2975 return ($itema > $itemb) ? +
1 : -1;
2982 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2985 class tabobject
implements renderable
{
2986 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
2988 /** @var moodle_url|string link */
2990 /** @var string text on the tab */
2992 /** @var string title under the link, by defaul equals to text */
2994 /** @var bool whether to display a link under the tab name when it's selected */
2995 var $linkedwhenselected = false;
2996 /** @var bool whether the tab is inactive */
2997 var $inactive = false;
2998 /** @var bool indicates that this tab's child is selected */
2999 var $activated = false;
3000 /** @var bool indicates that this tab is selected */
3001 var $selected = false;
3002 /** @var array stores children tabobjects */
3003 var $subtree = array();
3004 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
3010 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
3011 * @param string|moodle_url $link
3012 * @param string $text text on the tab
3013 * @param string $title title under the link, by defaul equals to text
3014 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
3016 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
3018 $this->link
= $link;
3019 $this->text
= $text;
3020 $this->title
= $title ?
$title : $text;
3021 $this->linkedwhenselected
= $linkedwhenselected;
3025 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
3027 * @param string $selected the id of the selected tab (whatever row it's on),
3028 * if null marks all tabs as unselected
3029 * @return bool whether this tab is selected or contains selected tab in its subtree
3031 protected function set_selected($selected) {
3032 if ((string)$selected === (string)$this->id
) {
3033 $this->selected
= true;
3034 // This tab is selected. No need to travel through subtree.
3037 foreach ($this->subtree
as $subitem) {
3038 if ($subitem->set_selected($selected)) {
3039 // This tab has child that is selected. Mark it as activated. No need to check other children.
3040 $this->activated
= true;
3048 * Travels through tree and finds a tab with specified id
3051 * @return tabtree|null
3053 public function find($id) {
3054 if ((string)$this->id
=== (string)$id) {
3057 foreach ($this->subtree
as $tab) {
3058 if ($obj = $tab->find($id)) {
3066 * Allows to mark each tab's level in the tree before rendering.
3070 protected function set_level($level) {
3071 $this->level
= $level;
3072 foreach ($this->subtree
as $tab) {
3073 $tab->set_level($level +
1);
3081 * Example how to print a single line tabs:
3083 * new tabobject(...),
3084 * new tabobject(...)
3086 * echo $OUTPUT->tabtree($rows, $selectedid);
3088 * Multiple row tabs may not look good on some devices but if you want to use them
3089 * you can specify ->subtree for the active tabobject.
3091 * @copyright 2013 Marina Glancy
3092 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3097 class tabtree
extends tabobject
{
3101 * It is highly recommended to call constructor when list of tabs is already
3102 * populated, this way you ensure that selected and inactive tabs are located
3103 * and attribute level is set correctly.
3105 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3106 * @param string|null $selected which tab to mark as selected, all parent tabs will
3107 * automatically be marked as activated
3108 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3109 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3111 public function __construct($tabs, $selected = null, $inactive = null) {
3112 $this->subtree
= $tabs;
3113 if ($selected !== null) {
3114 $this->set_selected($selected);
3116 if ($inactive !== null) {
3117 if (is_array($inactive)) {
3118 foreach ($inactive as $id) {
3119 if ($tab = $this->find($id)) {
3120 $tab->inactive
= true;
3123 } else if ($tab = $this->find($inactive)) {
3124 $tab->inactive
= true;
3127 $this->set_level(0);
3134 * This action menu component takes a series of primary and secondary actions.
3135 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
3140 * @copyright 2013 Sam Hemelryk
3141 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3143 class action_menu
implements renderable
{
3146 * Top right alignment.
3151 * Top right alignment.
3156 * Top right alignment.
3161 * Top right alignment.
3166 * The instance number. This is unique to this instance of the action menu.
3169 protected $instance = 0;
3172 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
3175 protected $primaryactions = array();
3178 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
3181 protected $secondaryactions = array();
3184 * An array of attributes added to the container of the action menu.
3185 * Initialised with defaults during construction.
3188 public $attributes = array();
3190 * An array of attributes added to the container of the primary actions.
3191 * Initialised with defaults during construction.
3194 public $attributesprimary = array();
3196 * An array of attributes added to the container of the secondary actions.
3197 * Initialised with defaults during construction.
3200 public $attributessecondary = array();
3203 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
3206 public $actiontext = null;
3209 * An icon to use for the toggling the secondary menu (dropdown).
3215 * Any text to use for the toggling the secondary menu (dropdown).
3218 public $menutrigger = '';
3221 * Place the action menu before all other actions.
3224 public $prioritise = false;
3227 * Constructs the action menu with the given items.
3229 * @param array $actions An array of actions.
3231 public function __construct(array $actions = array()) {
3232 static $initialised = 0;
3233 $this->instance
= $initialised;
3236 $this->attributes
= array(
3237 'id' => 'action-menu-'.$this->instance
,
3238 'class' => 'moodle-actionmenu',
3239 'data-enhance' => 'moodle-core-actionmenu'
3241 $this->attributesprimary
= array(
3242 'id' => 'action-menu-'.$this->instance
.'-menubar',
3243 'class' => 'menubar',
3246 $this->attributessecondary
= array(
3247 'id' => 'action-menu-'.$this->instance
.'-menu',
3249 'data-rel' => 'menu-content',
3250 'aria-labelledby' => 'action-menu-toggle-'.$this->instance
,
3253 $this->set_alignment(self
::TR
, self
::BR
);
3254 foreach ($actions as $action) {
3255 $this->add($action);
3259 public function set_menu_trigger($trigger) {
3260 $this->menutrigger
= $trigger;
3264 * Initialises JS required fore the action menu.
3265 * The JS is only required once as it manages all action menu's on the page.
3267 * @param moodle_page $page
3269 public function initialise_js(moodle_page
$page) {
3270 static $initialised = false;
3271 if (!$initialised) {
3272 $page->requires
->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
3273 $initialised = true;
3278 * Adds an action to this action menu.
3280 * @param action_menu_link|pix_icon|string $action
3282 public function add($action) {
3283 if ($action instanceof action_link
) {
3284 if ($action->primary
) {
3285 $this->add_primary_action($action);
3287 $this->add_secondary_action($action);
3289 } else if ($action instanceof pix_icon
) {
3290 $this->add_primary_action($action);
3292 $this->add_secondary_action($action);
3297 * Adds a primary action to the action menu.
3299 * @param action_menu_link|action_link|pix_icon|string $action
3301 public function add_primary_action($action) {
3302 if ($action instanceof action_link ||
$action instanceof pix_icon
) {
3303 $action->attributes
['role'] = 'menuitem';
3304 if ($action instanceof action_menu_link
) {
3305 $action->actionmenu
= $this;
3308 $this->primaryactions
[] = $action;
3312 * Adds a secondary action to the action menu.
3314 * @param action_link|pix_icon|string $action
3316 public function add_secondary_action($action) {
3317 if ($action instanceof action_link ||
$action instanceof pix_icon
) {
3318 $action->attributes
['role'] = 'menuitem';
3319 if ($action instanceof action_menu_link
) {
3320 $action->actionmenu
= $this;
3323 $this->secondaryactions
[] = $action;
3327 * Returns the primary actions ready to be rendered.
3329 * @param core_renderer $output The renderer to use for getting icons.
3332 public function get_primary_actions(core_renderer
$output = null) {
3334 if ($output === null) {
3337 $pixicon = $this->actionicon
;
3338 $linkclasses = array('toggle-display');
3341 if (!empty($this->menutrigger
)) {
3342 $pixicon = '<b class="caret"></b>';
3343 $linkclasses[] = 'textmenu';
3345 $title = new lang_string('actions', 'moodle');
3346 $this->actionicon
= new pix_icon(
3350 array('class' => 'iconsmall actionmenu', 'title' => '')
3352 $pixicon = $this->actionicon
;
3354 if ($pixicon instanceof renderable
) {
3355 $pixicon = $output->render($pixicon);
3356 if ($pixicon instanceof pix_icon
&& isset($pixicon->attributes
['alt'])) {
3357 $title = $pixicon->attributes
['alt'];
3361 if ($this->actiontext
) {
3362 $string = $this->actiontext
;
3364 $actions = $this->primaryactions
;
3365 $attributes = array(
3366 'class' => implode(' ', $linkclasses),
3368 'id' => 'action-menu-toggle-'.$this->instance
,
3369 'role' => 'menuitem'
3371 $link = html_writer
::link('#', $string . $this->menutrigger
. $pixicon, $attributes);
3372 if ($this->prioritise
) {
3373 array_unshift($actions, $link);
3381 * Returns the secondary actions ready to be rendered.
3384 public function get_secondary_actions() {
3385 return $this->secondaryactions
;
3389 * Sets the selector that should be used to find the owning node of this menu.
3390 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
3392 public function set_owner_selector($selector) {
3393 $this->attributes
['data-owner'] = $selector;
3397 * Sets the alignment of the dialogue in relation to button used to toggle it.
3399 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3400 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3402 public function set_alignment($dialogue, $button) {
3403 if (isset($this->attributessecondary
['data-align'])) {
3404 // We've already got one set, lets remove the old class so as to avoid troubles.
3405 $class = $this->attributessecondary
['class'];
3406 $search = 'align-'.$this->attributessecondary
['data-align'];
3407 $this->attributessecondary
['class'] = str_replace($search, '', $class);
3409 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
3410 $this->attributessecondary
['data-align'] = $align;
3411 $this->attributessecondary
['class'] .= ' align-'.$align;
3415 * Returns a string to describe the alignment.
3417 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3420 protected function get_align_string($align) {
3436 * Sets a constraint for the dialogue.
3438 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
3439 * element the constraint identifies.
3441 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
3443 public function set_constraint($ancestorselector) {
3444 $this->attributessecondary
['data-constraint'] = $ancestorselector;
3448 * If you call this method the action menu will be displayed but will not be enhanced.
3450 * By not displaying the menu enhanced all items will be displayed in a single row.
3452 public function do_not_enhance() {
3453 unset($this->attributes
['data-enhance']);
3457 * Returns true if this action menu will be enhanced.
3461 public function will_be_enhanced() {
3462 return isset($this->attributes
['data-enhance']);
3466 * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
3468 * This property can be useful when the action menu is displayed within a parent element that is either floated
3469 * or relatively positioned.
3470 * In that situation the width of the menu is determined by the width of the parent element which may not be large
3471 * enough for the menu items without them wrapping.
3472 * This disables the wrapping so that the menu takes on the width of the longest item.
3474 * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
3476 public function set_nowrap_on_items($value = true) {
3477 $class = 'nowrap-items';
3478 if (!empty($this->attributes
['class'])) {
3479 $pos = strpos($this->attributes
['class'], $class);
3480 if ($value === true && $pos === false) {
3481 // The value is true and the class has not been set yet. Add it.
3482 $this->attributes
['class'] .= ' '.$class;
3483 } else if ($value === false && $pos !== false) {
3484 // The value is false and the class has been set. Remove it.
3485 $this->attributes
['class'] = substr($this->attributes
['class'], $pos, strlen($class));
3487 } else if ($value) {
3488 // The value is true and the class has not been set yet. Add it.
3489 $this->attributes
['class'] = $class;
3495 * An action menu filler
3499 * @copyright 2013 Andrew Nicols
3500 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3502 class action_menu_filler
extends action_link
implements renderable
{
3505 * True if this is a primary action. False if not.
3508 public $primary = true;
3511 * Constructs the object.
3513 public function __construct() {
3518 * An action menu action
3522 * @copyright 2013 Sam Hemelryk
3523 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3525 class action_menu_link
extends action_link
implements renderable
{
3528 * True if this is a primary action. False if not.
3531 public $primary = true;
3534 * The action menu this link has been added to.
3537 public $actionmenu = null;
3540 * Constructs the object.
3542 * @param moodle_url $url The URL for the action.
3543 * @param pix_icon $icon The icon to represent the action.
3544 * @param string $text The text to represent the action.
3545 * @param bool $primary Whether this is a primary action or not.
3546 * @param array $attributes Any attribtues associated with the action.
3548 public function __construct(moodle_url
$url, pix_icon
$icon = null, $text, $primary = true, array $attributes = array()) {
3549 parent
::__construct($url, $text, null, $attributes, $icon);
3550 $this->primary
= (bool)$primary;
3551 $this->add_class('menu-action');
3552 $this->attributes
['role'] = 'menuitem';
3557 * A primary action menu action
3561 * @copyright 2013 Sam Hemelryk
3562 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3564 class action_menu_link_primary
extends action_menu_link
{
3566 * Constructs the object.
3568 * @param moodle_url $url
3569 * @param pix_icon $icon
3570 * @param string $text
3571 * @param array $attributes
3573 public function __construct(moodle_url
$url, pix_icon
$icon = null, $text, array $attributes = array()) {
3574 parent
::__construct($url, $icon, $text, true, $attributes);
3579 * A secondary action menu action
3583 * @copyright 2013 Sam Hemelryk
3584 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3586 class action_menu_link_secondary
extends action_menu_link
{
3588 * Constructs the object.
3590 * @param moodle_url $url
3591 * @param pix_icon $icon
3592 * @param string $text
3593 * @param array $attributes
3595 public function __construct(moodle_url
$url, pix_icon
$icon = null, $text, array $attributes = array()) {
3596 parent
::__construct($url, $icon, $text, false, $attributes);