Merge branch 'MDL-37621-master-fix2' of git://github.com/damyon/moodle
[moodle.git] / lib / outputcomponents.php
blobd3091751e707864b0f0cee9fbc2f579d51573d7d
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
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.
8 //
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/>.
17 /**
18 * Classes representing HTML elements, used by $OUTPUT methods
20 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
21 * for an overview.
23 * @package core
24 * @category output
25 * @copyright 2009 Tim Hunt
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') || die();
31 /**
32 * Interface marking other classes as suitable for renderer_base::render()
34 * @copyright 2010 Petr Skoda (skodak) info@skodak.org
35 * @package core
36 * @category output
38 interface renderable {
39 // intentionally empty
42 /**
43 * Data structure representing a file picker.
45 * @copyright 2010 Dongsheng Cai
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
47 * @since Moodle 2.0
48 * @package core
49 * @category output
51 class file_picker implements renderable {
53 /**
54 * @var stdClass An object containing options for the file picker
56 public $options;
58 /**
59 * Constructs a file picker object.
61 * The following are possible options for the filepicker:
62 * - accepted_types (*)
63 * - return_types (FILE_INTERNAL)
64 * - env (filepicker)
65 * - client_id (uniqid)
66 * - itemid (0)
67 * - maxbytes (-1)
68 * - maxfiles (1)
69 * - buttonname (false)
71 * @param stdClass $options An object containing options for the file picker.
73 public function __construct(stdClass $options) {
74 global $CFG, $USER, $PAGE;
75 require_once($CFG->dirroot. '/repository/lib.php');
76 $defaults = array(
77 'accepted_types'=>'*',
78 'return_types'=>FILE_INTERNAL,
79 'env' => 'filepicker',
80 'client_id' => uniqid(),
81 'itemid' => 0,
82 'maxbytes'=>-1,
83 'maxfiles'=>1,
84 'buttonname'=>false
86 foreach ($defaults as $key=>$value) {
87 if (empty($options->$key)) {
88 $options->$key = $value;
92 $options->currentfile = '';
93 if (!empty($options->itemid)) {
94 $fs = get_file_storage();
95 $usercontext = context_user::instance($USER->id);
96 if (empty($options->filename)) {
97 if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
98 $file = reset($files);
100 } else {
101 $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
103 if (!empty($file)) {
104 $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
108 // initilise options, getting files in root path
109 $this->options = initialise_filepicker($options);
111 // copying other options
112 foreach ($options as $name=>$value) {
113 if (!isset($this->options->$name)) {
114 $this->options->$name = $value;
121 * Data structure representing a user picture.
123 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
124 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
125 * @since Modle 2.0
126 * @package core
127 * @category output
129 class user_picture implements renderable {
131 * @var array List of mandatory fields in user record here. (do not include
132 * TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
134 protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'imagealt', 'email');
137 * @var stdClass A user object with at least fields all columns specified
138 * in $fields array constant set.
140 public $user;
143 * @var int The course id. Used when constructing the link to the user's
144 * profile, page course id used if not specified.
146 public $courseid;
149 * @var bool Add course profile link to image
151 public $link = true;
154 * @var int Size in pixels. Special values are (true/1 = 100px) and
155 * (false/0 = 35px)
156 * for backward compatibility.
158 public $size = 35;
161 * @var bool Add non-blank alt-text to the image.
162 * Default true, set to false when image alt just duplicates text in screenreaders.
164 public $alttext = true;
167 * @var bool Whether or not to open the link in a popup window.
169 public $popup = false;
172 * @var string Image class attribute
174 public $class = 'userpicture';
177 * User picture constructor.
179 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
180 * It is recommended to add also contextid of the user for performance reasons.
182 public function __construct(stdClass $user) {
183 global $DB;
185 if (empty($user->id)) {
186 throw new coding_exception('User id is required when printing user avatar image.');
189 // only touch the DB if we are missing data and complain loudly...
190 $needrec = false;
191 foreach (self::$fields as $field) {
192 if (!array_key_exists($field, $user)) {
193 $needrec = true;
194 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
195 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
196 break;
200 if ($needrec) {
201 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
202 } else {
203 $this->user = clone($user);
208 * Returns a list of required user fields, useful when fetching required user info from db.
210 * In some cases we have to fetch the user data together with some other information,
211 * the idalias is useful there because the id would otherwise override the main
212 * id of the result record. Please note it has to be converted back to id before rendering.
214 * @param string $tableprefix name of database table prefix in query
215 * @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)
216 * @param string $idalias alias of id field
217 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
218 * @return string
220 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
221 if (!$tableprefix and !$extrafields and !$idalias) {
222 return implode(',', self::$fields);
224 if ($tableprefix) {
225 $tableprefix .= '.';
227 $fields = array();
228 foreach (self::$fields as $field) {
229 if ($field === 'id' and $idalias and $idalias !== 'id') {
230 $fields[$field] = "$tableprefix$field AS $idalias";
231 } else {
232 if ($fieldprefix and $field !== 'id') {
233 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
234 } else {
235 $fields[$field] = "$tableprefix$field";
239 // add extra fields if not already there
240 if ($extrafields) {
241 foreach ($extrafields as $e) {
242 if ($e === 'id' or isset($fields[$e])) {
243 continue;
245 if ($fieldprefix) {
246 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
247 } else {
248 $fields[$e] = "$tableprefix$e";
252 return implode(',', $fields);
256 * Extract the aliased user fields from a given record
258 * Given a record that was previously obtained using {@link self::fields()} with aliases,
259 * this method extracts user related unaliased fields.
261 * @param stdClass $record containing user picture fields
262 * @param array $extrafields extra fields included in the $record
263 * @param string $idalias alias of the id field
264 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
265 * @return stdClass object with unaliased user fields
267 public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
269 if (empty($idalias)) {
270 $idalias = 'id';
273 $return = new stdClass();
275 foreach (self::$fields as $field) {
276 if ($field === 'id') {
277 if (property_exists($record, $idalias)) {
278 $return->id = $record->{$idalias};
280 } else {
281 if (property_exists($record, $fieldprefix.$field)) {
282 $return->{$field} = $record->{$fieldprefix.$field};
286 // add extra fields if not already there
287 if ($extrafields) {
288 foreach ($extrafields as $e) {
289 if ($e === 'id' or property_exists($return, $e)) {
290 continue;
292 $return->{$e} = $record->{$fieldprefix.$e};
296 return $return;
300 * Works out the URL for the users picture.
302 * This method is recommended as it avoids costly redirects of user pictures
303 * if requests are made for non-existent files etc.
305 * @param moodle_page $page
306 * @param renderer_base $renderer
307 * @return moodle_url
309 public function get_url(moodle_page $page, renderer_base $renderer = null) {
310 global $CFG;
312 if (is_null($renderer)) {
313 $renderer = $page->get_renderer('core');
316 // Sort out the filename and size. Size is only required for the gravatar
317 // implementation presently.
318 if (empty($this->size)) {
319 $filename = 'f2';
320 $size = 35;
321 } else if ($this->size === true or $this->size == 1) {
322 $filename = 'f1';
323 $size = 100;
324 } else if ($this->size > 100) {
325 $filename = 'f3';
326 $size = (int)$this->size;
327 } else if ($this->size >= 50) {
328 $filename = 'f1';
329 $size = (int)$this->size;
330 } else {
331 $filename = 'f2';
332 $size = (int)$this->size;
335 $defaulturl = $renderer->pix_url('u/'.$filename); // default image
337 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
338 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
339 // Protect images if login required and not logged in;
340 // also if login is required for profile images and is not logged in or guest
341 // do not use require_login() because it is expensive and not suitable here anyway.
342 return $defaulturl;
345 // First try to detect deleted users - but do not read from database for performance reasons!
346 if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
347 // All deleted users should have email replaced by md5 hash,
348 // all active users are expected to have valid email.
349 return $defaulturl;
352 // Did the user upload a picture?
353 if ($this->user->picture > 0) {
354 if (!empty($this->user->contextid)) {
355 $contextid = $this->user->contextid;
356 } else {
357 $context = context_user::instance($this->user->id, IGNORE_MISSING);
358 if (!$context) {
359 // This must be an incorrectly deleted user, all other users have context.
360 return $defaulturl;
362 $contextid = $context->id;
365 $path = '/';
366 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
367 // We append the theme name to the file path if we have it so that
368 // in the circumstance that the profile picture is not available
369 // when the user actually requests it they still get the profile
370 // picture for the correct theme.
371 $path .= $page->theme->name.'/';
373 // Set the image URL to the URL for the uploaded file and return.
374 $url = moodle_url::make_pluginfile_url($contextid, 'user', 'icon', NULL, $path, $filename);
375 $url->param('rev', $this->user->picture);
376 return $url;
379 if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
380 // Normalise the size variable to acceptable bounds
381 if ($size < 1 || $size > 512) {
382 $size = 35;
384 // Hash the users email address
385 $md5 = md5(strtolower(trim($this->user->email)));
386 // Build a gravatar URL with what we know.
388 // Find the best default image URL we can (MDL-35669)
389 if (empty($CFG->gravatardefaulturl)) {
390 $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
391 if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
392 $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
393 } else {
394 $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
396 } else {
397 $gravatardefault = $CFG->gravatardefaulturl;
400 // If the currently requested page is https then we'll return an
401 // https gravatar page.
402 if (strpos($CFG->httpswwwroot, 'https:') === 0) {
403 $gravatardefault = str_replace($CFG->wwwroot, $CFG->httpswwwroot, $gravatardefault); // Replace by secure url.
404 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
405 } else {
406 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
410 return $defaulturl;
415 * Data structure representing a help icon.
417 * @copyright 2010 Petr Skoda (info@skodak.org)
418 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
419 * @since Moodle 2.0
420 * @package core
421 * @category output
423 class help_icon implements renderable {
426 * @var string lang pack identifier (without the "_help" suffix),
427 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
428 * must exist.
430 public $identifier;
433 * @var string Component name, the same as in get_string()
435 public $component;
438 * @var string Extra descriptive text next to the icon
440 public $linktext = null;
443 * Constructor
445 * @param string $identifier string for help page title,
446 * string with _help suffix is used for the actual help text.
447 * string with _link suffix is used to create a link to further info (if it exists)
448 * @param string $component
450 public function __construct($identifier, $component) {
451 $this->identifier = $identifier;
452 $this->component = $component;
456 * Verifies that both help strings exists, shows debug warnings if not
458 public function diag_strings() {
459 $sm = get_string_manager();
460 if (!$sm->string_exists($this->identifier, $this->component)) {
461 debugging("Help title string does not exist: [$this->identifier, $this->component]");
463 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
464 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
471 * Data structure representing an icon.
473 * @copyright 2010 Petr Skoda
474 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
475 * @since Moodle 2.0
476 * @package core
477 * @category output
479 class pix_icon implements renderable {
482 * @var string The icon name
484 var $pix;
487 * @var string The component the icon belongs to.
489 var $component;
492 * @var array An array of attributes to use on the icon
494 var $attributes = array();
497 * Constructor
499 * @param string $pix short icon name
500 * @param string $alt The alt text to use for the icon
501 * @param string $component component name
502 * @param array $attributes html attributes
504 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
505 $this->pix = $pix;
506 $this->component = $component;
507 $this->attributes = (array)$attributes;
509 $this->attributes['alt'] = $alt;
510 if (empty($this->attributes['class'])) {
511 $this->attributes['class'] = 'smallicon';
513 if (!isset($this->attributes['title'])) {
514 $this->attributes['title'] = $this->attributes['alt'];
515 } else if (empty($this->attributes['title'])) {
516 // Remove the title attribute if empty, we probably want to use the parent node's title
517 // and some browsers might overwrite it with an empty title.
518 unset($this->attributes['title']);
524 * Data structure representing an emoticon image
526 * @copyright 2010 David Mudrak
527 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
528 * @since Moodle 2.0
529 * @package core
530 * @category output
532 class pix_emoticon extends pix_icon implements renderable {
535 * Constructor
536 * @param string $pix short icon name
537 * @param string $alt alternative text
538 * @param string $component emoticon image provider
539 * @param array $attributes explicit HTML attributes
541 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
542 if (empty($attributes['class'])) {
543 $attributes['class'] = 'emoticon';
545 parent::__construct($pix, $alt, $component, $attributes);
550 * Data structure representing a simple form with only one button.
552 * @copyright 2009 Petr Skoda
553 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
554 * @since Moodle 2.0
555 * @package core
556 * @category output
558 class single_button implements renderable {
561 * @var moodle_url Target url
563 var $url;
566 * @var string Button label
568 var $label;
571 * @var string Form submit method post or get
573 var $method = 'post';
576 * @var string Wrapping div class
578 var $class = 'singlebutton';
581 * @var bool True if button disabled, false if normal
583 var $disabled = false;
586 * @var string Button tooltip
588 var $tooltip = null;
591 * @var string Form id
593 var $formid;
596 * @var array List of attached actions
598 var $actions = array();
601 * Constructor
602 * @param moodle_url $url
603 * @param string $label button text
604 * @param string $method get or post submit method
606 public function __construct(moodle_url $url, $label, $method='post') {
607 $this->url = clone($url);
608 $this->label = $label;
609 $this->method = $method;
613 * Shortcut for adding a JS confirm dialog when the button is clicked.
614 * The message must be a yes/no question.
616 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
618 public function add_confirm_action($confirmmessage) {
619 $this->add_action(new confirm_action($confirmmessage));
623 * Add action to the button.
624 * @param component_action $action
626 public function add_action(component_action $action) {
627 $this->actions[] = $action;
633 * Simple form with just one select field that gets submitted automatically.
635 * If JS not enabled small go button is printed too.
637 * @copyright 2009 Petr Skoda
638 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
639 * @since Moodle 2.0
640 * @package core
641 * @category output
643 class single_select implements renderable {
646 * @var moodle_url Target url - includes hidden fields
648 var $url;
651 * @var string Name of the select element.
653 var $name;
656 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
657 * it is also possible to specify optgroup as complex label array ex.:
658 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
659 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
661 var $options;
664 * @var string Selected option
666 var $selected;
669 * @var array Nothing selected
671 var $nothing;
674 * @var array Extra select field attributes
676 var $attributes = array();
679 * @var string Button label
681 var $label = '';
684 * @var array Button label's attributes
686 var $labelattributes = array();
689 * @var string Form submit method post or get
691 var $method = 'get';
694 * @var string Wrapping div class
696 var $class = 'singleselect';
699 * @var bool True if button disabled, false if normal
701 var $disabled = false;
704 * @var string Button tooltip
706 var $tooltip = null;
709 * @var string Form id
711 var $formid = null;
714 * @var array List of attached actions
716 var $helpicon = null;
719 * Constructor
720 * @param moodle_url $url form action target, includes hidden fields
721 * @param string $name name of selection field - the changing parameter in url
722 * @param array $options list of options
723 * @param string $selected selected element
724 * @param array $nothing
725 * @param string $formid
727 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
728 $this->url = $url;
729 $this->name = $name;
730 $this->options = $options;
731 $this->selected = $selected;
732 $this->nothing = $nothing;
733 $this->formid = $formid;
737 * Shortcut for adding a JS confirm dialog when the button is clicked.
738 * The message must be a yes/no question.
740 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
742 public function add_confirm_action($confirmmessage) {
743 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
747 * Add action to the button.
749 * @param component_action $action
751 public function add_action(component_action $action) {
752 $this->actions[] = $action;
756 * Adds help icon.
758 * @deprecated since Moodle 2.0
760 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
761 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
765 * Adds help icon.
767 * @param string $identifier The keyword that defines a help page
768 * @param string $component
770 public function set_help_icon($identifier, $component = 'moodle') {
771 $this->helpicon = new help_icon($identifier, $component);
775 * Sets select's label
777 * @param string $label
778 * @param array $attributes (optional)
780 public function set_label($label, $attributes = array()) {
781 $this->label = $label;
782 $this->labelattributes = $attributes;
788 * Simple URL selection widget description.
790 * @copyright 2009 Petr Skoda
791 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
792 * @since Moodle 2.0
793 * @package core
794 * @category output
796 class url_select implements renderable {
798 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
799 * it is also possible to specify optgroup as complex label array ex.:
800 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
801 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
803 var $urls;
806 * @var string Selected option
808 var $selected;
811 * @var array Nothing selected
813 var $nothing;
816 * @var array Extra select field attributes
818 var $attributes = array();
821 * @var string Button label
823 var $label = '';
826 * @var array Button label's attributes
828 var $labelattributes = array();
831 * @var string Wrapping div class
833 var $class = 'urlselect';
836 * @var bool True if button disabled, false if normal
838 var $disabled = false;
841 * @var string Button tooltip
843 var $tooltip = null;
846 * @var string Form id
848 var $formid = null;
851 * @var array List of attached actions
853 var $helpicon = null;
856 * @var string If set, makes button visible with given name for button
858 var $showbutton = null;
861 * Constructor
862 * @param array $urls list of options
863 * @param string $selected selected element
864 * @param array $nothing
865 * @param string $formid
866 * @param string $showbutton Set to text of button if it should be visible
867 * or null if it should be hidden (hidden version always has text 'go')
869 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
870 $this->urls = $urls;
871 $this->selected = $selected;
872 $this->nothing = $nothing;
873 $this->formid = $formid;
874 $this->showbutton = $showbutton;
878 * Adds help icon.
880 * @deprecated since Moodle 2.0
882 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
883 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
887 * Adds help icon.
889 * @param string $identifier The keyword that defines a help page
890 * @param string $component
892 public function set_help_icon($identifier, $component = 'moodle') {
893 $this->helpicon = new help_icon($identifier, $component);
897 * Sets select's label
899 * @param string $label
900 * @param array $attributes (optional)
902 public function set_label($label, $attributes = array()) {
903 $this->label = $label;
904 $this->labelattributes = $attributes;
909 * Data structure describing html link with special action attached.
911 * @copyright 2010 Petr Skoda
912 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
913 * @since Moodle 2.0
914 * @package core
915 * @category output
917 class action_link implements renderable {
920 * @var moodle_url Href url
922 var $url;
925 * @var string Link text HTML fragment
927 var $text;
930 * @var array HTML attributes
932 var $attributes;
935 * @var array List of actions attached to link
937 var $actions;
940 * Constructor
941 * @param moodle_url $url
942 * @param string $text HTML fragment
943 * @param component_action $action
944 * @param array $attributes associative array of html link attributes + disabled
946 public function __construct(moodle_url $url, $text, component_action $action = null, array $attributes = null) {
947 $this->url = clone($url);
948 $this->text = $text;
949 $this->attributes = (array)$attributes;
950 if ($action) {
951 $this->add_action($action);
956 * Add action to the link.
958 * @param component_action $action
960 public function add_action(component_action $action) {
961 $this->actions[] = $action;
965 * Adds a CSS class to this action link object
966 * @param string $class
968 public function add_class($class) {
969 if (empty($this->attributes['class'])) {
970 $this->attributes['class'] = $class;
971 } else {
972 $this->attributes['class'] .= ' ' . $class;
978 * Simple html output class
980 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
981 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
982 * @since Moodle 2.0
983 * @package core
984 * @category output
986 class html_writer {
989 * Outputs a tag with attributes and contents
991 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
992 * @param string $contents What goes between the opening and closing tags
993 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
994 * @return string HTML fragment
996 public static function tag($tagname, $contents, array $attributes = null) {
997 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1001 * Outputs an opening tag with attributes
1003 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1004 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1005 * @return string HTML fragment
1007 public static function start_tag($tagname, array $attributes = null) {
1008 return '<' . $tagname . self::attributes($attributes) . '>';
1012 * Outputs a closing tag
1014 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1015 * @return string HTML fragment
1017 public static function end_tag($tagname) {
1018 return '</' . $tagname . '>';
1022 * Outputs an empty tag with attributes
1024 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1025 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1026 * @return string HTML fragment
1028 public static function empty_tag($tagname, array $attributes = null) {
1029 return '<' . $tagname . self::attributes($attributes) . ' />';
1033 * Outputs a tag, but only if the contents are not empty
1035 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1036 * @param string $contents What goes between the opening and closing tags
1037 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1038 * @return string HTML fragment
1040 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1041 if ($contents === '' || is_null($contents)) {
1042 return '';
1044 return self::tag($tagname, $contents, $attributes);
1048 * Outputs a HTML attribute and value
1050 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1051 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1052 * @return string HTML fragment
1054 public static function attribute($name, $value) {
1055 if ($value instanceof moodle_url) {
1056 return ' ' . $name . '="' . $value->out() . '"';
1059 // special case, we do not want these in output
1060 if ($value === null) {
1061 return '';
1064 // no sloppy trimming here!
1065 return ' ' . $name . '="' . s($value) . '"';
1069 * Outputs a list of HTML attributes and values
1071 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1072 * The values will be escaped with {@link s()}
1073 * @return string HTML fragment
1075 public static function attributes(array $attributes = null) {
1076 $attributes = (array)$attributes;
1077 $output = '';
1078 foreach ($attributes as $name => $value) {
1079 $output .= self::attribute($name, $value);
1081 return $output;
1085 * Generates random html element id.
1087 * @staticvar int $counter
1088 * @staticvar type $uniq
1089 * @param string $base A string fragment that will be included in the random ID.
1090 * @return string A unique ID
1092 public static function random_id($base='random') {
1093 static $counter = 0;
1094 static $uniq;
1096 if (!isset($uniq)) {
1097 $uniq = uniqid();
1100 $counter++;
1101 return $base.$uniq.$counter;
1105 * Generates a simple html link
1107 * @param string|moodle_url $url The URL
1108 * @param string $text The text
1109 * @param array $attributes HTML attributes
1110 * @return string HTML fragment
1112 public static function link($url, $text, array $attributes = null) {
1113 $attributes = (array)$attributes;
1114 $attributes['href'] = $url;
1115 return self::tag('a', $text, $attributes);
1119 * Generates a simple checkbox with optional label
1121 * @param string $name The name of the checkbox
1122 * @param string $value The value of the checkbox
1123 * @param bool $checked Whether the checkbox is checked
1124 * @param string $label The label for the checkbox
1125 * @param array $attributes Any attributes to apply to the checkbox
1126 * @return string html fragment
1128 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1129 $attributes = (array)$attributes;
1130 $output = '';
1132 if ($label !== '' and !is_null($label)) {
1133 if (empty($attributes['id'])) {
1134 $attributes['id'] = self::random_id('checkbox_');
1137 $attributes['type'] = 'checkbox';
1138 $attributes['value'] = $value;
1139 $attributes['name'] = $name;
1140 $attributes['checked'] = $checked ? 'checked' : null;
1142 $output .= self::empty_tag('input', $attributes);
1144 if ($label !== '' and !is_null($label)) {
1145 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1148 return $output;
1152 * Generates a simple select yes/no form field
1154 * @param string $name name of select element
1155 * @param bool $selected
1156 * @param array $attributes - html select element attributes
1157 * @return string HTML fragment
1159 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1160 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1161 return self::select($options, $name, $selected, null, $attributes);
1165 * Generates a simple select form field
1167 * @param array $options associative array value=>label ex.:
1168 * array(1=>'One, 2=>Two)
1169 * it is also possible to specify optgroup as complex label array ex.:
1170 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1171 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1172 * @param string $name name of select element
1173 * @param string|array $selected value or array of values depending on multiple attribute
1174 * @param array|bool $nothing add nothing selected option, or false of not added
1175 * @param array $attributes html select element attributes
1176 * @return string HTML fragment
1178 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1179 $attributes = (array)$attributes;
1180 if (is_array($nothing)) {
1181 foreach ($nothing as $k=>$v) {
1182 if ($v === 'choose' or $v === 'choosedots') {
1183 $nothing[$k] = get_string('choosedots');
1186 $options = $nothing + $options; // keep keys, do not override
1188 } else if (is_string($nothing) and $nothing !== '') {
1189 // BC
1190 $options = array(''=>$nothing) + $options;
1193 // we may accept more values if multiple attribute specified
1194 $selected = (array)$selected;
1195 foreach ($selected as $k=>$v) {
1196 $selected[$k] = (string)$v;
1199 if (!isset($attributes['id'])) {
1200 $id = 'menu'.$name;
1201 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1202 $id = str_replace('[', '', $id);
1203 $id = str_replace(']', '', $id);
1204 $attributes['id'] = $id;
1207 if (!isset($attributes['class'])) {
1208 $class = 'menu'.$name;
1209 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1210 $class = str_replace('[', '', $class);
1211 $class = str_replace(']', '', $class);
1212 $attributes['class'] = $class;
1214 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
1216 $attributes['name'] = $name;
1218 if (!empty($attributes['disabled'])) {
1219 $attributes['disabled'] = 'disabled';
1220 } else {
1221 unset($attributes['disabled']);
1224 $output = '';
1225 foreach ($options as $value=>$label) {
1226 if (is_array($label)) {
1227 // ignore key, it just has to be unique
1228 $output .= self::select_optgroup(key($label), current($label), $selected);
1229 } else {
1230 $output .= self::select_option($label, $value, $selected);
1233 return self::tag('select', $output, $attributes);
1237 * Returns HTML to display a select box option.
1239 * @param string $label The label to display as the option.
1240 * @param string|int $value The value the option represents
1241 * @param array $selected An array of selected options
1242 * @return string HTML fragment
1244 private static function select_option($label, $value, array $selected) {
1245 $attributes = array();
1246 $value = (string)$value;
1247 if (in_array($value, $selected, true)) {
1248 $attributes['selected'] = 'selected';
1250 $attributes['value'] = $value;
1251 return self::tag('option', $label, $attributes);
1255 * Returns HTML to display a select box option group.
1257 * @param string $groupname The label to use for the group
1258 * @param array $options The options in the group
1259 * @param array $selected An array of selected values.
1260 * @return string HTML fragment.
1262 private static function select_optgroup($groupname, $options, array $selected) {
1263 if (empty($options)) {
1264 return '';
1266 $attributes = array('label'=>$groupname);
1267 $output = '';
1268 foreach ($options as $value=>$label) {
1269 $output .= self::select_option($label, $value, $selected);
1271 return self::tag('optgroup', $output, $attributes);
1275 * This is a shortcut for making an hour selector menu.
1277 * @param string $type The type of selector (years, months, days, hours, minutes)
1278 * @param string $name fieldname
1279 * @param int $currenttime A default timestamp in GMT
1280 * @param int $step minute spacing
1281 * @param array $attributes - html select element attributes
1282 * @return HTML fragment
1284 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1285 if (!$currenttime) {
1286 $currenttime = time();
1288 $currentdate = usergetdate($currenttime);
1289 $userdatetype = $type;
1290 $timeunits = array();
1292 switch ($type) {
1293 case 'years':
1294 for ($i=1970; $i<=2020; $i++) {
1295 $timeunits[$i] = $i;
1297 $userdatetype = 'year';
1298 break;
1299 case 'months':
1300 for ($i=1; $i<=12; $i++) {
1301 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1303 $userdatetype = 'month';
1304 $currentdate['month'] = (int)$currentdate['mon'];
1305 break;
1306 case 'days':
1307 for ($i=1; $i<=31; $i++) {
1308 $timeunits[$i] = $i;
1310 $userdatetype = 'mday';
1311 break;
1312 case 'hours':
1313 for ($i=0; $i<=23; $i++) {
1314 $timeunits[$i] = sprintf("%02d",$i);
1316 break;
1317 case 'minutes':
1318 if ($step != 1) {
1319 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1322 for ($i=0; $i<=59; $i+=$step) {
1323 $timeunits[$i] = sprintf("%02d",$i);
1325 break;
1326 default:
1327 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1330 if (empty($attributes['id'])) {
1331 $attributes['id'] = self::random_id('ts_');
1333 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1334 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1336 return $label.$timerselector;
1340 * Shortcut for quick making of lists
1342 * Note: 'list' is a reserved keyword ;-)
1344 * @param array $items
1345 * @param array $attributes
1346 * @param string $tag ul or ol
1347 * @return string
1349 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1350 $output = '';
1352 foreach ($items as $item) {
1353 $output .= html_writer::start_tag('li') . "\n";
1354 $output .= $item . "\n";
1355 $output .= html_writer::end_tag('li') . "\n";
1358 return html_writer::tag($tag, $output, $attributes);
1362 * Returns hidden input fields created from url parameters.
1364 * @param moodle_url $url
1365 * @param array $exclude list of excluded parameters
1366 * @return string HTML fragment
1368 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1369 $exclude = (array)$exclude;
1370 $params = $url->params();
1371 foreach ($exclude as $key) {
1372 unset($params[$key]);
1375 $output = '';
1376 foreach ($params as $key => $value) {
1377 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1378 $output .= self::empty_tag('input', $attributes)."\n";
1380 return $output;
1384 * Generate a script tag containing the the specified code.
1386 * @param string $jscode the JavaScript code
1387 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
1388 * @return string HTML, the code wrapped in <script> tags.
1390 public static function script($jscode, $url=null) {
1391 if ($jscode) {
1392 $attributes = array('type'=>'text/javascript');
1393 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1395 } else if ($url) {
1396 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1397 return self::tag('script', '', $attributes) . "\n";
1399 } else {
1400 return '';
1405 * Renders HTML table
1407 * This method may modify the passed instance by adding some default properties if they are not set yet.
1408 * If this is not what you want, you should make a full clone of your data before passing them to this
1409 * method. In most cases this is not an issue at all so we do not clone by default for performance
1410 * and memory consumption reasons.
1412 * @param html_table $table data to be rendered
1413 * @return string HTML code
1415 public static function table(html_table $table) {
1416 // prepare table data and populate missing properties with reasonable defaults
1417 if (!empty($table->align)) {
1418 foreach ($table->align as $key => $aa) {
1419 if ($aa) {
1420 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1421 } else {
1422 $table->align[$key] = null;
1426 if (!empty($table->size)) {
1427 foreach ($table->size as $key => $ss) {
1428 if ($ss) {
1429 $table->size[$key] = 'width:'. $ss .';';
1430 } else {
1431 $table->size[$key] = null;
1435 if (!empty($table->wrap)) {
1436 foreach ($table->wrap as $key => $ww) {
1437 if ($ww) {
1438 $table->wrap[$key] = 'white-space:nowrap;';
1439 } else {
1440 $table->wrap[$key] = '';
1444 if (!empty($table->head)) {
1445 foreach ($table->head as $key => $val) {
1446 if (!isset($table->align[$key])) {
1447 $table->align[$key] = null;
1449 if (!isset($table->size[$key])) {
1450 $table->size[$key] = null;
1452 if (!isset($table->wrap[$key])) {
1453 $table->wrap[$key] = null;
1458 if (empty($table->attributes['class'])) {
1459 $table->attributes['class'] = 'generaltable';
1461 if (!empty($table->tablealign)) {
1462 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1465 // explicitly assigned properties override those defined via $table->attributes
1466 $table->attributes['class'] = trim($table->attributes['class']);
1467 $attributes = array_merge($table->attributes, array(
1468 'id' => $table->id,
1469 'width' => $table->width,
1470 'summary' => $table->summary,
1471 'cellpadding' => $table->cellpadding,
1472 'cellspacing' => $table->cellspacing,
1474 $output = html_writer::start_tag('table', $attributes) . "\n";
1476 $countcols = 0;
1478 if (!empty($table->head)) {
1479 $countcols = count($table->head);
1481 $output .= html_writer::start_tag('thead', array()) . "\n";
1482 $output .= html_writer::start_tag('tr', array()) . "\n";
1483 $keys = array_keys($table->head);
1484 $lastkey = end($keys);
1486 foreach ($table->head as $key => $heading) {
1487 // Convert plain string headings into html_table_cell objects
1488 if (!($heading instanceof html_table_cell)) {
1489 $headingtext = $heading;
1490 $heading = new html_table_cell();
1491 $heading->text = $headingtext;
1492 $heading->header = true;
1495 if ($heading->header !== false) {
1496 $heading->header = true;
1499 if ($heading->header && empty($heading->scope)) {
1500 $heading->scope = 'col';
1503 $heading->attributes['class'] .= ' header c' . $key;
1504 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1505 $heading->colspan = $table->headspan[$key];
1506 $countcols += $table->headspan[$key] - 1;
1509 if ($key == $lastkey) {
1510 $heading->attributes['class'] .= ' lastcol';
1512 if (isset($table->colclasses[$key])) {
1513 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1515 $heading->attributes['class'] = trim($heading->attributes['class']);
1516 $attributes = array_merge($heading->attributes, array(
1517 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1518 'scope' => $heading->scope,
1519 'colspan' => $heading->colspan,
1522 $tagtype = 'td';
1523 if ($heading->header === true) {
1524 $tagtype = 'th';
1526 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1528 $output .= html_writer::end_tag('tr') . "\n";
1529 $output .= html_writer::end_tag('thead') . "\n";
1531 if (empty($table->data)) {
1532 // For valid XHTML strict every table must contain either a valid tr
1533 // or a valid tbody... both of which must contain a valid td
1534 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1535 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1536 $output .= html_writer::end_tag('tbody');
1540 if (!empty($table->data)) {
1541 $oddeven = 1;
1542 $keys = array_keys($table->data);
1543 $lastrowkey = end($keys);
1544 $output .= html_writer::start_tag('tbody', array());
1546 foreach ($table->data as $key => $row) {
1547 if (($row === 'hr') && ($countcols)) {
1548 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1549 } else {
1550 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1551 if (!($row instanceof html_table_row)) {
1552 $newrow = new html_table_row();
1554 foreach ($row as $cell) {
1555 if (!($cell instanceof html_table_cell)) {
1556 $cell = new html_table_cell($cell);
1558 $newrow->cells[] = $cell;
1560 $row = $newrow;
1563 $oddeven = $oddeven ? 0 : 1;
1564 if (isset($table->rowclasses[$key])) {
1565 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1568 $row->attributes['class'] .= ' r' . $oddeven;
1569 if ($key == $lastrowkey) {
1570 $row->attributes['class'] .= ' lastrow';
1573 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1574 $keys2 = array_keys($row->cells);
1575 $lastkey = end($keys2);
1577 $gotlastkey = false; //flag for sanity checking
1578 foreach ($row->cells as $key => $cell) {
1579 if ($gotlastkey) {
1580 //This should never happen. Why do we have a cell after the last cell?
1581 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1584 if (!($cell instanceof html_table_cell)) {
1585 $mycell = new html_table_cell();
1586 $mycell->text = $cell;
1587 $cell = $mycell;
1590 if (($cell->header === true) && empty($cell->scope)) {
1591 $cell->scope = 'row';
1594 if (isset($table->colclasses[$key])) {
1595 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1598 $cell->attributes['class'] .= ' cell c' . $key;
1599 if ($key == $lastkey) {
1600 $cell->attributes['class'] .= ' lastcol';
1601 $gotlastkey = true;
1603 $tdstyle = '';
1604 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1605 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1606 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1607 $cell->attributes['class'] = trim($cell->attributes['class']);
1608 $tdattributes = array_merge($cell->attributes, array(
1609 'style' => $tdstyle . $cell->style,
1610 'colspan' => $cell->colspan,
1611 'rowspan' => $cell->rowspan,
1612 'id' => $cell->id,
1613 'abbr' => $cell->abbr,
1614 'scope' => $cell->scope,
1616 $tagtype = 'td';
1617 if ($cell->header === true) {
1618 $tagtype = 'th';
1620 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1623 $output .= html_writer::end_tag('tr') . "\n";
1625 $output .= html_writer::end_tag('tbody') . "\n";
1627 $output .= html_writer::end_tag('table') . "\n";
1629 return $output;
1633 * Renders form element label
1635 * By default, the label is suffixed with a label separator defined in the
1636 * current language pack (colon by default in the English lang pack).
1637 * Adding the colon can be explicitly disabled if needed. Label separators
1638 * are put outside the label tag itself so they are not read by
1639 * screenreaders (accessibility).
1641 * Parameter $for explicitly associates the label with a form control. When
1642 * set, the value of this attribute must be the same as the value of
1643 * the id attribute of the form control in the same document. When null,
1644 * the label being defined is associated with the control inside the label
1645 * element.
1647 * @param string $text content of the label tag
1648 * @param string|null $for id of the element this label is associated with, null for no association
1649 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1650 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1651 * @return string HTML of the label element
1653 public static function label($text, $for, $colonize = true, array $attributes=array()) {
1654 if (!is_null($for)) {
1655 $attributes = array_merge($attributes, array('for' => $for));
1657 $text = trim($text);
1658 $label = self::tag('label', $text, $attributes);
1660 // TODO MDL-12192 $colonize disabled for now yet
1661 // if (!empty($text) and $colonize) {
1662 // // the $text may end with the colon already, though it is bad string definition style
1663 // $colon = get_string('labelsep', 'langconfig');
1664 // if (!empty($colon)) {
1665 // $trimmed = trim($colon);
1666 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1667 // //debugging('The label text should not end with colon or other label separator,
1668 // // please fix the string definition.', DEBUG_DEVELOPER);
1669 // } else {
1670 // $label .= $colon;
1671 // }
1672 // }
1673 // }
1675 return $label;
1679 * Combines a class parameter with other attributes. Aids in code reduction
1680 * because the class parameter is very frequently used.
1682 * If the class attribute is specified both in the attributes and in the
1683 * class parameter, the two values are combined with a space between.
1685 * @param string $class Optional CSS class (or classes as space-separated list)
1686 * @param array $attributes Optional other attributes as array
1687 * @return array Attributes (or null if still none)
1689 private static function add_class($class = '', array $attributes = null) {
1690 if ($class !== '') {
1691 $classattribute = array('class' => $class);
1692 if ($attributes) {
1693 if (array_key_exists('class', $attributes)) {
1694 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
1695 } else {
1696 $attributes = $classattribute + $attributes;
1698 } else {
1699 $attributes = $classattribute;
1702 return $attributes;
1706 * Creates a <div> tag. (Shortcut function.)
1708 * @param string $content HTML content of tag
1709 * @param string $class Optional CSS class (or classes as space-separated list)
1710 * @param array $attributes Optional other attributes as array
1711 * @return string HTML code for div
1713 public static function div($content, $class = '', array $attributes = null) {
1714 return self::tag('div', $content, self::add_class($class, $attributes));
1718 * Starts a <div> tag. (Shortcut function.)
1720 * @param string $class Optional CSS class (or classes as space-separated list)
1721 * @param array $attributes Optional other attributes as array
1722 * @return string HTML code for open div tag
1724 public static function start_div($class = '', array $attributes = null) {
1725 return self::start_tag('div', self::add_class($class, $attributes));
1729 * Ends a <div> tag. (Shortcut function.)
1731 * @return string HTML code for close div tag
1733 public static function end_div() {
1734 return self::end_tag('div');
1738 * Creates a <span> tag. (Shortcut function.)
1740 * @param string $content HTML content of tag
1741 * @param string $class Optional CSS class (or classes as space-separated list)
1742 * @param array $attributes Optional other attributes as array
1743 * @return string HTML code for span
1745 public static function span($content, $class = '', array $attributes = null) {
1746 return self::tag('span', $content, self::add_class($class, $attributes));
1750 * Starts a <span> tag. (Shortcut function.)
1752 * @param string $class Optional CSS class (or classes as space-separated list)
1753 * @param array $attributes Optional other attributes as array
1754 * @return string HTML code for open span tag
1756 public static function start_span($class = '', array $attributes = null) {
1757 return self::start_tag('span', self::add_class($class, $attributes));
1761 * Ends a <span> tag. (Shortcut function.)
1763 * @return string HTML code for close span tag
1765 public static function end_span() {
1766 return self::end_tag('span');
1771 * Simple javascript output class
1773 * @copyright 2010 Petr Skoda
1774 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1775 * @since Moodle 2.0
1776 * @package core
1777 * @category output
1779 class js_writer {
1782 * Returns javascript code calling the function
1784 * @param string $function function name, can be complex like Y.Event.purgeElement
1785 * @param array $arguments parameters
1786 * @param int $delay execution delay in seconds
1787 * @return string JS code fragment
1789 public static function function_call($function, array $arguments = null, $delay=0) {
1790 if ($arguments) {
1791 $arguments = array_map('json_encode', convert_to_array($arguments));
1792 $arguments = implode(', ', $arguments);
1793 } else {
1794 $arguments = '';
1796 $js = "$function($arguments);";
1798 if ($delay) {
1799 $delay = $delay * 1000; // in miliseconds
1800 $js = "setTimeout(function() { $js }, $delay);";
1802 return $js . "\n";
1806 * Special function which adds Y as first argument of function call.
1808 * @param string $function The function to call
1809 * @param array $extraarguments Any arguments to pass to it
1810 * @return string Some JS code
1812 public static function function_call_with_Y($function, array $extraarguments = null) {
1813 if ($extraarguments) {
1814 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1815 $arguments = 'Y, ' . implode(', ', $extraarguments);
1816 } else {
1817 $arguments = 'Y';
1819 return "$function($arguments);\n";
1823 * Returns JavaScript code to initialise a new object
1825 * @param string $var If it is null then no var is assigned the new object.
1826 * @param string $class The class to initialise an object for.
1827 * @param array $arguments An array of args to pass to the init method.
1828 * @param array $requirements Any modules required for this class.
1829 * @param int $delay The delay before initialisation. 0 = no delay.
1830 * @return string Some JS code
1832 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1833 if (is_array($arguments)) {
1834 $arguments = array_map('json_encode', convert_to_array($arguments));
1835 $arguments = implode(', ', $arguments);
1838 if ($var === null) {
1839 $js = "new $class(Y, $arguments);";
1840 } else if (strpos($var, '.')!==false) {
1841 $js = "$var = new $class(Y, $arguments);";
1842 } else {
1843 $js = "var $var = new $class(Y, $arguments);";
1846 if ($delay) {
1847 $delay = $delay * 1000; // in miliseconds
1848 $js = "setTimeout(function() { $js }, $delay);";
1851 if (count($requirements) > 0) {
1852 $requirements = implode("', '", $requirements);
1853 $js = "Y.use('$requirements', function(Y){ $js });";
1855 return $js."\n";
1859 * Returns code setting value to variable
1861 * @param string $name
1862 * @param mixed $value json serialised value
1863 * @param bool $usevar add var definition, ignored for nested properties
1864 * @return string JS code fragment
1866 public static function set_variable($name, $value, $usevar = true) {
1867 $output = '';
1869 if ($usevar) {
1870 if (strpos($name, '.')) {
1871 $output .= '';
1872 } else {
1873 $output .= 'var ';
1877 $output .= "$name = ".json_encode($value).";";
1879 return $output;
1883 * Writes event handler attaching code
1885 * @param array|string $selector standard YUI selector for elements, may be
1886 * array or string, element id is in the form "#idvalue"
1887 * @param string $event A valid DOM event (click, mousedown, change etc.)
1888 * @param string $function The name of the function to call
1889 * @param array $arguments An optional array of argument parameters to pass to the function
1890 * @return string JS code fragment
1892 public static function event_handler($selector, $event, $function, array $arguments = null) {
1893 $selector = json_encode($selector);
1894 $output = "Y.on('$event', $function, $selector, null";
1895 if (!empty($arguments)) {
1896 $output .= ', ' . json_encode($arguments);
1898 return $output . ");\n";
1903 * Holds all the information required to render a <table> by {@link core_renderer::table()}
1905 * Example of usage:
1906 * $t = new html_table();
1907 * ... // set various properties of the object $t as described below
1908 * echo html_writer::table($t);
1910 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1911 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1912 * @since Moodle 2.0
1913 * @package core
1914 * @category output
1916 class html_table {
1919 * @var string Value to use for the id attribute of the table
1921 public $id = null;
1924 * @var array Attributes of HTML attributes for the <table> element
1926 public $attributes = array();
1929 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
1930 * For more control over the rendering of the headers, an array of html_table_cell objects
1931 * can be passed instead of an array of strings.
1933 * Example of usage:
1934 * $t->head = array('Student', 'Grade');
1936 public $head;
1939 * @var array An array that can be used to make a heading span multiple columns.
1940 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1941 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
1943 * Example of usage:
1944 * $t->headspan = array(2,1);
1946 public $headspan;
1949 * @var array An array of column alignments.
1950 * The value is used as CSS 'text-align' property. Therefore, possible
1951 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1952 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1954 * Examples of usage:
1955 * $t->align = array(null, 'right');
1956 * or
1957 * $t->align[1] = 'right';
1959 public $align;
1962 * @var array The value is used as CSS 'size' property.
1964 * Examples of usage:
1965 * $t->size = array('50%', '50%');
1966 * or
1967 * $t->size[1] = '120px';
1969 public $size;
1972 * @var array An array of wrapping information.
1973 * The only possible value is 'nowrap' that sets the
1974 * CSS property 'white-space' to the value 'nowrap' in the given column.
1976 * Example of usage:
1977 * $t->wrap = array(null, 'nowrap');
1979 public $wrap;
1982 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
1983 * $head specified, the string 'hr' (for horizontal ruler) can be used
1984 * instead of an array of cells data resulting in a divider rendered.
1986 * Example of usage with array of arrays:
1987 * $row1 = array('Harry Potter', '76 %');
1988 * $row2 = array('Hermione Granger', '100 %');
1989 * $t->data = array($row1, $row2);
1991 * Example with array of html_table_row objects: (used for more fine-grained control)
1992 * $cell1 = new html_table_cell();
1993 * $cell1->text = 'Harry Potter';
1994 * $cell1->colspan = 2;
1995 * $row1 = new html_table_row();
1996 * $row1->cells[] = $cell1;
1997 * $cell2 = new html_table_cell();
1998 * $cell2->text = 'Hermione Granger';
1999 * $cell3 = new html_table_cell();
2000 * $cell3->text = '100 %';
2001 * $row2 = new html_table_row();
2002 * $row2->cells = array($cell2, $cell3);
2003 * $t->data = array($row1, $row2);
2005 public $data;
2008 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2009 * @var string Width of the table, percentage of the page preferred.
2011 public $width = null;
2014 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2015 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2017 public $tablealign = null;
2020 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2021 * @var int Padding on each cell, in pixels
2023 public $cellpadding = null;
2026 * @var int Spacing between cells, in pixels
2027 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2029 public $cellspacing = null;
2032 * @var array Array of classes to add to particular rows, space-separated string.
2033 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
2034 * respectively. Class 'lastrow' is added automatically for the last row
2035 * in the table.
2037 * Example of usage:
2038 * $t->rowclasses[9] = 'tenth'
2040 public $rowclasses;
2043 * @var array An array of classes to add to every cell in a particular column,
2044 * space-separated string. Class 'cell' is added automatically by the renderer.
2045 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2046 * respectively. Class 'lastcol' is added automatically for all last cells
2047 * in a row.
2049 * Example of usage:
2050 * $t->colclasses = array(null, 'grade');
2052 public $colclasses;
2055 * @var string Description of the contents for screen readers.
2057 public $summary;
2060 * Constructor
2062 public function __construct() {
2063 $this->attributes['class'] = '';
2068 * Component representing a table row.
2070 * @copyright 2009 Nicolas Connault
2071 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2072 * @since Moodle 2.0
2073 * @package core
2074 * @category output
2076 class html_table_row {
2079 * @var string Value to use for the id attribute of the row.
2081 public $id = null;
2084 * @var array Array of html_table_cell objects
2086 public $cells = array();
2089 * @var string Value to use for the style attribute of the table row
2091 public $style = null;
2094 * @var array Attributes of additional HTML attributes for the <tr> element
2096 public $attributes = array();
2099 * Constructor
2100 * @param array $cells
2102 public function __construct(array $cells=null) {
2103 $this->attributes['class'] = '';
2104 $cells = (array)$cells;
2105 foreach ($cells as $cell) {
2106 if ($cell instanceof html_table_cell) {
2107 $this->cells[] = $cell;
2108 } else {
2109 $this->cells[] = new html_table_cell($cell);
2116 * Component representing a table cell.
2118 * @copyright 2009 Nicolas Connault
2119 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2120 * @since Moodle 2.0
2121 * @package core
2122 * @category output
2124 class html_table_cell {
2127 * @var string Value to use for the id attribute of the cell.
2129 public $id = null;
2132 * @var string The contents of the cell.
2134 public $text;
2137 * @var string Abbreviated version of the contents of the cell.
2139 public $abbr = null;
2142 * @var int Number of columns this cell should span.
2144 public $colspan = null;
2147 * @var int Number of rows this cell should span.
2149 public $rowspan = null;
2152 * @var string Defines a way to associate header cells and data cells in a table.
2154 public $scope = null;
2157 * @var bool Whether or not this cell is a header cell.
2159 public $header = null;
2162 * @var string Value to use for the style attribute of the table cell
2164 public $style = null;
2167 * @var array Attributes of additional HTML attributes for the <td> element
2169 public $attributes = array();
2172 * Constructs a table cell
2174 * @param string $text
2176 public function __construct($text = null) {
2177 $this->text = $text;
2178 $this->attributes['class'] = '';
2183 * Component representing a paging bar.
2185 * @copyright 2009 Nicolas Connault
2186 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2187 * @since Moodle 2.0
2188 * @package core
2189 * @category output
2191 class paging_bar implements renderable {
2194 * @var int The maximum number of pagelinks to display.
2196 public $maxdisplay = 18;
2199 * @var int The total number of entries to be pages through..
2201 public $totalcount;
2204 * @var int The page you are currently viewing.
2206 public $page;
2209 * @var int The number of entries that should be shown per page.
2211 public $perpage;
2214 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2215 * an equals sign and the page number.
2216 * If this is a moodle_url object then the pagevar param will be replaced by
2217 * the page no, for each page.
2219 public $baseurl;
2222 * @var string This is the variable name that you use for the pagenumber in your
2223 * code (ie. 'tablepage', 'blogpage', etc)
2225 public $pagevar;
2228 * @var string A HTML link representing the "previous" page.
2230 public $previouslink = null;
2233 * @var string A HTML link representing the "next" page.
2235 public $nextlink = null;
2238 * @var string A HTML link representing the first page.
2240 public $firstlink = null;
2243 * @var string A HTML link representing the last page.
2245 public $lastlink = null;
2248 * @var array An array of strings. One of them is just a string: the current page
2250 public $pagelinks = array();
2253 * Constructor paging_bar with only the required params.
2255 * @param int $totalcount The total number of entries available to be paged through
2256 * @param int $page The page you are currently viewing
2257 * @param int $perpage The number of entries that should be shown per page
2258 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2259 * @param string $pagevar name of page parameter that holds the page number
2261 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2262 $this->totalcount = $totalcount;
2263 $this->page = $page;
2264 $this->perpage = $perpage;
2265 $this->baseurl = $baseurl;
2266 $this->pagevar = $pagevar;
2270 * Prepares the paging bar for output.
2272 * This method validates the arguments set up for the paging bar and then
2273 * produces fragments of HTML to assist display later on.
2275 * @param renderer_base $output
2276 * @param moodle_page $page
2277 * @param string $target
2278 * @throws coding_exception
2280 public function prepare(renderer_base $output, moodle_page $page, $target) {
2281 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2282 throw new coding_exception('paging_bar requires a totalcount value.');
2284 if (!isset($this->page) || is_null($this->page)) {
2285 throw new coding_exception('paging_bar requires a page value.');
2287 if (empty($this->perpage)) {
2288 throw new coding_exception('paging_bar requires a perpage value.');
2290 if (empty($this->baseurl)) {
2291 throw new coding_exception('paging_bar requires a baseurl value.');
2294 if ($this->totalcount > $this->perpage) {
2295 $pagenum = $this->page - 1;
2297 if ($this->page > 0) {
2298 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2301 if ($this->perpage > 0) {
2302 $lastpage = ceil($this->totalcount / $this->perpage);
2303 } else {
2304 $lastpage = 1;
2307 if ($this->page > round(($this->maxdisplay/3)*2)) {
2308 $currpage = $this->page - round($this->maxdisplay/3);
2310 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2311 } else {
2312 $currpage = 0;
2315 $displaycount = $displaypage = 0;
2317 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2318 $displaypage = $currpage + 1;
2320 if ($this->page == $currpage) {
2321 $this->pagelinks[] = $displaypage;
2322 } else {
2323 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2324 $this->pagelinks[] = $pagelink;
2327 $displaycount++;
2328 $currpage++;
2331 if ($currpage < $lastpage) {
2332 $lastpageactual = $lastpage - 1;
2333 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2336 $pagenum = $this->page + 1;
2338 if ($pagenum != $displaypage) {
2339 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2346 * This class represents how a block appears on a page.
2348 * During output, each block instance is asked to return a block_contents object,
2349 * those are then passed to the $OUTPUT->block function for display.
2351 * contents should probably be generated using a moodle_block_..._renderer.
2353 * Other block-like things that need to appear on the page, for example the
2354 * add new block UI, are also represented as block_contents objects.
2356 * @copyright 2009 Tim Hunt
2357 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2358 * @since Moodle 2.0
2359 * @package core
2360 * @category output
2362 class block_contents {
2364 /** Used when the block cannot be collapsed **/
2365 const NOT_HIDEABLE = 0;
2367 /** Used when the block can be collapsed but currently is not **/
2368 const VISIBLE = 1;
2370 /** Used when the block has been collapsed **/
2371 const HIDDEN = 2;
2374 * @var int Used to set $skipid.
2376 protected static $idcounter = 1;
2379 * @var int All the blocks (or things that look like blocks) printed on
2380 * a page are given a unique number that can be used to construct id="" attributes.
2381 * This is set automatically be the {@link prepare()} method.
2382 * Do not try to set it manually.
2384 public $skipid;
2387 * @var int If this is the contents of a real block, this should be set
2388 * to the block_instance.id. Otherwise this should be set to 0.
2390 public $blockinstanceid = 0;
2393 * @var int If this is a real block instance, and there is a corresponding
2394 * block_position.id for the block on this page, this should be set to that id.
2395 * Otherwise it should be 0.
2397 public $blockpositionid = 0;
2400 * @var array An array of attribute => value pairs that are put on the outer div of this
2401 * block. {@link $id} and {@link $classes} attributes should be set separately.
2403 public $attributes;
2406 * @var string The title of this block. If this came from user input, it should already
2407 * have had format_string() processing done on it. This will be output inside
2408 * <h2> tags. Please do not cause invalid XHTML.
2410 public $title = '';
2413 * @var string The label to use when the block does not, or will not have a visible title.
2414 * You should never set this as well as title... it will just be ignored.
2416 public $arialabel = '';
2419 * @var string HTML for the content
2421 public $content = '';
2424 * @var array An alternative to $content, it you want a list of things with optional icons.
2426 public $footer = '';
2429 * @var string Any small print that should appear under the block to explain
2430 * to the teacher about the block, for example 'This is a sticky block that was
2431 * added in the system context.'
2433 public $annotation = '';
2436 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2437 * the user can toggle whether this block is visible.
2439 public $collapsible = self::NOT_HIDEABLE;
2442 * @var array A (possibly empty) array of editing controls. Each element of
2443 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2444 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2446 public $controls = array();
2450 * Create new instance of block content
2451 * @param array $attributes
2453 public function __construct(array $attributes = null) {
2454 $this->skipid = self::$idcounter;
2455 self::$idcounter += 1;
2457 if ($attributes) {
2458 // standard block
2459 $this->attributes = $attributes;
2460 } else {
2461 // simple "fake" blocks used in some modules and "Add new block" block
2462 $this->attributes = array('class'=>'block');
2467 * Add html class to block
2469 * @param string $class
2471 public function add_class($class) {
2472 $this->attributes['class'] .= ' '.$class;
2478 * This class represents a target for where a block can go when it is being moved.
2480 * This needs to be rendered as a form with the given hidden from fields, and
2481 * clicking anywhere in the form should submit it. The form action should be
2482 * $PAGE->url.
2484 * @copyright 2009 Tim Hunt
2485 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2486 * @since Moodle 2.0
2487 * @package core
2488 * @category output
2490 class block_move_target {
2493 * @var moodle_url Move url
2495 public $url;
2498 * Constructor
2499 * @param moodle_url $url
2501 public function __construct(moodle_url $url) {
2502 $this->url = $url;
2507 * Custom menu item
2509 * This class is used to represent one item within a custom menu that may or may
2510 * not have children.
2512 * @copyright 2010 Sam Hemelryk
2513 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2514 * @since Moodle 2.0
2515 * @package core
2516 * @category output
2518 class custom_menu_item implements renderable {
2521 * @var string The text to show for the item
2523 protected $text;
2526 * @var moodle_url The link to give the icon if it has no children
2528 protected $url;
2531 * @var string A title to apply to the item. By default the text
2533 protected $title;
2536 * @var int A sort order for the item, not necessary if you order things in
2537 * the CFG var.
2539 protected $sort;
2542 * @var custom_menu_item A reference to the parent for this item or NULL if
2543 * it is a top level item
2545 protected $parent;
2548 * @var array A array in which to store children this item has.
2550 protected $children = array();
2553 * @var int A reference to the sort var of the last child that was added
2555 protected $lastsort = 0;
2558 * Constructs the new custom menu item
2560 * @param string $text
2561 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2562 * @param string $title A title to apply to this item [Optional]
2563 * @param int $sort A sort or to use if we need to sort differently [Optional]
2564 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2565 * belongs to, only if the child has a parent. [Optional]
2567 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
2568 $this->text = $text;
2569 $this->url = $url;
2570 $this->title = $title;
2571 $this->sort = (int)$sort;
2572 $this->parent = $parent;
2576 * Adds a custom menu item as a child of this node given its properties.
2578 * @param string $text
2579 * @param moodle_url $url
2580 * @param string $title
2581 * @param int $sort
2582 * @return custom_menu_item
2584 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
2585 $key = count($this->children);
2586 if (empty($sort)) {
2587 $sort = $this->lastsort + 1;
2589 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2590 $this->lastsort = (int)$sort;
2591 return $this->children[$key];
2595 * Returns the text for this item
2596 * @return string
2598 public function get_text() {
2599 return $this->text;
2603 * Returns the url for this item
2604 * @return moodle_url
2606 public function get_url() {
2607 return $this->url;
2611 * Returns the title for this item
2612 * @return string
2614 public function get_title() {
2615 return $this->title;
2619 * Sorts and returns the children for this item
2620 * @return array
2622 public function get_children() {
2623 $this->sort();
2624 return $this->children;
2628 * Gets the sort order for this child
2629 * @return int
2631 public function get_sort_order() {
2632 return $this->sort;
2636 * Gets the parent this child belong to
2637 * @return custom_menu_item
2639 public function get_parent() {
2640 return $this->parent;
2644 * Sorts the children this item has
2646 public function sort() {
2647 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2651 * Returns true if this item has any children
2652 * @return bool
2654 public function has_children() {
2655 return (count($this->children) > 0);
2659 * Sets the text for the node
2660 * @param string $text
2662 public function set_text($text) {
2663 $this->text = (string)$text;
2667 * Sets the title for the node
2668 * @param string $title
2670 public function set_title($title) {
2671 $this->title = (string)$title;
2675 * Sets the url for the node
2676 * @param moodle_url $url
2678 public function set_url(moodle_url $url) {
2679 $this->url = $url;
2684 * Custom menu class
2686 * This class is used to operate a custom menu that can be rendered for the page.
2687 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2688 * of custom_menu_item nodes that can be rendered by the core renderer.
2690 * To configure the custom menu:
2691 * Settings: Administration > Appearance > Themes > Theme settings
2693 * @copyright 2010 Sam Hemelryk
2694 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2695 * @since Moodle 2.0
2696 * @package core
2697 * @category output
2699 class custom_menu extends custom_menu_item {
2702 * @var string The language we should render for, null disables multilang support.
2704 protected $currentlanguage = null;
2707 * Creates the custom menu
2709 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2710 * @param string $currentlanguage the current language code, null disables multilang support
2712 public function __construct($definition = '', $currentlanguage = null) {
2713 $this->currentlanguage = $currentlanguage;
2714 parent::__construct('root'); // create virtual root element of the menu
2715 if (!empty($definition)) {
2716 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2721 * Overrides the children of this custom menu. Useful when getting children
2722 * from $CFG->custommenuitems
2724 * @param array $children
2726 public function override_children(array $children) {
2727 $this->children = array();
2728 foreach ($children as $child) {
2729 if ($child instanceof custom_menu_item) {
2730 $this->children[] = $child;
2736 * Converts a string into a structured array of custom_menu_items which can
2737 * then be added to a custom menu.
2739 * Structure:
2740 * text|url|title|langs
2741 * The number of hyphens at the start determines the depth of the item. The
2742 * languages are optional, comma separated list of languages the line is for.
2744 * Example structure:
2745 * First level first item|http://www.moodle.com/
2746 * -Second level first item|http://www.moodle.com/partners/
2747 * -Second level second item|http://www.moodle.com/hq/
2748 * --Third level first item|http://www.moodle.com/jobs/
2749 * -Second level third item|http://www.moodle.com/development/
2750 * First level second item|http://www.moodle.com/feedback/
2751 * First level third item
2752 * English only|http://moodle.com|English only item|en
2753 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2756 * @static
2757 * @param string $text the menu items definition
2758 * @param string $language the language code, null disables multilang support
2759 * @return array
2761 public static function convert_text_to_menu_nodes($text, $language = null) {
2762 $lines = explode("\n", $text);
2763 $children = array();
2764 $lastchild = null;
2765 $lastdepth = null;
2766 $lastsort = 0;
2767 foreach ($lines as $line) {
2768 $line = trim($line);
2769 $bits = explode('|', $line, 4); // name|url|title|langs
2770 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2771 // Every item must have a name to be valid
2772 continue;
2773 } else {
2774 $bits[0] = ltrim($bits[0],'-');
2776 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2777 // Set the url to null
2778 $bits[1] = null;
2779 } else {
2780 // Make sure the url is a moodle url
2781 $bits[1] = new moodle_url(trim($bits[1]));
2783 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2784 // Set the title to null seeing as there isn't one
2785 $bits[2] = $bits[0];
2787 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2788 // The item is valid for all languages
2789 $itemlangs = null;
2790 } else {
2791 $itemlangs = array_map('trim', explode(',', $bits[3]));
2793 if (!empty($language) and !empty($itemlangs)) {
2794 // check that the item is intended for the current language
2795 if (!in_array($language, $itemlangs)) {
2796 continue;
2799 // Set an incremental sort order to keep it simple.
2800 $lastsort++;
2801 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2802 $depth = strlen($match[1]);
2803 if ($depth < $lastdepth) {
2804 $difference = $lastdepth - $depth;
2805 if ($lastdepth > 1 && $lastdepth != $difference) {
2806 $tempchild = $lastchild->get_parent();
2807 for ($i =0; $i < $difference; $i++) {
2808 $tempchild = $tempchild->get_parent();
2810 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2811 } else {
2812 $depth = 0;
2813 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2814 $children[] = $lastchild;
2816 } else if ($depth > $lastdepth) {
2817 $depth = $lastdepth + 1;
2818 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2819 } else {
2820 if ($depth == 0) {
2821 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2822 $children[] = $lastchild;
2823 } else {
2824 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2827 } else {
2828 $depth = 0;
2829 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2830 $children[] = $lastchild;
2832 $lastdepth = $depth;
2834 return $children;
2838 * Sorts two custom menu items
2840 * This function is designed to be used with the usort method
2841 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2843 * @static
2844 * @param custom_menu_item $itema
2845 * @param custom_menu_item $itemb
2846 * @return int
2848 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2849 $itema = $itema->get_sort_order();
2850 $itemb = $itemb->get_sort_order();
2851 if ($itema == $itemb) {
2852 return 0;
2854 return ($itema > $itemb) ? +1 : -1;
2859 * Stores one tab
2861 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2862 * @package core
2864 class tabobject implements renderable {
2865 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
2866 var $id;
2867 /** @var moodle_url|string link */
2868 var $link;
2869 /** @var string text on the tab */
2870 var $text;
2871 /** @var string title under the link, by defaul equals to text */
2872 var $title;
2873 /** @var bool whether to display a link under the tab name when it's selected */
2874 var $linkedwhenselected = false;
2875 /** @var bool whether the tab is inactive */
2876 var $inactive = false;
2877 /** @var bool indicates that this tab's child is selected */
2878 var $activated = false;
2879 /** @var bool indicates that this tab is selected */
2880 var $selected = false;
2881 /** @var array stores children tabobjects */
2882 var $subtree = array();
2883 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
2884 var $level = 1;
2887 * Constructor
2889 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
2890 * @param string|moodle_url $link
2891 * @param string $text text on the tab
2892 * @param string $title title under the link, by defaul equals to text
2893 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
2895 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
2896 $this->id = $id;
2897 $this->link = $link;
2898 $this->text = $text;
2899 $this->title = $title ? $title : $text;
2900 $this->linkedwhenselected = $linkedwhenselected;
2904 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
2906 * @param string $selected the id of the selected tab (whatever row it's on),
2907 * if null marks all tabs as unselected
2908 * @return bool whether this tab is selected or contains selected tab in its subtree
2910 protected function set_selected($selected) {
2911 if ((string)$selected === (string)$this->id) {
2912 $this->selected = true;
2913 // This tab is selected. No need to travel through subtree.
2914 return true;
2916 foreach ($this->subtree as $subitem) {
2917 if ($subitem->set_selected($selected)) {
2918 // This tab has child that is selected. Mark it as activated. No need to check other children.
2919 $this->activated = true;
2920 return true;
2923 return false;
2927 * Travels through tree and finds a tab with specified id
2929 * @param string $id
2930 * @return tabtree|null
2932 public function find($id) {
2933 if ((string)$this->id === (string)$id) {
2934 return $this;
2936 foreach ($this->subtree as $tab) {
2937 if ($obj = $tab->find($id)) {
2938 return $obj;
2941 return null;
2945 * Allows to mark each tab's level in the tree before rendering.
2947 * @param int $level
2949 protected function set_level($level) {
2950 $this->level = $level;
2951 foreach ($this->subtree as $tab) {
2952 $tab->set_level($level + 1);
2958 * Stores tabs list
2960 * Example how to print a single line tabs:
2961 * $rows = array(
2962 * new tabobject(...),
2963 * new tabobject(...)
2964 * );
2965 * echo $OUTPUT->tabtree($rows, $selectedid);
2967 * Multiple row tabs may not look good on some devices but if you want to use them
2968 * you can specify ->subtree for the active tabobject.
2970 * @copyright 2013 Marina Glancy
2971 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2972 * @since Moodle 2.5
2973 * @package core
2974 * @category output
2976 class tabtree extends tabobject {
2978 * Constuctor
2980 * It is highly recommended to call constructor when list of tabs is already
2981 * populated, this way you ensure that selected and inactive tabs are located
2982 * and attribute level is set correctly.
2984 * @param array $tabs array of tabs, each of them may have it's own ->subtree
2985 * @param string|null $selected which tab to mark as selected, all parent tabs will
2986 * automatically be marked as activated
2987 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
2988 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
2990 public function __construct($tabs, $selected = null, $inactive = null) {
2991 $this->subtree = $tabs;
2992 if ($selected !== null) {
2993 $this->set_selected($selected);
2995 if ($inactive !== null) {
2996 if (is_array($inactive)) {
2997 foreach ($inactive as $id) {
2998 if ($tab = $this->find($id)) {
2999 $tab->inactive = true;
3002 } else if ($tab = $this->find($inactive)) {
3003 $tab->inactive = true;
3006 $this->set_level(0);