Merge branch '45699-29' of git://github.com/samhemelryk/moodle
[moodle.git] / lib / outputcomponents.php
blob04aeba49aa4f19dd823dc4148b8325751d05ec53
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', 'firstnamephonetic', 'lastnamephonetic',
135 'middlename', 'alternatename', 'imagealt', 'email');
138 * @var stdClass A user object with at least fields all columns specified
139 * in $fields array constant set.
141 public $user;
144 * @var int The course id. Used when constructing the link to the user's
145 * profile, page course id used if not specified.
147 public $courseid;
150 * @var bool Add course profile link to image
152 public $link = true;
155 * @var int Size in pixels. Special values are (true/1 = 100px) and
156 * (false/0 = 35px)
157 * for backward compatibility.
159 public $size = 35;
162 * @var bool Add non-blank alt-text to the image.
163 * Default true, set to false when image alt just duplicates text in screenreaders.
165 public $alttext = true;
168 * @var bool Whether or not to open the link in a popup window.
170 public $popup = false;
173 * @var string Image class attribute
175 public $class = 'userpicture';
178 * @var bool Whether to be visible to screen readers.
180 public $visibletoscreenreaders = true;
183 * User picture constructor.
185 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
186 * It is recommended to add also contextid of the user for performance reasons.
188 public function __construct(stdClass $user) {
189 global $DB;
191 if (empty($user->id)) {
192 throw new coding_exception('User id is required when printing user avatar image.');
195 // only touch the DB if we are missing data and complain loudly...
196 $needrec = false;
197 foreach (self::$fields as $field) {
198 if (!array_key_exists($field, $user)) {
199 $needrec = true;
200 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
201 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
202 break;
206 if ($needrec) {
207 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
208 } else {
209 $this->user = clone($user);
214 * Returns a list of required user fields, useful when fetching required user info from db.
216 * In some cases we have to fetch the user data together with some other information,
217 * the idalias is useful there because the id would otherwise override the main
218 * id of the result record. Please note it has to be converted back to id before rendering.
220 * @param string $tableprefix name of database table prefix in query
221 * @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)
222 * @param string $idalias alias of id field
223 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
224 * @return string
226 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
227 if (!$tableprefix and !$extrafields and !$idalias) {
228 return implode(',', self::$fields);
230 if ($tableprefix) {
231 $tableprefix .= '.';
233 foreach (self::$fields as $field) {
234 if ($field === 'id' and $idalias and $idalias !== 'id') {
235 $fields[$field] = "$tableprefix$field AS $idalias";
236 } else {
237 if ($fieldprefix and $field !== 'id') {
238 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
239 } else {
240 $fields[$field] = "$tableprefix$field";
244 // add extra fields if not already there
245 if ($extrafields) {
246 foreach ($extrafields as $e) {
247 if ($e === 'id' or isset($fields[$e])) {
248 continue;
250 if ($fieldprefix) {
251 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
252 } else {
253 $fields[$e] = "$tableprefix$e";
257 return implode(',', $fields);
261 * Extract the aliased user fields from a given record
263 * Given a record that was previously obtained using {@link self::fields()} with aliases,
264 * this method extracts user related unaliased fields.
266 * @param stdClass $record containing user picture fields
267 * @param array $extrafields extra fields included in the $record
268 * @param string $idalias alias of the id field
269 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
270 * @return stdClass object with unaliased user fields
272 public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
274 if (empty($idalias)) {
275 $idalias = 'id';
278 $return = new stdClass();
280 foreach (self::$fields as $field) {
281 if ($field === 'id') {
282 if (property_exists($record, $idalias)) {
283 $return->id = $record->{$idalias};
285 } else {
286 if (property_exists($record, $fieldprefix.$field)) {
287 $return->{$field} = $record->{$fieldprefix.$field};
291 // add extra fields if not already there
292 if ($extrafields) {
293 foreach ($extrafields as $e) {
294 if ($e === 'id' or property_exists($return, $e)) {
295 continue;
297 $return->{$e} = $record->{$fieldprefix.$e};
301 return $return;
305 * Works out the URL for the users picture.
307 * This method is recommended as it avoids costly redirects of user pictures
308 * if requests are made for non-existent files etc.
310 * @param moodle_page $page
311 * @param renderer_base $renderer
312 * @return moodle_url
314 public function get_url(moodle_page $page, renderer_base $renderer = null) {
315 global $CFG;
317 if (is_null($renderer)) {
318 $renderer = $page->get_renderer('core');
321 // Sort out the filename and size. Size is only required for the gravatar
322 // implementation presently.
323 if (empty($this->size)) {
324 $filename = 'f2';
325 $size = 35;
326 } else if ($this->size === true or $this->size == 1) {
327 $filename = 'f1';
328 $size = 100;
329 } else if ($this->size > 100) {
330 $filename = 'f3';
331 $size = (int)$this->size;
332 } else if ($this->size >= 50) {
333 $filename = 'f1';
334 $size = (int)$this->size;
335 } else {
336 $filename = 'f2';
337 $size = (int)$this->size;
340 $defaulturl = $renderer->pix_url('u/'.$filename); // default image
342 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
343 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
344 // Protect images if login required and not logged in;
345 // also if login is required for profile images and is not logged in or guest
346 // do not use require_login() because it is expensive and not suitable here anyway.
347 return $defaulturl;
350 // First try to detect deleted users - but do not read from database for performance reasons!
351 if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
352 // All deleted users should have email replaced by md5 hash,
353 // all active users are expected to have valid email.
354 return $defaulturl;
357 // Did the user upload a picture?
358 if ($this->user->picture > 0) {
359 if (!empty($this->user->contextid)) {
360 $contextid = $this->user->contextid;
361 } else {
362 $context = context_user::instance($this->user->id, IGNORE_MISSING);
363 if (!$context) {
364 // This must be an incorrectly deleted user, all other users have context.
365 return $defaulturl;
367 $contextid = $context->id;
370 $path = '/';
371 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
372 // We append the theme name to the file path if we have it so that
373 // in the circumstance that the profile picture is not available
374 // when the user actually requests it they still get the profile
375 // picture for the correct theme.
376 $path .= $page->theme->name.'/';
378 // Set the image URL to the URL for the uploaded file and return.
379 $url = moodle_url::make_pluginfile_url($contextid, 'user', 'icon', NULL, $path, $filename);
380 $url->param('rev', $this->user->picture);
381 return $url;
384 if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
385 // Normalise the size variable to acceptable bounds
386 if ($size < 1 || $size > 512) {
387 $size = 35;
389 // Hash the users email address
390 $md5 = md5(strtolower(trim($this->user->email)));
391 // Build a gravatar URL with what we know.
393 // Find the best default image URL we can (MDL-35669)
394 if (empty($CFG->gravatardefaulturl)) {
395 $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
396 if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
397 $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
398 } else {
399 $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
401 } else {
402 $gravatardefault = $CFG->gravatardefaulturl;
405 // If the currently requested page is https then we'll return an
406 // https gravatar page.
407 if (is_https()) {
408 $gravatardefault = str_replace($CFG->wwwroot, $CFG->httpswwwroot, $gravatardefault); // Replace by secure url.
409 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
410 } else {
411 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
415 return $defaulturl;
420 * Data structure representing a help icon.
422 * @copyright 2010 Petr Skoda (info@skodak.org)
423 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
424 * @since Moodle 2.0
425 * @package core
426 * @category output
428 class help_icon implements renderable {
431 * @var string lang pack identifier (without the "_help" suffix),
432 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
433 * must exist.
435 public $identifier;
438 * @var string Component name, the same as in get_string()
440 public $component;
443 * @var string Extra descriptive text next to the icon
445 public $linktext = null;
448 * Constructor
450 * @param string $identifier string for help page title,
451 * string with _help suffix is used for the actual help text.
452 * string with _link suffix is used to create a link to further info (if it exists)
453 * @param string $component
455 public function __construct($identifier, $component) {
456 $this->identifier = $identifier;
457 $this->component = $component;
461 * Verifies that both help strings exists, shows debug warnings if not
463 public function diag_strings() {
464 $sm = get_string_manager();
465 if (!$sm->string_exists($this->identifier, $this->component)) {
466 debugging("Help title string does not exist: [$this->identifier, $this->component]");
468 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
469 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
476 * Data structure representing an icon.
478 * @copyright 2010 Petr Skoda
479 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
480 * @since Moodle 2.0
481 * @package core
482 * @category output
484 class pix_icon implements renderable {
487 * @var string The icon name
489 var $pix;
492 * @var string The component the icon belongs to.
494 var $component;
497 * @var array An array of attributes to use on the icon
499 var $attributes = array();
502 * Constructor
504 * @param string $pix short icon name
505 * @param string $alt The alt text to use for the icon
506 * @param string $component component name
507 * @param array $attributes html attributes
509 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
510 $this->pix = $pix;
511 $this->component = $component;
512 $this->attributes = (array)$attributes;
514 $this->attributes['alt'] = $alt;
515 if (empty($this->attributes['class'])) {
516 $this->attributes['class'] = 'smallicon';
518 if (!isset($this->attributes['title'])) {
519 $this->attributes['title'] = $this->attributes['alt'];
520 } else if (empty($this->attributes['title'])) {
521 // Remove the title attribute if empty, we probably want to use the parent node's title
522 // and some browsers might overwrite it with an empty title.
523 unset($this->attributes['title']);
529 * Data structure representing an emoticon image
531 * @copyright 2010 David Mudrak
532 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
533 * @since Moodle 2.0
534 * @package core
535 * @category output
537 class pix_emoticon extends pix_icon implements renderable {
540 * Constructor
541 * @param string $pix short icon name
542 * @param string $alt alternative text
543 * @param string $component emoticon image provider
544 * @param array $attributes explicit HTML attributes
546 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
547 if (empty($attributes['class'])) {
548 $attributes['class'] = 'emoticon';
550 parent::__construct($pix, $alt, $component, $attributes);
555 * Data structure representing a simple form with only one button.
557 * @copyright 2009 Petr Skoda
558 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
559 * @since Moodle 2.0
560 * @package core
561 * @category output
563 class single_button implements renderable {
566 * @var moodle_url Target url
568 var $url;
571 * @var string Button label
573 var $label;
576 * @var string Form submit method post or get
578 var $method = 'post';
581 * @var string Wrapping div class
583 var $class = 'singlebutton';
586 * @var bool True if button disabled, false if normal
588 var $disabled = false;
591 * @var string Button tooltip
593 var $tooltip = null;
596 * @var string Form id
598 var $formid;
601 * @var array List of attached actions
603 var $actions = array();
606 * Constructor
607 * @param moodle_url $url
608 * @param string $label button text
609 * @param string $method get or post submit method
611 public function __construct(moodle_url $url, $label, $method='post') {
612 $this->url = clone($url);
613 $this->label = $label;
614 $this->method = $method;
618 * Shortcut for adding a JS confirm dialog when the button is clicked.
619 * The message must be a yes/no question.
621 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
623 public function add_confirm_action($confirmmessage) {
624 $this->add_action(new confirm_action($confirmmessage));
628 * Add action to the button.
629 * @param component_action $action
631 public function add_action(component_action $action) {
632 $this->actions[] = $action;
638 * Simple form with just one select field that gets submitted automatically.
640 * If JS not enabled small go button is printed too.
642 * @copyright 2009 Petr Skoda
643 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
644 * @since Moodle 2.0
645 * @package core
646 * @category output
648 class single_select implements renderable {
651 * @var moodle_url Target url - includes hidden fields
653 var $url;
656 * @var string Name of the select element.
658 var $name;
661 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
662 * it is also possible to specify optgroup as complex label array ex.:
663 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
664 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
666 var $options;
669 * @var string Selected option
671 var $selected;
674 * @var array Nothing selected
676 var $nothing;
679 * @var array Extra select field attributes
681 var $attributes = array();
684 * @var string Button label
686 var $label = '';
689 * @var array Button label's attributes
691 var $labelattributes = array();
694 * @var string Form submit method post or get
696 var $method = 'get';
699 * @var string Wrapping div class
701 var $class = 'singleselect';
704 * @var bool True if button disabled, false if normal
706 var $disabled = false;
709 * @var string Button tooltip
711 var $tooltip = null;
714 * @var string Form id
716 var $formid = null;
719 * @var array List of attached actions
721 var $helpicon = null;
724 * Constructor
725 * @param moodle_url $url form action target, includes hidden fields
726 * @param string $name name of selection field - the changing parameter in url
727 * @param array $options list of options
728 * @param string $selected selected element
729 * @param array $nothing
730 * @param string $formid
732 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
733 $this->url = $url;
734 $this->name = $name;
735 $this->options = $options;
736 $this->selected = $selected;
737 $this->nothing = $nothing;
738 $this->formid = $formid;
742 * Shortcut for adding a JS confirm dialog when the button is clicked.
743 * The message must be a yes/no question.
745 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
747 public function add_confirm_action($confirmmessage) {
748 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
752 * Add action to the button.
754 * @param component_action $action
756 public function add_action(component_action $action) {
757 $this->actions[] = $action;
761 * Adds help icon.
763 * @deprecated since Moodle 2.0
765 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
766 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
770 * Adds help icon.
772 * @param string $identifier The keyword that defines a help page
773 * @param string $component
775 public function set_help_icon($identifier, $component = 'moodle') {
776 $this->helpicon = new help_icon($identifier, $component);
780 * Sets select's label
782 * @param string $label
783 * @param array $attributes (optional)
785 public function set_label($label, $attributes = array()) {
786 $this->label = $label;
787 $this->labelattributes = $attributes;
793 * Simple URL selection widget description.
795 * @copyright 2009 Petr Skoda
796 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
797 * @since Moodle 2.0
798 * @package core
799 * @category output
801 class url_select implements renderable {
803 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
804 * it is also possible to specify optgroup as complex label array ex.:
805 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
806 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
808 var $urls;
811 * @var string Selected option
813 var $selected;
816 * @var array Nothing selected
818 var $nothing;
821 * @var array Extra select field attributes
823 var $attributes = array();
826 * @var string Button label
828 var $label = '';
831 * @var array Button label's attributes
833 var $labelattributes = array();
836 * @var string Wrapping div class
838 var $class = 'urlselect';
841 * @var bool True if button disabled, false if normal
843 var $disabled = false;
846 * @var string Button tooltip
848 var $tooltip = null;
851 * @var string Form id
853 var $formid = null;
856 * @var array List of attached actions
858 var $helpicon = null;
861 * @var string If set, makes button visible with given name for button
863 var $showbutton = null;
866 * Constructor
867 * @param array $urls list of options
868 * @param string $selected selected element
869 * @param array $nothing
870 * @param string $formid
871 * @param string $showbutton Set to text of button if it should be visible
872 * or null if it should be hidden (hidden version always has text 'go')
874 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
875 $this->urls = $urls;
876 $this->selected = $selected;
877 $this->nothing = $nothing;
878 $this->formid = $formid;
879 $this->showbutton = $showbutton;
883 * Adds help icon.
885 * @deprecated since Moodle 2.0
887 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
888 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
892 * Adds help icon.
894 * @param string $identifier The keyword that defines a help page
895 * @param string $component
897 public function set_help_icon($identifier, $component = 'moodle') {
898 $this->helpicon = new help_icon($identifier, $component);
902 * Sets select's label
904 * @param string $label
905 * @param array $attributes (optional)
907 public function set_label($label, $attributes = array()) {
908 $this->label = $label;
909 $this->labelattributes = $attributes;
914 * Data structure describing html link with special action attached.
916 * @copyright 2010 Petr Skoda
917 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
918 * @since Moodle 2.0
919 * @package core
920 * @category output
922 class action_link implements renderable {
925 * @var moodle_url Href url
927 public $url;
930 * @var string Link text HTML fragment
932 public $text;
935 * @var array HTML attributes
937 public $attributes;
940 * @var array List of actions attached to link
942 public $actions;
945 * @var pix_icon Optional pix icon to render with the link
947 public $icon;
950 * Constructor
951 * @param moodle_url $url
952 * @param string $text HTML fragment
953 * @param component_action $action
954 * @param array $attributes associative array of html link attributes + disabled
955 * @param pix_icon $icon optional pix_icon to render with the link text
957 public function __construct(moodle_url $url,
958 $text,
959 component_action $action=null,
960 array $attributes=null,
961 pix_icon $icon=null) {
962 $this->url = clone($url);
963 $this->text = $text;
964 $this->attributes = (array)$attributes;
965 if ($action) {
966 $this->add_action($action);
968 $this->icon = $icon;
972 * Add action to the link.
974 * @param component_action $action
976 public function add_action(component_action $action) {
977 $this->actions[] = $action;
981 * Adds a CSS class to this action link object
982 * @param string $class
984 public function add_class($class) {
985 if (empty($this->attributes['class'])) {
986 $this->attributes['class'] = $class;
987 } else {
988 $this->attributes['class'] .= ' ' . $class;
993 * Returns true if the specified class has been added to this link.
994 * @param string $class
995 * @return bool
997 public function has_class($class) {
998 return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
1003 * Simple html output class
1005 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1006 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1007 * @since Moodle 2.0
1008 * @package core
1009 * @category output
1011 class html_writer {
1014 * Outputs a tag with attributes and contents
1016 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1017 * @param string $contents What goes between the opening and closing tags
1018 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1019 * @return string HTML fragment
1021 public static function tag($tagname, $contents, array $attributes = null) {
1022 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1026 * Outputs an opening tag with attributes
1028 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1029 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1030 * @return string HTML fragment
1032 public static function start_tag($tagname, array $attributes = null) {
1033 return '<' . $tagname . self::attributes($attributes) . '>';
1037 * Outputs a closing tag
1039 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1040 * @return string HTML fragment
1042 public static function end_tag($tagname) {
1043 return '</' . $tagname . '>';
1047 * Outputs an empty tag with attributes
1049 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1050 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1051 * @return string HTML fragment
1053 public static function empty_tag($tagname, array $attributes = null) {
1054 return '<' . $tagname . self::attributes($attributes) . ' />';
1058 * Outputs a tag, but only if the contents are not empty
1060 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1061 * @param string $contents What goes between the opening and closing tags
1062 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1063 * @return string HTML fragment
1065 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1066 if ($contents === '' || is_null($contents)) {
1067 return '';
1069 return self::tag($tagname, $contents, $attributes);
1073 * Outputs a HTML attribute and value
1075 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1076 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1077 * @return string HTML fragment
1079 public static function attribute($name, $value) {
1080 if ($value instanceof moodle_url) {
1081 return ' ' . $name . '="' . $value->out() . '"';
1084 // special case, we do not want these in output
1085 if ($value === null) {
1086 return '';
1089 // no sloppy trimming here!
1090 return ' ' . $name . '="' . s($value) . '"';
1094 * Outputs a list of HTML attributes and values
1096 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1097 * The values will be escaped with {@link s()}
1098 * @return string HTML fragment
1100 public static function attributes(array $attributes = null) {
1101 $attributes = (array)$attributes;
1102 $output = '';
1103 foreach ($attributes as $name => $value) {
1104 $output .= self::attribute($name, $value);
1106 return $output;
1110 * Generates a simple image tag with attributes.
1112 * @param string $src The source of image
1113 * @param string $alt The alternate text for image
1114 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1115 * @return string HTML fragment
1117 public static function img($src, $alt, array $attributes = null) {
1118 $attributes = (array)$attributes;
1119 $attributes['src'] = $src;
1120 $attributes['alt'] = $alt;
1122 return self::empty_tag('img', $attributes);
1126 * Generates random html element id.
1128 * @staticvar int $counter
1129 * @staticvar type $uniq
1130 * @param string $base A string fragment that will be included in the random ID.
1131 * @return string A unique ID
1133 public static function random_id($base='random') {
1134 static $counter = 0;
1135 static $uniq;
1137 if (!isset($uniq)) {
1138 $uniq = uniqid();
1141 $counter++;
1142 return $base.$uniq.$counter;
1146 * Generates a simple html link
1148 * @param string|moodle_url $url The URL
1149 * @param string $text The text
1150 * @param array $attributes HTML attributes
1151 * @return string HTML fragment
1153 public static function link($url, $text, array $attributes = null) {
1154 $attributes = (array)$attributes;
1155 $attributes['href'] = $url;
1156 return self::tag('a', $text, $attributes);
1160 * Generates a simple checkbox with optional label
1162 * @param string $name The name of the checkbox
1163 * @param string $value The value of the checkbox
1164 * @param bool $checked Whether the checkbox is checked
1165 * @param string $label The label for the checkbox
1166 * @param array $attributes Any attributes to apply to the checkbox
1167 * @return string html fragment
1169 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1170 $attributes = (array)$attributes;
1171 $output = '';
1173 if ($label !== '' and !is_null($label)) {
1174 if (empty($attributes['id'])) {
1175 $attributes['id'] = self::random_id('checkbox_');
1178 $attributes['type'] = 'checkbox';
1179 $attributes['value'] = $value;
1180 $attributes['name'] = $name;
1181 $attributes['checked'] = $checked ? 'checked' : null;
1183 $output .= self::empty_tag('input', $attributes);
1185 if ($label !== '' and !is_null($label)) {
1186 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1189 return $output;
1193 * Generates a simple select yes/no form field
1195 * @param string $name name of select element
1196 * @param bool $selected
1197 * @param array $attributes - html select element attributes
1198 * @return string HTML fragment
1200 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1201 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1202 return self::select($options, $name, $selected, null, $attributes);
1206 * Generates a simple select form field
1208 * @param array $options associative array value=>label ex.:
1209 * array(1=>'One, 2=>Two)
1210 * it is also possible to specify optgroup as complex label array ex.:
1211 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1212 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1213 * @param string $name name of select element
1214 * @param string|array $selected value or array of values depending on multiple attribute
1215 * @param array|bool $nothing add nothing selected option, or false of not added
1216 * @param array $attributes html select element attributes
1217 * @return string HTML fragment
1219 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1220 $attributes = (array)$attributes;
1221 if (is_array($nothing)) {
1222 foreach ($nothing as $k=>$v) {
1223 if ($v === 'choose' or $v === 'choosedots') {
1224 $nothing[$k] = get_string('choosedots');
1227 $options = $nothing + $options; // keep keys, do not override
1229 } else if (is_string($nothing) and $nothing !== '') {
1230 // BC
1231 $options = array(''=>$nothing) + $options;
1234 // we may accept more values if multiple attribute specified
1235 $selected = (array)$selected;
1236 foreach ($selected as $k=>$v) {
1237 $selected[$k] = (string)$v;
1240 if (!isset($attributes['id'])) {
1241 $id = 'menu'.$name;
1242 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1243 $id = str_replace('[', '', $id);
1244 $id = str_replace(']', '', $id);
1245 $attributes['id'] = $id;
1248 if (!isset($attributes['class'])) {
1249 $class = 'menu'.$name;
1250 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1251 $class = str_replace('[', '', $class);
1252 $class = str_replace(']', '', $class);
1253 $attributes['class'] = $class;
1255 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
1257 $attributes['name'] = $name;
1259 if (!empty($attributes['disabled'])) {
1260 $attributes['disabled'] = 'disabled';
1261 } else {
1262 unset($attributes['disabled']);
1265 $output = '';
1266 foreach ($options as $value=>$label) {
1267 if (is_array($label)) {
1268 // ignore key, it just has to be unique
1269 $output .= self::select_optgroup(key($label), current($label), $selected);
1270 } else {
1271 $output .= self::select_option($label, $value, $selected);
1274 return self::tag('select', $output, $attributes);
1278 * Returns HTML to display a select box option.
1280 * @param string $label The label to display as the option.
1281 * @param string|int $value The value the option represents
1282 * @param array $selected An array of selected options
1283 * @return string HTML fragment
1285 private static function select_option($label, $value, array $selected) {
1286 $attributes = array();
1287 $value = (string)$value;
1288 if (in_array($value, $selected, true)) {
1289 $attributes['selected'] = 'selected';
1291 $attributes['value'] = $value;
1292 return self::tag('option', $label, $attributes);
1296 * Returns HTML to display a select box option group.
1298 * @param string $groupname The label to use for the group
1299 * @param array $options The options in the group
1300 * @param array $selected An array of selected values.
1301 * @return string HTML fragment.
1303 private static function select_optgroup($groupname, $options, array $selected) {
1304 if (empty($options)) {
1305 return '';
1307 $attributes = array('label'=>$groupname);
1308 $output = '';
1309 foreach ($options as $value=>$label) {
1310 $output .= self::select_option($label, $value, $selected);
1312 return self::tag('optgroup', $output, $attributes);
1316 * This is a shortcut for making an hour selector menu.
1318 * @param string $type The type of selector (years, months, days, hours, minutes)
1319 * @param string $name fieldname
1320 * @param int $currenttime A default timestamp in GMT
1321 * @param int $step minute spacing
1322 * @param array $attributes - html select element attributes
1323 * @return HTML fragment
1325 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1326 if (!$currenttime) {
1327 $currenttime = time();
1329 $currentdate = usergetdate($currenttime);
1330 $userdatetype = $type;
1331 $timeunits = array();
1333 switch ($type) {
1334 case 'years':
1335 for ($i=1970; $i<=2020; $i++) {
1336 $timeunits[$i] = $i;
1338 $userdatetype = 'year';
1339 break;
1340 case 'months':
1341 for ($i=1; $i<=12; $i++) {
1342 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1344 $userdatetype = 'month';
1345 $currentdate['month'] = (int)$currentdate['mon'];
1346 break;
1347 case 'days':
1348 for ($i=1; $i<=31; $i++) {
1349 $timeunits[$i] = $i;
1351 $userdatetype = 'mday';
1352 break;
1353 case 'hours':
1354 for ($i=0; $i<=23; $i++) {
1355 $timeunits[$i] = sprintf("%02d",$i);
1357 break;
1358 case 'minutes':
1359 if ($step != 1) {
1360 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1363 for ($i=0; $i<=59; $i+=$step) {
1364 $timeunits[$i] = sprintf("%02d",$i);
1366 break;
1367 default:
1368 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1371 if (empty($attributes['id'])) {
1372 $attributes['id'] = self::random_id('ts_');
1374 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, $attributes);
1375 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1377 return $label.$timerselector;
1381 * Shortcut for quick making of lists
1383 * Note: 'list' is a reserved keyword ;-)
1385 * @param array $items
1386 * @param array $attributes
1387 * @param string $tag ul or ol
1388 * @return string
1390 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1391 $output = html_writer::start_tag($tag, $attributes)."\n";
1392 foreach ($items as $item) {
1393 $output .= html_writer::tag('li', $item)."\n";
1395 $output .= html_writer::end_tag($tag);
1396 return $output;
1400 * Returns hidden input fields created from url parameters.
1402 * @param moodle_url $url
1403 * @param array $exclude list of excluded parameters
1404 * @return string HTML fragment
1406 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1407 $exclude = (array)$exclude;
1408 $params = $url->params();
1409 foreach ($exclude as $key) {
1410 unset($params[$key]);
1413 $output = '';
1414 foreach ($params as $key => $value) {
1415 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1416 $output .= self::empty_tag('input', $attributes)."\n";
1418 return $output;
1422 * Generate a script tag containing the the specified code.
1424 * @param string $jscode the JavaScript code
1425 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
1426 * @return string HTML, the code wrapped in <script> tags.
1428 public static function script($jscode, $url=null) {
1429 if ($jscode) {
1430 $attributes = array('type'=>'text/javascript');
1431 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1433 } else if ($url) {
1434 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1435 return self::tag('script', '', $attributes) . "\n";
1437 } else {
1438 return '';
1443 * Renders HTML table
1445 * This method may modify the passed instance by adding some default properties if they are not set yet.
1446 * If this is not what you want, you should make a full clone of your data before passing them to this
1447 * method. In most cases this is not an issue at all so we do not clone by default for performance
1448 * and memory consumption reasons.
1450 * @param html_table $table data to be rendered
1451 * @return string HTML code
1453 public static function table(html_table $table) {
1454 // prepare table data and populate missing properties with reasonable defaults
1455 if (!empty($table->align)) {
1456 foreach ($table->align as $key => $aa) {
1457 if ($aa) {
1458 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1459 } else {
1460 $table->align[$key] = null;
1464 if (!empty($table->size)) {
1465 foreach ($table->size as $key => $ss) {
1466 if ($ss) {
1467 $table->size[$key] = 'width:'. $ss .';';
1468 } else {
1469 $table->size[$key] = null;
1473 if (!empty($table->wrap)) {
1474 foreach ($table->wrap as $key => $ww) {
1475 if ($ww) {
1476 $table->wrap[$key] = 'white-space:nowrap;';
1477 } else {
1478 $table->wrap[$key] = '';
1482 if (!empty($table->head)) {
1483 foreach ($table->head as $key => $val) {
1484 if (!isset($table->align[$key])) {
1485 $table->align[$key] = null;
1487 if (!isset($table->size[$key])) {
1488 $table->size[$key] = null;
1490 if (!isset($table->wrap[$key])) {
1491 $table->wrap[$key] = null;
1496 if (empty($table->attributes['class'])) {
1497 $table->attributes['class'] = 'generaltable';
1499 if (!empty($table->tablealign)) {
1500 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1503 // explicitly assigned properties override those defined via $table->attributes
1504 $table->attributes['class'] = trim($table->attributes['class']);
1505 $attributes = array_merge($table->attributes, array(
1506 'id' => $table->id,
1507 'width' => $table->width,
1508 'summary' => $table->summary,
1509 'cellpadding' => $table->cellpadding,
1510 'cellspacing' => $table->cellspacing,
1512 $output = html_writer::start_tag('table', $attributes) . "\n";
1514 $countcols = 0;
1516 if (!empty($table->head)) {
1517 $countcols = count($table->head);
1519 $output .= html_writer::start_tag('thead', array()) . "\n";
1520 $output .= html_writer::start_tag('tr', array()) . "\n";
1521 $keys = array_keys($table->head);
1522 $lastkey = end($keys);
1524 foreach ($table->head as $key => $heading) {
1525 // Convert plain string headings into html_table_cell objects
1526 if (!($heading instanceof html_table_cell)) {
1527 $headingtext = $heading;
1528 $heading = new html_table_cell();
1529 $heading->text = $headingtext;
1530 $heading->header = true;
1533 if ($heading->header !== false) {
1534 $heading->header = true;
1537 if ($heading->header && empty($heading->scope)) {
1538 $heading->scope = 'col';
1541 $heading->attributes['class'] .= ' header c' . $key;
1542 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1543 $heading->colspan = $table->headspan[$key];
1544 $countcols += $table->headspan[$key] - 1;
1547 if ($key == $lastkey) {
1548 $heading->attributes['class'] .= ' lastcol';
1550 if (isset($table->colclasses[$key])) {
1551 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1553 $heading->attributes['class'] = trim($heading->attributes['class']);
1554 $attributes = array_merge($heading->attributes, array(
1555 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1556 'scope' => $heading->scope,
1557 'colspan' => $heading->colspan,
1560 $tagtype = 'td';
1561 if ($heading->header === true) {
1562 $tagtype = 'th';
1564 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1566 $output .= html_writer::end_tag('tr') . "\n";
1567 $output .= html_writer::end_tag('thead') . "\n";
1569 if (empty($table->data)) {
1570 // For valid XHTML strict every table must contain either a valid tr
1571 // or a valid tbody... both of which must contain a valid td
1572 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1573 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1574 $output .= html_writer::end_tag('tbody');
1578 if (!empty($table->data)) {
1579 $keys = array_keys($table->data);
1580 $lastrowkey = end($keys);
1581 $output .= html_writer::start_tag('tbody', array());
1583 foreach ($table->data as $key => $row) {
1584 if (($row === 'hr') && ($countcols)) {
1585 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1586 } else {
1587 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1588 if (!($row instanceof html_table_row)) {
1589 $newrow = new html_table_row();
1591 foreach ($row as $cell) {
1592 if (!($cell instanceof html_table_cell)) {
1593 $cell = new html_table_cell($cell);
1595 $newrow->cells[] = $cell;
1597 $row = $newrow;
1600 if (isset($table->rowclasses[$key])) {
1601 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1604 if ($key == $lastrowkey) {
1605 $row->attributes['class'] .= ' lastrow';
1608 // Explicitly assigned properties should override those defined in the attributes.
1609 $row->attributes['class'] = trim($row->attributes['class']);
1610 $trattributes = array_merge($row->attributes, array(
1611 'id' => $row->id,
1612 'style' => $row->style,
1614 $output .= html_writer::start_tag('tr', $trattributes) . "\n";
1615 $keys2 = array_keys($row->cells);
1616 $lastkey = end($keys2);
1618 $gotlastkey = false; //flag for sanity checking
1619 foreach ($row->cells as $key => $cell) {
1620 if ($gotlastkey) {
1621 //This should never happen. Why do we have a cell after the last cell?
1622 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1625 if (!($cell instanceof html_table_cell)) {
1626 $mycell = new html_table_cell();
1627 $mycell->text = $cell;
1628 $cell = $mycell;
1631 if (($cell->header === true) && empty($cell->scope)) {
1632 $cell->scope = 'row';
1635 if (isset($table->colclasses[$key])) {
1636 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1639 $cell->attributes['class'] .= ' cell c' . $key;
1640 if ($key == $lastkey) {
1641 $cell->attributes['class'] .= ' lastcol';
1642 $gotlastkey = true;
1644 $tdstyle = '';
1645 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1646 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1647 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1648 $cell->attributes['class'] = trim($cell->attributes['class']);
1649 $tdattributes = array_merge($cell->attributes, array(
1650 'style' => $tdstyle . $cell->style,
1651 'colspan' => $cell->colspan,
1652 'rowspan' => $cell->rowspan,
1653 'id' => $cell->id,
1654 'abbr' => $cell->abbr,
1655 'scope' => $cell->scope,
1657 $tagtype = 'td';
1658 if ($cell->header === true) {
1659 $tagtype = 'th';
1661 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1664 $output .= html_writer::end_tag('tr') . "\n";
1666 $output .= html_writer::end_tag('tbody') . "\n";
1668 $output .= html_writer::end_tag('table') . "\n";
1670 return $output;
1674 * Renders form element label
1676 * By default, the label is suffixed with a label separator defined in the
1677 * current language pack (colon by default in the English lang pack).
1678 * Adding the colon can be explicitly disabled if needed. Label separators
1679 * are put outside the label tag itself so they are not read by
1680 * screenreaders (accessibility).
1682 * Parameter $for explicitly associates the label with a form control. When
1683 * set, the value of this attribute must be the same as the value of
1684 * the id attribute of the form control in the same document. When null,
1685 * the label being defined is associated with the control inside the label
1686 * element.
1688 * @param string $text content of the label tag
1689 * @param string|null $for id of the element this label is associated with, null for no association
1690 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1691 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1692 * @return string HTML of the label element
1694 public static function label($text, $for, $colonize = true, array $attributes=array()) {
1695 if (!is_null($for)) {
1696 $attributes = array_merge($attributes, array('for' => $for));
1698 $text = trim($text);
1699 $label = self::tag('label', $text, $attributes);
1701 // TODO MDL-12192 $colonize disabled for now yet
1702 // if (!empty($text) and $colonize) {
1703 // // the $text may end with the colon already, though it is bad string definition style
1704 // $colon = get_string('labelsep', 'langconfig');
1705 // if (!empty($colon)) {
1706 // $trimmed = trim($colon);
1707 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1708 // //debugging('The label text should not end with colon or other label separator,
1709 // // please fix the string definition.', DEBUG_DEVELOPER);
1710 // } else {
1711 // $label .= $colon;
1712 // }
1713 // }
1714 // }
1716 return $label;
1720 * Combines a class parameter with other attributes. Aids in code reduction
1721 * because the class parameter is very frequently used.
1723 * If the class attribute is specified both in the attributes and in the
1724 * class parameter, the two values are combined with a space between.
1726 * @param string $class Optional CSS class (or classes as space-separated list)
1727 * @param array $attributes Optional other attributes as array
1728 * @return array Attributes (or null if still none)
1730 private static function add_class($class = '', array $attributes = null) {
1731 if ($class !== '') {
1732 $classattribute = array('class' => $class);
1733 if ($attributes) {
1734 if (array_key_exists('class', $attributes)) {
1735 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
1736 } else {
1737 $attributes = $classattribute + $attributes;
1739 } else {
1740 $attributes = $classattribute;
1743 return $attributes;
1747 * Creates a <div> tag. (Shortcut function.)
1749 * @param string $content HTML content of tag
1750 * @param string $class Optional CSS class (or classes as space-separated list)
1751 * @param array $attributes Optional other attributes as array
1752 * @return string HTML code for div
1754 public static function div($content, $class = '', array $attributes = null) {
1755 return self::tag('div', $content, self::add_class($class, $attributes));
1759 * Starts a <div> tag. (Shortcut function.)
1761 * @param string $class Optional CSS class (or classes as space-separated list)
1762 * @param array $attributes Optional other attributes as array
1763 * @return string HTML code for open div tag
1765 public static function start_div($class = '', array $attributes = null) {
1766 return self::start_tag('div', self::add_class($class, $attributes));
1770 * Ends a <div> tag. (Shortcut function.)
1772 * @return string HTML code for close div tag
1774 public static function end_div() {
1775 return self::end_tag('div');
1779 * Creates a <span> tag. (Shortcut function.)
1781 * @param string $content HTML content of tag
1782 * @param string $class Optional CSS class (or classes as space-separated list)
1783 * @param array $attributes Optional other attributes as array
1784 * @return string HTML code for span
1786 public static function span($content, $class = '', array $attributes = null) {
1787 return self::tag('span', $content, self::add_class($class, $attributes));
1791 * Starts a <span> tag. (Shortcut function.)
1793 * @param string $class Optional CSS class (or classes as space-separated list)
1794 * @param array $attributes Optional other attributes as array
1795 * @return string HTML code for open span tag
1797 public static function start_span($class = '', array $attributes = null) {
1798 return self::start_tag('span', self::add_class($class, $attributes));
1802 * Ends a <span> tag. (Shortcut function.)
1804 * @return string HTML code for close span tag
1806 public static function end_span() {
1807 return self::end_tag('span');
1812 * Simple javascript output class
1814 * @copyright 2010 Petr Skoda
1815 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1816 * @since Moodle 2.0
1817 * @package core
1818 * @category output
1820 class js_writer {
1823 * Returns javascript code calling the function
1825 * @param string $function function name, can be complex like Y.Event.purgeElement
1826 * @param array $arguments parameters
1827 * @param int $delay execution delay in seconds
1828 * @return string JS code fragment
1830 public static function function_call($function, array $arguments = null, $delay=0) {
1831 if ($arguments) {
1832 $arguments = array_map('json_encode', convert_to_array($arguments));
1833 $arguments = implode(', ', $arguments);
1834 } else {
1835 $arguments = '';
1837 $js = "$function($arguments);";
1839 if ($delay) {
1840 $delay = $delay * 1000; // in miliseconds
1841 $js = "setTimeout(function() { $js }, $delay);";
1843 return $js . "\n";
1847 * Special function which adds Y as first argument of function call.
1849 * @param string $function The function to call
1850 * @param array $extraarguments Any arguments to pass to it
1851 * @return string Some JS code
1853 public static function function_call_with_Y($function, array $extraarguments = null) {
1854 if ($extraarguments) {
1855 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1856 $arguments = 'Y, ' . implode(', ', $extraarguments);
1857 } else {
1858 $arguments = 'Y';
1860 return "$function($arguments);\n";
1864 * Returns JavaScript code to initialise a new object
1866 * @param string $var If it is null then no var is assigned the new object.
1867 * @param string $class The class to initialise an object for.
1868 * @param array $arguments An array of args to pass to the init method.
1869 * @param array $requirements Any modules required for this class.
1870 * @param int $delay The delay before initialisation. 0 = no delay.
1871 * @return string Some JS code
1873 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1874 if (is_array($arguments)) {
1875 $arguments = array_map('json_encode', convert_to_array($arguments));
1876 $arguments = implode(', ', $arguments);
1879 if ($var === null) {
1880 $js = "new $class(Y, $arguments);";
1881 } else if (strpos($var, '.')!==false) {
1882 $js = "$var = new $class(Y, $arguments);";
1883 } else {
1884 $js = "var $var = new $class(Y, $arguments);";
1887 if ($delay) {
1888 $delay = $delay * 1000; // in miliseconds
1889 $js = "setTimeout(function() { $js }, $delay);";
1892 if (count($requirements) > 0) {
1893 $requirements = implode("', '", $requirements);
1894 $js = "Y.use('$requirements', function(Y){ $js });";
1896 return $js."\n";
1900 * Returns code setting value to variable
1902 * @param string $name
1903 * @param mixed $value json serialised value
1904 * @param bool $usevar add var definition, ignored for nested properties
1905 * @return string JS code fragment
1907 public static function set_variable($name, $value, $usevar = true) {
1908 $output = '';
1910 if ($usevar) {
1911 if (strpos($name, '.')) {
1912 $output .= '';
1913 } else {
1914 $output .= 'var ';
1918 $output .= "$name = ".json_encode($value).";";
1920 return $output;
1924 * Writes event handler attaching code
1926 * @param array|string $selector standard YUI selector for elements, may be
1927 * array or string, element id is in the form "#idvalue"
1928 * @param string $event A valid DOM event (click, mousedown, change etc.)
1929 * @param string $function The name of the function to call
1930 * @param array $arguments An optional array of argument parameters to pass to the function
1931 * @return string JS code fragment
1933 public static function event_handler($selector, $event, $function, array $arguments = null) {
1934 $selector = json_encode($selector);
1935 $output = "Y.on('$event', $function, $selector, null";
1936 if (!empty($arguments)) {
1937 $output .= ', ' . json_encode($arguments);
1939 return $output . ");\n";
1944 * Holds all the information required to render a <table> by {@link core_renderer::table()}
1946 * Example of usage:
1947 * $t = new html_table();
1948 * ... // set various properties of the object $t as described below
1949 * echo html_writer::table($t);
1951 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1952 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1953 * @since Moodle 2.0
1954 * @package core
1955 * @category output
1957 class html_table {
1960 * @var string Value to use for the id attribute of the table
1962 public $id = null;
1965 * @var array Attributes of HTML attributes for the <table> element
1967 public $attributes = array();
1970 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
1971 * For more control over the rendering of the headers, an array of html_table_cell objects
1972 * can be passed instead of an array of strings.
1974 * Example of usage:
1975 * $t->head = array('Student', 'Grade');
1977 public $head;
1980 * @var array An array that can be used to make a heading span multiple columns.
1981 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1982 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
1984 * Example of usage:
1985 * $t->headspan = array(2,1);
1987 public $headspan;
1990 * @var array An array of column alignments.
1991 * The value is used as CSS 'text-align' property. Therefore, possible
1992 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1993 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1995 * Examples of usage:
1996 * $t->align = array(null, 'right');
1997 * or
1998 * $t->align[1] = 'right';
2000 public $align;
2003 * @var array The value is used as CSS 'size' property.
2005 * Examples of usage:
2006 * $t->size = array('50%', '50%');
2007 * or
2008 * $t->size[1] = '120px';
2010 public $size;
2013 * @var array An array of wrapping information.
2014 * The only possible value is 'nowrap' that sets the
2015 * CSS property 'white-space' to the value 'nowrap' in the given column.
2017 * Example of usage:
2018 * $t->wrap = array(null, 'nowrap');
2020 public $wrap;
2023 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2024 * $head specified, the string 'hr' (for horizontal ruler) can be used
2025 * instead of an array of cells data resulting in a divider rendered.
2027 * Example of usage with array of arrays:
2028 * $row1 = array('Harry Potter', '76 %');
2029 * $row2 = array('Hermione Granger', '100 %');
2030 * $t->data = array($row1, $row2);
2032 * Example with array of html_table_row objects: (used for more fine-grained control)
2033 * $cell1 = new html_table_cell();
2034 * $cell1->text = 'Harry Potter';
2035 * $cell1->colspan = 2;
2036 * $row1 = new html_table_row();
2037 * $row1->cells[] = $cell1;
2038 * $cell2 = new html_table_cell();
2039 * $cell2->text = 'Hermione Granger';
2040 * $cell3 = new html_table_cell();
2041 * $cell3->text = '100 %';
2042 * $row2 = new html_table_row();
2043 * $row2->cells = array($cell2, $cell3);
2044 * $t->data = array($row1, $row2);
2046 public $data;
2049 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2050 * @var string Width of the table, percentage of the page preferred.
2052 public $width = null;
2055 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2056 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2058 public $tablealign = null;
2061 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2062 * @var int Padding on each cell, in pixels
2064 public $cellpadding = null;
2067 * @var int Spacing between cells, in pixels
2068 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2070 public $cellspacing = null;
2073 * @var array Array of classes to add to particular rows, space-separated string.
2074 * Class 'lastrow' is added automatically for the last row in the table.
2076 * Example of usage:
2077 * $t->rowclasses[9] = 'tenth'
2079 public $rowclasses;
2082 * @var array An array of classes to add to every cell in a particular column,
2083 * space-separated string. Class 'cell' is added automatically by the renderer.
2084 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2085 * respectively. Class 'lastcol' is added automatically for all last cells
2086 * in a row.
2088 * Example of usage:
2089 * $t->colclasses = array(null, 'grade');
2091 public $colclasses;
2094 * @var string Description of the contents for screen readers.
2096 public $summary;
2099 * Constructor
2101 public function __construct() {
2102 $this->attributes['class'] = '';
2107 * Component representing a table row.
2109 * @copyright 2009 Nicolas Connault
2110 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2111 * @since Moodle 2.0
2112 * @package core
2113 * @category output
2115 class html_table_row {
2118 * @var string Value to use for the id attribute of the row.
2120 public $id = null;
2123 * @var array Array of html_table_cell objects
2125 public $cells = array();
2128 * @var string Value to use for the style attribute of the table row
2130 public $style = null;
2133 * @var array Attributes of additional HTML attributes for the <tr> element
2135 public $attributes = array();
2138 * Constructor
2139 * @param array $cells
2141 public function __construct(array $cells=null) {
2142 $this->attributes['class'] = '';
2143 $cells = (array)$cells;
2144 foreach ($cells as $cell) {
2145 if ($cell instanceof html_table_cell) {
2146 $this->cells[] = $cell;
2147 } else {
2148 $this->cells[] = new html_table_cell($cell);
2155 * Component representing a table cell.
2157 * @copyright 2009 Nicolas Connault
2158 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2159 * @since Moodle 2.0
2160 * @package core
2161 * @category output
2163 class html_table_cell {
2166 * @var string Value to use for the id attribute of the cell.
2168 public $id = null;
2171 * @var string The contents of the cell.
2173 public $text;
2176 * @var string Abbreviated version of the contents of the cell.
2178 public $abbr = null;
2181 * @var int Number of columns this cell should span.
2183 public $colspan = null;
2186 * @var int Number of rows this cell should span.
2188 public $rowspan = null;
2191 * @var string Defines a way to associate header cells and data cells in a table.
2193 public $scope = null;
2196 * @var bool Whether or not this cell is a header cell.
2198 public $header = null;
2201 * @var string Value to use for the style attribute of the table cell
2203 public $style = null;
2206 * @var array Attributes of additional HTML attributes for the <td> element
2208 public $attributes = array();
2211 * Constructs a table cell
2213 * @param string $text
2215 public function __construct($text = null) {
2216 $this->text = $text;
2217 $this->attributes['class'] = '';
2222 * Component representing a paging bar.
2224 * @copyright 2009 Nicolas Connault
2225 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2226 * @since Moodle 2.0
2227 * @package core
2228 * @category output
2230 class paging_bar implements renderable {
2233 * @var int The maximum number of pagelinks to display.
2235 public $maxdisplay = 18;
2238 * @var int The total number of entries to be pages through..
2240 public $totalcount;
2243 * @var int The page you are currently viewing.
2245 public $page;
2248 * @var int The number of entries that should be shown per page.
2250 public $perpage;
2253 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2254 * an equals sign and the page number.
2255 * If this is a moodle_url object then the pagevar param will be replaced by
2256 * the page no, for each page.
2258 public $baseurl;
2261 * @var string This is the variable name that you use for the pagenumber in your
2262 * code (ie. 'tablepage', 'blogpage', etc)
2264 public $pagevar;
2267 * @var string A HTML link representing the "previous" page.
2269 public $previouslink = null;
2272 * @var string A HTML link representing the "next" page.
2274 public $nextlink = null;
2277 * @var string A HTML link representing the first page.
2279 public $firstlink = null;
2282 * @var string A HTML link representing the last page.
2284 public $lastlink = null;
2287 * @var array An array of strings. One of them is just a string: the current page
2289 public $pagelinks = array();
2292 * Constructor paging_bar with only the required params.
2294 * @param int $totalcount The total number of entries available to be paged through
2295 * @param int $page The page you are currently viewing
2296 * @param int $perpage The number of entries that should be shown per page
2297 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2298 * @param string $pagevar name of page parameter that holds the page number
2300 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2301 $this->totalcount = $totalcount;
2302 $this->page = $page;
2303 $this->perpage = $perpage;
2304 $this->baseurl = $baseurl;
2305 $this->pagevar = $pagevar;
2309 * Prepares the paging bar for output.
2311 * This method validates the arguments set up for the paging bar and then
2312 * produces fragments of HTML to assist display later on.
2314 * @param renderer_base $output
2315 * @param moodle_page $page
2316 * @param string $target
2317 * @throws coding_exception
2319 public function prepare(renderer_base $output, moodle_page $page, $target) {
2320 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2321 throw new coding_exception('paging_bar requires a totalcount value.');
2323 if (!isset($this->page) || is_null($this->page)) {
2324 throw new coding_exception('paging_bar requires a page value.');
2326 if (empty($this->perpage)) {
2327 throw new coding_exception('paging_bar requires a perpage value.');
2329 if (empty($this->baseurl)) {
2330 throw new coding_exception('paging_bar requires a baseurl value.');
2333 if ($this->totalcount > $this->perpage) {
2334 $pagenum = $this->page - 1;
2336 if ($this->page > 0) {
2337 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2340 if ($this->perpage > 0) {
2341 $lastpage = ceil($this->totalcount / $this->perpage);
2342 } else {
2343 $lastpage = 1;
2346 if ($this->page > round(($this->maxdisplay/3)*2)) {
2347 $currpage = $this->page - round($this->maxdisplay/3);
2349 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2350 } else {
2351 $currpage = 0;
2354 $displaycount = $displaypage = 0;
2356 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2357 $displaypage = $currpage + 1;
2359 if ($this->page == $currpage) {
2360 $this->pagelinks[] = html_writer::span($displaypage, 'current-page');
2361 } else {
2362 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2363 $this->pagelinks[] = $pagelink;
2366 $displaycount++;
2367 $currpage++;
2370 if ($currpage < $lastpage) {
2371 $lastpageactual = $lastpage - 1;
2372 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2375 $pagenum = $this->page + 1;
2377 if ($pagenum != $displaypage) {
2378 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2385 * This class represents how a block appears on a page.
2387 * During output, each block instance is asked to return a block_contents object,
2388 * those are then passed to the $OUTPUT->block function for display.
2390 * contents should probably be generated using a moodle_block_..._renderer.
2392 * Other block-like things that need to appear on the page, for example the
2393 * add new block UI, are also represented as block_contents objects.
2395 * @copyright 2009 Tim Hunt
2396 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2397 * @since Moodle 2.0
2398 * @package core
2399 * @category output
2401 class block_contents {
2403 /** Used when the block cannot be collapsed **/
2404 const NOT_HIDEABLE = 0;
2406 /** Used when the block can be collapsed but currently is not **/
2407 const VISIBLE = 1;
2409 /** Used when the block has been collapsed **/
2410 const HIDDEN = 2;
2413 * @var int Used to set $skipid.
2415 protected static $idcounter = 1;
2418 * @var int All the blocks (or things that look like blocks) printed on
2419 * a page are given a unique number that can be used to construct id="" attributes.
2420 * This is set automatically be the {@link prepare()} method.
2421 * Do not try to set it manually.
2423 public $skipid;
2426 * @var int If this is the contents of a real block, this should be set
2427 * to the block_instance.id. Otherwise this should be set to 0.
2429 public $blockinstanceid = 0;
2432 * @var int If this is a real block instance, and there is a corresponding
2433 * block_position.id for the block on this page, this should be set to that id.
2434 * Otherwise it should be 0.
2436 public $blockpositionid = 0;
2439 * @var array An array of attribute => value pairs that are put on the outer div of this
2440 * block. {@link $id} and {@link $classes} attributes should be set separately.
2442 public $attributes;
2445 * @var string The title of this block. If this came from user input, it should already
2446 * have had format_string() processing done on it. This will be output inside
2447 * <h2> tags. Please do not cause invalid XHTML.
2449 public $title = '';
2452 * @var string The label to use when the block does not, or will not have a visible title.
2453 * You should never set this as well as title... it will just be ignored.
2455 public $arialabel = '';
2458 * @var string HTML for the content
2460 public $content = '';
2463 * @var array An alternative to $content, it you want a list of things with optional icons.
2465 public $footer = '';
2468 * @var string Any small print that should appear under the block to explain
2469 * to the teacher about the block, for example 'This is a sticky block that was
2470 * added in the system context.'
2472 public $annotation = '';
2475 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2476 * the user can toggle whether this block is visible.
2478 public $collapsible = self::NOT_HIDEABLE;
2481 * Set this to true if the block is dockable.
2482 * @var bool
2484 public $dockable = false;
2487 * @var array A (possibly empty) array of editing controls. Each element of
2488 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2489 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2491 public $controls = array();
2495 * Create new instance of block content
2496 * @param array $attributes
2498 public function __construct(array $attributes = null) {
2499 $this->skipid = self::$idcounter;
2500 self::$idcounter += 1;
2502 if ($attributes) {
2503 // standard block
2504 $this->attributes = $attributes;
2505 } else {
2506 // simple "fake" blocks used in some modules and "Add new block" block
2507 $this->attributes = array('class'=>'block');
2512 * Add html class to block
2514 * @param string $class
2516 public function add_class($class) {
2517 $this->attributes['class'] .= ' '.$class;
2523 * This class represents a target for where a block can go when it is being moved.
2525 * This needs to be rendered as a form with the given hidden from fields, and
2526 * clicking anywhere in the form should submit it. The form action should be
2527 * $PAGE->url.
2529 * @copyright 2009 Tim Hunt
2530 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2531 * @since Moodle 2.0
2532 * @package core
2533 * @category output
2535 class block_move_target {
2538 * @var moodle_url Move url
2540 public $url;
2543 * Constructor
2544 * @param moodle_url $url
2546 public function __construct(moodle_url $url) {
2547 $this->url = $url;
2552 * Custom menu item
2554 * This class is used to represent one item within a custom menu that may or may
2555 * not have children.
2557 * @copyright 2010 Sam Hemelryk
2558 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2559 * @since Moodle 2.0
2560 * @package core
2561 * @category output
2563 class custom_menu_item implements renderable {
2566 * @var string The text to show for the item
2568 protected $text;
2571 * @var moodle_url The link to give the icon if it has no children
2573 protected $url;
2576 * @var string A title to apply to the item. By default the text
2578 protected $title;
2581 * @var int A sort order for the item, not necessary if you order things in
2582 * the CFG var.
2584 protected $sort;
2587 * @var custom_menu_item A reference to the parent for this item or NULL if
2588 * it is a top level item
2590 protected $parent;
2593 * @var array A array in which to store children this item has.
2595 protected $children = array();
2598 * @var int A reference to the sort var of the last child that was added
2600 protected $lastsort = 0;
2603 * Constructs the new custom menu item
2605 * @param string $text
2606 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2607 * @param string $title A title to apply to this item [Optional]
2608 * @param int $sort A sort or to use if we need to sort differently [Optional]
2609 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2610 * belongs to, only if the child has a parent. [Optional]
2612 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
2613 $this->text = $text;
2614 $this->url = $url;
2615 $this->title = $title;
2616 $this->sort = (int)$sort;
2617 $this->parent = $parent;
2621 * Adds a custom menu item as a child of this node given its properties.
2623 * @param string $text
2624 * @param moodle_url $url
2625 * @param string $title
2626 * @param int $sort
2627 * @return custom_menu_item
2629 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
2630 $key = count($this->children);
2631 if (empty($sort)) {
2632 $sort = $this->lastsort + 1;
2634 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2635 $this->lastsort = (int)$sort;
2636 return $this->children[$key];
2640 * Removes a custom menu item that is a child or descendant to the current menu.
2642 * Returns true if child was found and removed.
2644 * @param custom_menu_item $menuitem
2645 * @return bool
2647 public function remove_child(custom_menu_item $menuitem) {
2648 $removed = false;
2649 if (($key = array_search($menuitem, $this->children)) !== false) {
2650 unset($this->children[$key]);
2651 $this->children = array_values($this->children);
2652 $removed = true;
2653 } else {
2654 foreach ($this->children as $child) {
2655 if ($removed = $child->remove_child($menuitem)) {
2656 break;
2660 return $removed;
2664 * Returns the text for this item
2665 * @return string
2667 public function get_text() {
2668 return $this->text;
2672 * Returns the url for this item
2673 * @return moodle_url
2675 public function get_url() {
2676 return $this->url;
2680 * Returns the title for this item
2681 * @return string
2683 public function get_title() {
2684 return $this->title;
2688 * Sorts and returns the children for this item
2689 * @return array
2691 public function get_children() {
2692 $this->sort();
2693 return $this->children;
2697 * Gets the sort order for this child
2698 * @return int
2700 public function get_sort_order() {
2701 return $this->sort;
2705 * Gets the parent this child belong to
2706 * @return custom_menu_item
2708 public function get_parent() {
2709 return $this->parent;
2713 * Sorts the children this item has
2715 public function sort() {
2716 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2720 * Returns true if this item has any children
2721 * @return bool
2723 public function has_children() {
2724 return (count($this->children) > 0);
2728 * Sets the text for the node
2729 * @param string $text
2731 public function set_text($text) {
2732 $this->text = (string)$text;
2736 * Sets the title for the node
2737 * @param string $title
2739 public function set_title($title) {
2740 $this->title = (string)$title;
2744 * Sets the url for the node
2745 * @param moodle_url $url
2747 public function set_url(moodle_url $url) {
2748 $this->url = $url;
2753 * Custom menu class
2755 * This class is used to operate a custom menu that can be rendered for the page.
2756 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2757 * of custom_menu_item nodes that can be rendered by the core renderer.
2759 * To configure the custom menu:
2760 * Settings: Administration > Appearance > Themes > Theme settings
2762 * @copyright 2010 Sam Hemelryk
2763 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2764 * @since Moodle 2.0
2765 * @package core
2766 * @category output
2768 class custom_menu extends custom_menu_item {
2771 * @var string The language we should render for, null disables multilang support.
2773 protected $currentlanguage = null;
2776 * Creates the custom menu
2778 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2779 * @param string $currentlanguage the current language code, null disables multilang support
2781 public function __construct($definition = '', $currentlanguage = null) {
2782 $this->currentlanguage = $currentlanguage;
2783 parent::__construct('root'); // create virtual root element of the menu
2784 if (!empty($definition)) {
2785 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2790 * Overrides the children of this custom menu. Useful when getting children
2791 * from $CFG->custommenuitems
2793 * @param array $children
2795 public function override_children(array $children) {
2796 $this->children = array();
2797 foreach ($children as $child) {
2798 if ($child instanceof custom_menu_item) {
2799 $this->children[] = $child;
2805 * Converts a string into a structured array of custom_menu_items which can
2806 * then be added to a custom menu.
2808 * Structure:
2809 * text|url|title|langs
2810 * The number of hyphens at the start determines the depth of the item. The
2811 * languages are optional, comma separated list of languages the line is for.
2813 * Example structure:
2814 * First level first item|http://www.moodle.com/
2815 * -Second level first item|http://www.moodle.com/partners/
2816 * -Second level second item|http://www.moodle.com/hq/
2817 * --Third level first item|http://www.moodle.com/jobs/
2818 * -Second level third item|http://www.moodle.com/development/
2819 * First level second item|http://www.moodle.com/feedback/
2820 * First level third item
2821 * English only|http://moodle.com|English only item|en
2822 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2825 * @static
2826 * @param string $text the menu items definition
2827 * @param string $language the language code, null disables multilang support
2828 * @return array
2830 public static function convert_text_to_menu_nodes($text, $language = null) {
2831 $root = new custom_menu();
2832 $lastitem = $root;
2833 $lastdepth = 0;
2834 $hiddenitems = array();
2835 $lines = explode("\n", $text);
2836 foreach ($lines as $linenumber => $line) {
2837 $line = trim($line);
2838 if (strlen($line) == 0) {
2839 continue;
2841 // Parse item settings.
2842 $itemtext = null;
2843 $itemurl = null;
2844 $itemtitle = null;
2845 $itemvisible = true;
2846 $settings = explode('|', $line);
2847 foreach ($settings as $i => $setting) {
2848 $setting = trim($setting);
2849 if (!empty($setting)) {
2850 switch ($i) {
2851 case 0:
2852 $itemtext = ltrim($setting, '-');
2853 $itemtitle = $itemtext;
2854 break;
2855 case 1:
2856 try {
2857 $itemurl = new moodle_url($setting);
2858 } catch (moodle_exception $exception) {
2859 // We're not actually worried about this, we don't want to mess up the display
2860 // just for a wrongly entered URL.
2861 $itemurl = null;
2863 break;
2864 case 2:
2865 $itemtitle = $setting;
2866 break;
2867 case 3:
2868 if (!empty($language)) {
2869 $itemlanguages = array_map('trim', explode(',', $setting));
2870 $itemvisible &= in_array($language, $itemlanguages);
2872 break;
2876 // Get depth of new item.
2877 preg_match('/^(\-*)/', $line, $match);
2878 $itemdepth = strlen($match[1]) + 1;
2879 // Find parent item for new item.
2880 while (($lastdepth - $itemdepth) >= 0) {
2881 $lastitem = $lastitem->get_parent();
2882 $lastdepth--;
2884 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1);
2885 $lastdepth++;
2886 if (!$itemvisible) {
2887 $hiddenitems[] = $lastitem;
2890 foreach ($hiddenitems as $item) {
2891 $item->parent->remove_child($item);
2893 return $root->get_children();
2897 * Sorts two custom menu items
2899 * This function is designed to be used with the usort method
2900 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2902 * @static
2903 * @param custom_menu_item $itema
2904 * @param custom_menu_item $itemb
2905 * @return int
2907 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2908 $itema = $itema->get_sort_order();
2909 $itemb = $itemb->get_sort_order();
2910 if ($itema == $itemb) {
2911 return 0;
2913 return ($itema > $itemb) ? +1 : -1;
2918 * Stores one tab
2920 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2921 * @package core
2923 class tabobject implements renderable {
2924 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
2925 var $id;
2926 /** @var moodle_url|string link */
2927 var $link;
2928 /** @var string text on the tab */
2929 var $text;
2930 /** @var string title under the link, by defaul equals to text */
2931 var $title;
2932 /** @var bool whether to display a link under the tab name when it's selected */
2933 var $linkedwhenselected = false;
2934 /** @var bool whether the tab is inactive */
2935 var $inactive = false;
2936 /** @var bool indicates that this tab's child is selected */
2937 var $activated = false;
2938 /** @var bool indicates that this tab is selected */
2939 var $selected = false;
2940 /** @var array stores children tabobjects */
2941 var $subtree = array();
2942 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
2943 var $level = 1;
2946 * Constructor
2948 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
2949 * @param string|moodle_url $link
2950 * @param string $text text on the tab
2951 * @param string $title title under the link, by defaul equals to text
2952 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
2954 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
2955 $this->id = $id;
2956 $this->link = $link;
2957 $this->text = $text;
2958 $this->title = $title ? $title : $text;
2959 $this->linkedwhenselected = $linkedwhenselected;
2963 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
2965 * @param string $selected the id of the selected tab (whatever row it's on),
2966 * if null marks all tabs as unselected
2967 * @return bool whether this tab is selected or contains selected tab in its subtree
2969 protected function set_selected($selected) {
2970 if ((string)$selected === (string)$this->id) {
2971 $this->selected = true;
2972 // This tab is selected. No need to travel through subtree.
2973 return true;
2975 foreach ($this->subtree as $subitem) {
2976 if ($subitem->set_selected($selected)) {
2977 // This tab has child that is selected. Mark it as activated. No need to check other children.
2978 $this->activated = true;
2979 return true;
2982 return false;
2986 * Travels through tree and finds a tab with specified id
2988 * @param string $id
2989 * @return tabtree|null
2991 public function find($id) {
2992 if ((string)$this->id === (string)$id) {
2993 return $this;
2995 foreach ($this->subtree as $tab) {
2996 if ($obj = $tab->find($id)) {
2997 return $obj;
3000 return null;
3004 * Allows to mark each tab's level in the tree before rendering.
3006 * @param int $level
3008 protected function set_level($level) {
3009 $this->level = $level;
3010 foreach ($this->subtree as $tab) {
3011 $tab->set_level($level + 1);
3017 * Stores tabs list
3019 * Example how to print a single line tabs:
3020 * $rows = array(
3021 * new tabobject(...),
3022 * new tabobject(...)
3023 * );
3024 * echo $OUTPUT->tabtree($rows, $selectedid);
3026 * Multiple row tabs may not look good on some devices but if you want to use them
3027 * you can specify ->subtree for the active tabobject.
3029 * @copyright 2013 Marina Glancy
3030 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3031 * @since Moodle 2.5
3032 * @package core
3033 * @category output
3035 class tabtree extends tabobject {
3037 * Constuctor
3039 * It is highly recommended to call constructor when list of tabs is already
3040 * populated, this way you ensure that selected and inactive tabs are located
3041 * and attribute level is set correctly.
3043 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3044 * @param string|null $selected which tab to mark as selected, all parent tabs will
3045 * automatically be marked as activated
3046 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3047 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3049 public function __construct($tabs, $selected = null, $inactive = null) {
3050 $this->subtree = $tabs;
3051 if ($selected !== null) {
3052 $this->set_selected($selected);
3054 if ($inactive !== null) {
3055 if (is_array($inactive)) {
3056 foreach ($inactive as $id) {
3057 if ($tab = $this->find($id)) {
3058 $tab->inactive = true;
3061 } else if ($tab = $this->find($inactive)) {
3062 $tab->inactive = true;
3065 $this->set_level(0);
3070 * An action menu.
3072 * This action menu component takes a series of primary and secondary actions.
3073 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
3074 * down menu.
3076 * @package core
3077 * @category output
3078 * @copyright 2013 Sam Hemelryk
3079 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3081 class action_menu implements renderable {
3084 * Top right alignment.
3086 const TL = 1;
3089 * Top right alignment.
3091 const TR = 2;
3094 * Top right alignment.
3096 const BL = 3;
3099 * Top right alignment.
3101 const BR = 4;
3104 * The instance number. This is unique to this instance of the action menu.
3105 * @var int
3107 protected $instance = 0;
3110 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
3111 * @var array
3113 protected $primaryactions = array();
3116 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
3117 * @var array
3119 protected $secondaryactions = array();
3122 * An array of attributes added to the container of the action menu.
3123 * Initialised with defaults during construction.
3124 * @var array
3126 public $attributes = array();
3128 * An array of attributes added to the container of the primary actions.
3129 * Initialised with defaults during construction.
3130 * @var array
3132 public $attributesprimary = array();
3134 * An array of attributes added to the container of the secondary actions.
3135 * Initialised with defaults during construction.
3136 * @var array
3138 public $attributessecondary = array();
3141 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
3142 * @var array
3144 public $actiontext = null;
3147 * An icon to use for the toggling the secondary menu (dropdown).
3148 * @var actionicon
3150 public $actionicon;
3153 * Any text to use for the toggling the secondary menu (dropdown).
3154 * @var menutrigger
3156 public $menutrigger = '';
3159 * Place the action menu before all other actions.
3160 * @var prioritise
3162 public $prioritise = false;
3165 * Constructs the action menu with the given items.
3167 * @param array $actions An array of actions.
3169 public function __construct(array $actions = array()) {
3170 static $initialised = 0;
3171 $this->instance = $initialised;
3172 $initialised++;
3174 $this->attributes = array(
3175 'id' => 'action-menu-'.$this->instance,
3176 'class' => 'moodle-actionmenu',
3177 'data-enhance' => 'moodle-core-actionmenu'
3179 $this->attributesprimary = array(
3180 'id' => 'action-menu-'.$this->instance.'-menubar',
3181 'class' => 'menubar',
3182 'role' => 'menubar'
3184 $this->attributessecondary = array(
3185 'id' => 'action-menu-'.$this->instance.'-menu',
3186 'class' => 'menu',
3187 'data-rel' => 'menu-content',
3188 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
3189 'role' => 'menu'
3191 $this->set_alignment(self::TR, self::BR);
3192 foreach ($actions as $action) {
3193 $this->add($action);
3197 public function set_menu_trigger($trigger) {
3198 $this->menutrigger = $trigger;
3202 * Initialises JS required fore the action menu.
3203 * The JS is only required once as it manages all action menu's on the page.
3205 * @param moodle_page $page
3207 public function initialise_js(moodle_page $page) {
3208 static $initialised = false;
3209 if (!$initialised) {
3210 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
3211 $initialised = true;
3216 * Adds an action to this action menu.
3218 * @param action_menu_link|pix_icon|string $action
3220 public function add($action) {
3221 if ($action instanceof action_link) {
3222 if ($action->primary) {
3223 $this->add_primary_action($action);
3224 } else {
3225 $this->add_secondary_action($action);
3227 } else if ($action instanceof pix_icon) {
3228 $this->add_primary_action($action);
3229 } else {
3230 $this->add_secondary_action($action);
3235 * Adds a primary action to the action menu.
3237 * @param action_menu_link|action_link|pix_icon|string $action
3239 public function add_primary_action($action) {
3240 if ($action instanceof action_link || $action instanceof pix_icon) {
3241 $action->attributes['role'] = 'menuitem';
3242 if ($action instanceof action_menu_link) {
3243 $action->actionmenu = $this;
3246 $this->primaryactions[] = $action;
3250 * Adds a secondary action to the action menu.
3252 * @param action_link|pix_icon|string $action
3254 public function add_secondary_action($action) {
3255 if ($action instanceof action_link || $action instanceof pix_icon) {
3256 $action->attributes['role'] = 'menuitem';
3257 if ($action instanceof action_menu_link) {
3258 $action->actionmenu = $this;
3261 $this->secondaryactions[] = $action;
3265 * Returns the primary actions ready to be rendered.
3267 * @param core_renderer $output The renderer to use for getting icons.
3268 * @return array
3270 public function get_primary_actions(core_renderer $output = null) {
3271 global $OUTPUT;
3272 if ($output === null) {
3273 $output = $OUTPUT;
3275 $pixicon = $this->actionicon;
3276 $linkclasses = array('toggle-display');
3278 $title = '';
3279 if (!empty($this->menutrigger)) {
3280 $pixicon = '<b class="caret"></b>';
3281 $linkclasses[] = 'textmenu';
3282 } else {
3283 $title = new lang_string('actions', 'moodle');
3284 $this->actionicon = new pix_icon(
3285 't/edit_menu',
3287 'moodle',
3288 array('class' => 'iconsmall actionmenu', 'title' => '')
3290 $pixicon = $this->actionicon;
3292 if ($pixicon instanceof renderable) {
3293 $pixicon = $output->render($pixicon);
3294 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
3295 $title = $pixicon->attributes['alt'];
3298 $string = '';
3299 if ($this->actiontext) {
3300 $string = $this->actiontext;
3302 $actions = $this->primaryactions;
3303 $attributes = array(
3304 'class' => implode(' ', $linkclasses),
3305 'title' => $title,
3306 'id' => 'action-menu-toggle-'.$this->instance,
3307 'role' => 'menuitem'
3309 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
3310 if ($this->prioritise) {
3311 array_unshift($actions, $link);
3312 } else {
3313 $actions[] = $link;
3315 return $actions;
3319 * Returns the secondary actions ready to be rendered.
3320 * @return array
3322 public function get_secondary_actions() {
3323 return $this->secondaryactions;
3327 * Sets the selector that should be used to find the owning node of this menu.
3328 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
3330 public function set_owner_selector($selector) {
3331 $this->attributes['data-owner'] = $selector;
3335 * Sets the alignment of the dialogue in relation to button used to toggle it.
3337 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3338 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3340 public function set_alignment($dialogue, $button) {
3341 if (isset($this->attributessecondary['data-align'])) {
3342 // We've already got one set, lets remove the old class so as to avoid troubles.
3343 $class = $this->attributessecondary['class'];
3344 $search = 'align-'.$this->attributessecondary['data-align'];
3345 $this->attributessecondary['class'] = str_replace($search, '', $class);
3347 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
3348 $this->attributessecondary['data-align'] = $align;
3349 $this->attributessecondary['class'] .= ' align-'.$align;
3353 * Returns a string to describe the alignment.
3355 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3356 * @return string
3358 protected function get_align_string($align) {
3359 switch ($align) {
3360 case self::TL :
3361 return 'tl';
3362 case self::TR :
3363 return 'tr';
3364 case self::BL :
3365 return 'bl';
3366 case self::BR :
3367 return 'br';
3368 default :
3369 return 'tl';
3374 * Sets a constraint for the dialogue.
3376 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
3377 * element the constraint identifies.
3379 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
3381 public function set_constraint($ancestorselector) {
3382 $this->attributessecondary['data-constraint'] = $ancestorselector;
3386 * If you call this method the action menu will be displayed but will not be enhanced.
3388 * By not displaying the menu enhanced all items will be displayed in a single row.
3390 public function do_not_enhance() {
3391 unset($this->attributes['data-enhance']);
3395 * Returns true if this action menu will be enhanced.
3397 * @return bool
3399 public function will_be_enhanced() {
3400 return isset($this->attributes['data-enhance']);
3404 * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
3406 * This property can be useful when the action menu is displayed within a parent element that is either floated
3407 * or relatively positioned.
3408 * In that situation the width of the menu is determined by the width of the parent element which may not be large
3409 * enough for the menu items without them wrapping.
3410 * This disables the wrapping so that the menu takes on the width of the longest item.
3412 * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
3414 public function set_nowrap_on_items($value = true) {
3415 $class = 'nowrap-items';
3416 if (!empty($this->attributes['class'])) {
3417 $pos = strpos($this->attributes['class'], $class);
3418 if ($value === true && $pos === false) {
3419 // The value is true and the class has not been set yet. Add it.
3420 $this->attributes['class'] .= ' '.$class;
3421 } else if ($value === false && $pos !== false) {
3422 // The value is false and the class has been set. Remove it.
3423 $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class));
3425 } else if ($value) {
3426 // The value is true and the class has not been set yet. Add it.
3427 $this->attributes['class'] = $class;
3433 * An action menu filler
3435 * @package core
3436 * @category output
3437 * @copyright 2013 Andrew Nicols
3438 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3440 class action_menu_filler extends action_link implements renderable {
3443 * True if this is a primary action. False if not.
3444 * @var bool
3446 public $primary = true;
3449 * Constructs the object.
3451 public function __construct() {
3456 * An action menu action
3458 * @package core
3459 * @category output
3460 * @copyright 2013 Sam Hemelryk
3461 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3463 class action_menu_link extends action_link implements renderable {
3466 * True if this is a primary action. False if not.
3467 * @var bool
3469 public $primary = true;
3472 * The action menu this link has been added to.
3473 * @var action_menu
3475 public $actionmenu = null;
3478 * Constructs the object.
3480 * @param moodle_url $url The URL for the action.
3481 * @param pix_icon $icon The icon to represent the action.
3482 * @param string $text The text to represent the action.
3483 * @param bool $primary Whether this is a primary action or not.
3484 * @param array $attributes Any attribtues associated with the action.
3486 public function __construct(moodle_url $url, pix_icon $icon = null, $text, $primary = true, array $attributes = array()) {
3487 parent::__construct($url, $text, null, $attributes, $icon);
3488 $this->primary = (bool)$primary;
3489 $this->add_class('menu-action');
3490 $this->attributes['role'] = 'menuitem';
3495 * A primary action menu action
3497 * @package core
3498 * @category output
3499 * @copyright 2013 Sam Hemelryk
3500 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3502 class action_menu_link_primary extends action_menu_link {
3504 * Constructs the object.
3506 * @param moodle_url $url
3507 * @param pix_icon $icon
3508 * @param string $text
3509 * @param array $attributes
3511 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
3512 parent::__construct($url, $icon, $text, true, $attributes);
3517 * A secondary action menu action
3519 * @package core
3520 * @category output
3521 * @copyright 2013 Sam Hemelryk
3522 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3524 class action_menu_link_secondary extends action_menu_link {
3526 * Constructs the object.
3528 * @param moodle_url $url
3529 * @param pix_icon $icon
3530 * @param string $text
3531 * @param array $attributes
3533 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
3534 parent::__construct($url, $icon, $text, false, $attributes);