Merge branch 'MDL-40920_master' of https://github.com/markn86/moodle
[moodle.git] / lib / outputcomponents.php
blob5157293a23b9a94bc208a6d9f09fed655ea0bf4a
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 * User picture constructor.
180 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
181 * It is recommended to add also contextid of the user for performance reasons.
183 public function __construct(stdClass $user) {
184 global $DB;
186 if (empty($user->id)) {
187 throw new coding_exception('User id is required when printing user avatar image.');
190 // only touch the DB if we are missing data and complain loudly...
191 $needrec = false;
192 foreach (self::$fields as $field) {
193 if (!array_key_exists($field, $user)) {
194 $needrec = true;
195 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
196 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
197 break;
201 if ($needrec) {
202 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
203 } else {
204 $this->user = clone($user);
209 * Returns a list of required user fields, useful when fetching required user info from db.
211 * In some cases we have to fetch the user data together with some other information,
212 * the idalias is useful there because the id would otherwise override the main
213 * id of the result record. Please note it has to be converted back to id before rendering.
215 * @param string $tableprefix name of database table prefix in query
216 * @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)
217 * @param string $idalias alias of id field
218 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
219 * @return string
221 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
222 if (!$tableprefix and !$extrafields and !$idalias) {
223 return implode(',', self::$fields);
225 if ($tableprefix) {
226 $tableprefix .= '.';
228 foreach (self::$fields as $field) {
229 if ($field === 'id' and $idalias and $idalias !== 'id') {
230 $fields[$field] = "$tableprefix$field AS $idalias";
231 } else {
232 if ($fieldprefix and $field !== 'id') {
233 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
234 } else {
235 $fields[$field] = "$tableprefix$field";
239 // add extra fields if not already there
240 if ($extrafields) {
241 foreach ($extrafields as $e) {
242 if ($e === 'id' or isset($fields[$e])) {
243 continue;
245 if ($fieldprefix) {
246 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
247 } else {
248 $fields[$e] = "$tableprefix$e";
252 return implode(',', $fields);
256 * Extract the aliased user fields from a given record
258 * Given a record that was previously obtained using {@link self::fields()} with aliases,
259 * this method extracts user related unaliased fields.
261 * @param stdClass $record containing user picture fields
262 * @param array $extrafields extra fields included in the $record
263 * @param string $idalias alias of the id field
264 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
265 * @return stdClass object with unaliased user fields
267 public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
269 if (empty($idalias)) {
270 $idalias = 'id';
273 $return = new stdClass();
275 foreach (self::$fields as $field) {
276 if ($field === 'id') {
277 if (property_exists($record, $idalias)) {
278 $return->id = $record->{$idalias};
280 } else {
281 if (property_exists($record, $fieldprefix.$field)) {
282 $return->{$field} = $record->{$fieldprefix.$field};
286 // add extra fields if not already there
287 if ($extrafields) {
288 foreach ($extrafields as $e) {
289 if ($e === 'id' or property_exists($return, $e)) {
290 continue;
292 $return->{$e} = $record->{$fieldprefix.$e};
296 return $return;
300 * Works out the URL for the users picture.
302 * This method is recommended as it avoids costly redirects of user pictures
303 * if requests are made for non-existent files etc.
305 * @param moodle_page $page
306 * @param renderer_base $renderer
307 * @return moodle_url
309 public function get_url(moodle_page $page, renderer_base $renderer = null) {
310 global $CFG;
312 if (is_null($renderer)) {
313 $renderer = $page->get_renderer('core');
316 // Sort out the filename and size. Size is only required for the gravatar
317 // implementation presently.
318 if (empty($this->size)) {
319 $filename = 'f2';
320 $size = 35;
321 } else if ($this->size === true or $this->size == 1) {
322 $filename = 'f1';
323 $size = 100;
324 } else if ($this->size > 100) {
325 $filename = 'f3';
326 $size = (int)$this->size;
327 } else if ($this->size >= 50) {
328 $filename = 'f1';
329 $size = (int)$this->size;
330 } else {
331 $filename = 'f2';
332 $size = (int)$this->size;
335 $defaulturl = $renderer->pix_url('u/'.$filename); // default image
337 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
338 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
339 // Protect images if login required and not logged in;
340 // also if login is required for profile images and is not logged in or guest
341 // do not use require_login() because it is expensive and not suitable here anyway.
342 return $defaulturl;
345 // First try to detect deleted users - but do not read from database for performance reasons!
346 if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
347 // All deleted users should have email replaced by md5 hash,
348 // all active users are expected to have valid email.
349 return $defaulturl;
352 // Did the user upload a picture?
353 if ($this->user->picture > 0) {
354 if (!empty($this->user->contextid)) {
355 $contextid = $this->user->contextid;
356 } else {
357 $context = context_user::instance($this->user->id, IGNORE_MISSING);
358 if (!$context) {
359 // This must be an incorrectly deleted user, all other users have context.
360 return $defaulturl;
362 $contextid = $context->id;
365 $path = '/';
366 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
367 // We append the theme name to the file path if we have it so that
368 // in the circumstance that the profile picture is not available
369 // when the user actually requests it they still get the profile
370 // picture for the correct theme.
371 $path .= $page->theme->name.'/';
373 // Set the image URL to the URL for the uploaded file and return.
374 $url = moodle_url::make_pluginfile_url($contextid, 'user', 'icon', NULL, $path, $filename);
375 $url->param('rev', $this->user->picture);
376 return $url;
379 if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
380 // Normalise the size variable to acceptable bounds
381 if ($size < 1 || $size > 512) {
382 $size = 35;
384 // Hash the users email address
385 $md5 = md5(strtolower(trim($this->user->email)));
386 // Build a gravatar URL with what we know.
388 // Find the best default image URL we can (MDL-35669)
389 if (empty($CFG->gravatardefaulturl)) {
390 $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
391 if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
392 $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
393 } else {
394 $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
396 } else {
397 $gravatardefault = $CFG->gravatardefaulturl;
400 // If the currently requested page is https then we'll return an
401 // https gravatar page.
402 if (strpos($CFG->httpswwwroot, 'https:') === 0) {
403 $gravatardefault = str_replace($CFG->wwwroot, $CFG->httpswwwroot, $gravatardefault); // Replace by secure url.
404 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
405 } else {
406 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
410 return $defaulturl;
415 * Data structure representing a help icon.
417 * @copyright 2010 Petr Skoda (info@skodak.org)
418 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
419 * @since Moodle 2.0
420 * @package core
421 * @category output
423 class help_icon implements renderable {
426 * @var string lang pack identifier (without the "_help" suffix),
427 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
428 * must exist.
430 public $identifier;
433 * @var string Component name, the same as in get_string()
435 public $component;
438 * @var string Extra descriptive text next to the icon
440 public $linktext = null;
443 * Constructor
445 * @param string $identifier string for help page title,
446 * string with _help suffix is used for the actual help text.
447 * string with _link suffix is used to create a link to further info (if it exists)
448 * @param string $component
450 public function __construct($identifier, $component) {
451 $this->identifier = $identifier;
452 $this->component = $component;
456 * Verifies that both help strings exists, shows debug warnings if not
458 public function diag_strings() {
459 $sm = get_string_manager();
460 if (!$sm->string_exists($this->identifier, $this->component)) {
461 debugging("Help title string does not exist: [$this->identifier, $this->component]");
463 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
464 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
471 * Data structure representing an icon.
473 * @copyright 2010 Petr Skoda
474 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
475 * @since Moodle 2.0
476 * @package core
477 * @category output
479 class pix_icon implements renderable {
482 * @var string The icon name
484 var $pix;
487 * @var string The component the icon belongs to.
489 var $component;
492 * @var array An array of attributes to use on the icon
494 var $attributes = array();
497 * Constructor
499 * @param string $pix short icon name
500 * @param string $alt The alt text to use for the icon
501 * @param string $component component name
502 * @param array $attributes html attributes
504 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
505 $this->pix = $pix;
506 $this->component = $component;
507 $this->attributes = (array)$attributes;
509 $this->attributes['alt'] = $alt;
510 if (empty($this->attributes['class'])) {
511 $this->attributes['class'] = 'smallicon';
513 if (!isset($this->attributes['title'])) {
514 $this->attributes['title'] = $this->attributes['alt'];
515 } else if (empty($this->attributes['title'])) {
516 // Remove the title attribute if empty, we probably want to use the parent node's title
517 // and some browsers might overwrite it with an empty title.
518 unset($this->attributes['title']);
524 * Data structure representing an emoticon image
526 * @copyright 2010 David Mudrak
527 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
528 * @since Moodle 2.0
529 * @package core
530 * @category output
532 class pix_emoticon extends pix_icon implements renderable {
535 * Constructor
536 * @param string $pix short icon name
537 * @param string $alt alternative text
538 * @param string $component emoticon image provider
539 * @param array $attributes explicit HTML attributes
541 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
542 if (empty($attributes['class'])) {
543 $attributes['class'] = 'emoticon';
545 parent::__construct($pix, $alt, $component, $attributes);
550 * Data structure representing a simple form with only one button.
552 * @copyright 2009 Petr Skoda
553 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
554 * @since Moodle 2.0
555 * @package core
556 * @category output
558 class single_button implements renderable {
561 * @var moodle_url Target url
563 var $url;
566 * @var string Button label
568 var $label;
571 * @var string Form submit method post or get
573 var $method = 'post';
576 * @var string Wrapping div class
578 var $class = 'singlebutton';
581 * @var bool True if button disabled, false if normal
583 var $disabled = false;
586 * @var string Button tooltip
588 var $tooltip = null;
591 * @var string Form id
593 var $formid;
596 * @var array List of attached actions
598 var $actions = array();
601 * Constructor
602 * @param moodle_url $url
603 * @param string $label button text
604 * @param string $method get or post submit method
606 public function __construct(moodle_url $url, $label, $method='post') {
607 $this->url = clone($url);
608 $this->label = $label;
609 $this->method = $method;
613 * Shortcut for adding a JS confirm dialog when the button is clicked.
614 * The message must be a yes/no question.
616 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
618 public function add_confirm_action($confirmmessage) {
619 $this->add_action(new confirm_action($confirmmessage));
623 * Add action to the button.
624 * @param component_action $action
626 public function add_action(component_action $action) {
627 $this->actions[] = $action;
633 * Simple form with just one select field that gets submitted automatically.
635 * If JS not enabled small go button is printed too.
637 * @copyright 2009 Petr Skoda
638 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
639 * @since Moodle 2.0
640 * @package core
641 * @category output
643 class single_select implements renderable {
646 * @var moodle_url Target url - includes hidden fields
648 var $url;
651 * @var string Name of the select element.
653 var $name;
656 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
657 * it is also possible to specify optgroup as complex label array ex.:
658 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
659 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
661 var $options;
664 * @var string Selected option
666 var $selected;
669 * @var array Nothing selected
671 var $nothing;
674 * @var array Extra select field attributes
676 var $attributes = array();
679 * @var string Button label
681 var $label = '';
684 * @var array Button label's attributes
686 var $labelattributes = array();
689 * @var string Form submit method post or get
691 var $method = 'get';
694 * @var string Wrapping div class
696 var $class = 'singleselect';
699 * @var bool True if button disabled, false if normal
701 var $disabled = false;
704 * @var string Button tooltip
706 var $tooltip = null;
709 * @var string Form id
711 var $formid = null;
714 * @var array List of attached actions
716 var $helpicon = null;
719 * Constructor
720 * @param moodle_url $url form action target, includes hidden fields
721 * @param string $name name of selection field - the changing parameter in url
722 * @param array $options list of options
723 * @param string $selected selected element
724 * @param array $nothing
725 * @param string $formid
727 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
728 $this->url = $url;
729 $this->name = $name;
730 $this->options = $options;
731 $this->selected = $selected;
732 $this->nothing = $nothing;
733 $this->formid = $formid;
737 * Shortcut for adding a JS confirm dialog when the button is clicked.
738 * The message must be a yes/no question.
740 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
742 public function add_confirm_action($confirmmessage) {
743 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
747 * Add action to the button.
749 * @param component_action $action
751 public function add_action(component_action $action) {
752 $this->actions[] = $action;
756 * Adds help icon.
758 * @deprecated since Moodle 2.0
760 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
761 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
765 * Adds help icon.
767 * @param string $identifier The keyword that defines a help page
768 * @param string $component
770 public function set_help_icon($identifier, $component = 'moodle') {
771 $this->helpicon = new help_icon($identifier, $component);
775 * Sets select's label
777 * @param string $label
778 * @param array $attributes (optional)
780 public function set_label($label, $attributes = array()) {
781 $this->label = $label;
782 $this->labelattributes = $attributes;
788 * Simple URL selection widget description.
790 * @copyright 2009 Petr Skoda
791 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
792 * @since Moodle 2.0
793 * @package core
794 * @category output
796 class url_select implements renderable {
798 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
799 * it is also possible to specify optgroup as complex label array ex.:
800 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
801 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
803 var $urls;
806 * @var string Selected option
808 var $selected;
811 * @var array Nothing selected
813 var $nothing;
816 * @var array Extra select field attributes
818 var $attributes = array();
821 * @var string Button label
823 var $label = '';
826 * @var array Button label's attributes
828 var $labelattributes = array();
831 * @var string Wrapping div class
833 var $class = 'urlselect';
836 * @var bool True if button disabled, false if normal
838 var $disabled = false;
841 * @var string Button tooltip
843 var $tooltip = null;
846 * @var string Form id
848 var $formid = null;
851 * @var array List of attached actions
853 var $helpicon = null;
856 * @var string If set, makes button visible with given name for button
858 var $showbutton = null;
861 * Constructor
862 * @param array $urls list of options
863 * @param string $selected selected element
864 * @param array $nothing
865 * @param string $formid
866 * @param string $showbutton Set to text of button if it should be visible
867 * or null if it should be hidden (hidden version always has text 'go')
869 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
870 $this->urls = $urls;
871 $this->selected = $selected;
872 $this->nothing = $nothing;
873 $this->formid = $formid;
874 $this->showbutton = $showbutton;
878 * Adds help icon.
880 * @deprecated since Moodle 2.0
882 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
883 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
887 * Adds help icon.
889 * @param string $identifier The keyword that defines a help page
890 * @param string $component
892 public function set_help_icon($identifier, $component = 'moodle') {
893 $this->helpicon = new help_icon($identifier, $component);
897 * Sets select's label
899 * @param string $label
900 * @param array $attributes (optional)
902 public function set_label($label, $attributes = array()) {
903 $this->label = $label;
904 $this->labelattributes = $attributes;
909 * Data structure describing html link with special action attached.
911 * @copyright 2010 Petr Skoda
912 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
913 * @since Moodle 2.0
914 * @package core
915 * @category output
917 class action_link implements renderable {
920 * @var moodle_url Href url
922 public $url;
925 * @var string Link text HTML fragment
927 public $text;
930 * @var array HTML attributes
932 public $attributes;
935 * @var array List of actions attached to link
937 public $actions;
940 * @var pix_icon Optional pix icon to render with the link
942 public $icon;
945 * Constructor
946 * @param moodle_url $url
947 * @param string $text HTML fragment
948 * @param component_action $action
949 * @param array $attributes associative array of html link attributes + disabled
950 * @param pix_icon $icon optional pix_icon to render with the link text
952 public function __construct(moodle_url $url,
953 $text,
954 component_action $action=null,
955 array $attributes=null,
956 pix_icon $icon=null) {
957 $this->url = clone($url);
958 $this->text = $text;
959 $this->attributes = (array)$attributes;
960 if ($action) {
961 $this->add_action($action);
963 $this->icon = $icon;
967 * Add action to the link.
969 * @param component_action $action
971 public function add_action(component_action $action) {
972 $this->actions[] = $action;
976 * Adds a CSS class to this action link object
977 * @param string $class
979 public function add_class($class) {
980 if (empty($this->attributes['class'])) {
981 $this->attributes['class'] = $class;
982 } else {
983 $this->attributes['class'] .= ' ' . $class;
988 * Returns true if the specified class has been added to this link.
989 * @param string $class
990 * @return bool
992 public function has_class($class) {
993 return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
998 * Simple html output class
1000 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1001 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1002 * @since Moodle 2.0
1003 * @package core
1004 * @category output
1006 class html_writer {
1009 * Outputs a tag with attributes and contents
1011 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1012 * @param string $contents What goes between the opening and closing tags
1013 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1014 * @return string HTML fragment
1016 public static function tag($tagname, $contents, array $attributes = null) {
1017 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1021 * Outputs an opening tag with attributes
1023 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1024 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1025 * @return string HTML fragment
1027 public static function start_tag($tagname, array $attributes = null) {
1028 return '<' . $tagname . self::attributes($attributes) . '>';
1032 * Outputs a closing tag
1034 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1035 * @return string HTML fragment
1037 public static function end_tag($tagname) {
1038 return '</' . $tagname . '>';
1042 * Outputs an empty tag with attributes
1044 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1045 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1046 * @return string HTML fragment
1048 public static function empty_tag($tagname, array $attributes = null) {
1049 return '<' . $tagname . self::attributes($attributes) . ' />';
1053 * Outputs a tag, but only if the contents are not empty
1055 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1056 * @param string $contents What goes between the opening and closing tags
1057 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1058 * @return string HTML fragment
1060 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1061 if ($contents === '' || is_null($contents)) {
1062 return '';
1064 return self::tag($tagname, $contents, $attributes);
1068 * Outputs a HTML attribute and value
1070 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1071 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1072 * @return string HTML fragment
1074 public static function attribute($name, $value) {
1075 if ($value instanceof moodle_url) {
1076 return ' ' . $name . '="' . $value->out() . '"';
1079 // special case, we do not want these in output
1080 if ($value === null) {
1081 return '';
1084 // no sloppy trimming here!
1085 return ' ' . $name . '="' . s($value) . '"';
1089 * Outputs a list of HTML attributes and values
1091 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1092 * The values will be escaped with {@link s()}
1093 * @return string HTML fragment
1095 public static function attributes(array $attributes = null) {
1096 $attributes = (array)$attributes;
1097 $output = '';
1098 foreach ($attributes as $name => $value) {
1099 $output .= self::attribute($name, $value);
1101 return $output;
1105 * Generates random html element id.
1107 * @staticvar int $counter
1108 * @staticvar type $uniq
1109 * @param string $base A string fragment that will be included in the random ID.
1110 * @return string A unique ID
1112 public static function random_id($base='random') {
1113 static $counter = 0;
1114 static $uniq;
1116 if (!isset($uniq)) {
1117 $uniq = uniqid();
1120 $counter++;
1121 return $base.$uniq.$counter;
1125 * Generates a simple html link
1127 * @param string|moodle_url $url The URL
1128 * @param string $text The text
1129 * @param array $attributes HTML attributes
1130 * @return string HTML fragment
1132 public static function link($url, $text, array $attributes = null) {
1133 $attributes = (array)$attributes;
1134 $attributes['href'] = $url;
1135 return self::tag('a', $text, $attributes);
1139 * Generates a simple checkbox with optional label
1141 * @param string $name The name of the checkbox
1142 * @param string $value The value of the checkbox
1143 * @param bool $checked Whether the checkbox is checked
1144 * @param string $label The label for the checkbox
1145 * @param array $attributes Any attributes to apply to the checkbox
1146 * @return string html fragment
1148 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1149 $attributes = (array)$attributes;
1150 $output = '';
1152 if ($label !== '' and !is_null($label)) {
1153 if (empty($attributes['id'])) {
1154 $attributes['id'] = self::random_id('checkbox_');
1157 $attributes['type'] = 'checkbox';
1158 $attributes['value'] = $value;
1159 $attributes['name'] = $name;
1160 $attributes['checked'] = $checked ? 'checked' : null;
1162 $output .= self::empty_tag('input', $attributes);
1164 if ($label !== '' and !is_null($label)) {
1165 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1168 return $output;
1172 * Generates a simple select yes/no form field
1174 * @param string $name name of select element
1175 * @param bool $selected
1176 * @param array $attributes - html select element attributes
1177 * @return string HTML fragment
1179 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1180 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1181 return self::select($options, $name, $selected, null, $attributes);
1185 * Generates a simple select form field
1187 * @param array $options associative array value=>label ex.:
1188 * array(1=>'One, 2=>Two)
1189 * it is also possible to specify optgroup as complex label array ex.:
1190 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1191 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1192 * @param string $name name of select element
1193 * @param string|array $selected value or array of values depending on multiple attribute
1194 * @param array|bool $nothing add nothing selected option, or false of not added
1195 * @param array $attributes html select element attributes
1196 * @return string HTML fragment
1198 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1199 $attributes = (array)$attributes;
1200 if (is_array($nothing)) {
1201 foreach ($nothing as $k=>$v) {
1202 if ($v === 'choose' or $v === 'choosedots') {
1203 $nothing[$k] = get_string('choosedots');
1206 $options = $nothing + $options; // keep keys, do not override
1208 } else if (is_string($nothing) and $nothing !== '') {
1209 // BC
1210 $options = array(''=>$nothing) + $options;
1213 // we may accept more values if multiple attribute specified
1214 $selected = (array)$selected;
1215 foreach ($selected as $k=>$v) {
1216 $selected[$k] = (string)$v;
1219 if (!isset($attributes['id'])) {
1220 $id = 'menu'.$name;
1221 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1222 $id = str_replace('[', '', $id);
1223 $id = str_replace(']', '', $id);
1224 $attributes['id'] = $id;
1227 if (!isset($attributes['class'])) {
1228 $class = 'menu'.$name;
1229 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1230 $class = str_replace('[', '', $class);
1231 $class = str_replace(']', '', $class);
1232 $attributes['class'] = $class;
1234 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
1236 $attributes['name'] = $name;
1238 if (!empty($attributes['disabled'])) {
1239 $attributes['disabled'] = 'disabled';
1240 } else {
1241 unset($attributes['disabled']);
1244 $output = '';
1245 foreach ($options as $value=>$label) {
1246 if (is_array($label)) {
1247 // ignore key, it just has to be unique
1248 $output .= self::select_optgroup(key($label), current($label), $selected);
1249 } else {
1250 $output .= self::select_option($label, $value, $selected);
1253 return self::tag('select', $output, $attributes);
1257 * Returns HTML to display a select box option.
1259 * @param string $label The label to display as the option.
1260 * @param string|int $value The value the option represents
1261 * @param array $selected An array of selected options
1262 * @return string HTML fragment
1264 private static function select_option($label, $value, array $selected) {
1265 $attributes = array();
1266 $value = (string)$value;
1267 if (in_array($value, $selected, true)) {
1268 $attributes['selected'] = 'selected';
1270 $attributes['value'] = $value;
1271 return self::tag('option', $label, $attributes);
1275 * Returns HTML to display a select box option group.
1277 * @param string $groupname The label to use for the group
1278 * @param array $options The options in the group
1279 * @param array $selected An array of selected values.
1280 * @return string HTML fragment.
1282 private static function select_optgroup($groupname, $options, array $selected) {
1283 if (empty($options)) {
1284 return '';
1286 $attributes = array('label'=>$groupname);
1287 $output = '';
1288 foreach ($options as $value=>$label) {
1289 $output .= self::select_option($label, $value, $selected);
1291 return self::tag('optgroup', $output, $attributes);
1295 * This is a shortcut for making an hour selector menu.
1297 * @param string $type The type of selector (years, months, days, hours, minutes)
1298 * @param string $name fieldname
1299 * @param int $currenttime A default timestamp in GMT
1300 * @param int $step minute spacing
1301 * @param array $attributes - html select element attributes
1302 * @return HTML fragment
1304 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1305 if (!$currenttime) {
1306 $currenttime = time();
1308 $currentdate = usergetdate($currenttime);
1309 $userdatetype = $type;
1310 $timeunits = array();
1312 switch ($type) {
1313 case 'years':
1314 for ($i=1970; $i<=2020; $i++) {
1315 $timeunits[$i] = $i;
1317 $userdatetype = 'year';
1318 break;
1319 case 'months':
1320 for ($i=1; $i<=12; $i++) {
1321 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1323 $userdatetype = 'month';
1324 $currentdate['month'] = (int)$currentdate['mon'];
1325 break;
1326 case 'days':
1327 for ($i=1; $i<=31; $i++) {
1328 $timeunits[$i] = $i;
1330 $userdatetype = 'mday';
1331 break;
1332 case 'hours':
1333 for ($i=0; $i<=23; $i++) {
1334 $timeunits[$i] = sprintf("%02d",$i);
1336 break;
1337 case 'minutes':
1338 if ($step != 1) {
1339 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1342 for ($i=0; $i<=59; $i+=$step) {
1343 $timeunits[$i] = sprintf("%02d",$i);
1345 break;
1346 default:
1347 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1350 if (empty($attributes['id'])) {
1351 $attributes['id'] = self::random_id('ts_');
1353 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, array('id'=>$attributes['id']));
1354 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1356 return $label.$timerselector;
1360 * Shortcut for quick making of lists
1362 * Note: 'list' is a reserved keyword ;-)
1364 * @param array $items
1365 * @param array $attributes
1366 * @param string $tag ul or ol
1367 * @return string
1369 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1370 $output = html_writer::start_tag($tag, $attributes)."\n";
1371 foreach ($items as $item) {
1372 $output .= html_writer::tag('li', $item)."\n";
1374 $output .= html_writer::end_tag($tag);
1375 return $output;
1379 * Returns hidden input fields created from url parameters.
1381 * @param moodle_url $url
1382 * @param array $exclude list of excluded parameters
1383 * @return string HTML fragment
1385 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1386 $exclude = (array)$exclude;
1387 $params = $url->params();
1388 foreach ($exclude as $key) {
1389 unset($params[$key]);
1392 $output = '';
1393 foreach ($params as $key => $value) {
1394 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1395 $output .= self::empty_tag('input', $attributes)."\n";
1397 return $output;
1401 * Generate a script tag containing the the specified code.
1403 * @param string $jscode the JavaScript code
1404 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
1405 * @return string HTML, the code wrapped in <script> tags.
1407 public static function script($jscode, $url=null) {
1408 if ($jscode) {
1409 $attributes = array('type'=>'text/javascript');
1410 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1412 } else if ($url) {
1413 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1414 return self::tag('script', '', $attributes) . "\n";
1416 } else {
1417 return '';
1422 * Renders HTML table
1424 * This method may modify the passed instance by adding some default properties if they are not set yet.
1425 * If this is not what you want, you should make a full clone of your data before passing them to this
1426 * method. In most cases this is not an issue at all so we do not clone by default for performance
1427 * and memory consumption reasons.
1429 * @param html_table $table data to be rendered
1430 * @return string HTML code
1432 public static function table(html_table $table) {
1433 // prepare table data and populate missing properties with reasonable defaults
1434 if (!empty($table->align)) {
1435 foreach ($table->align as $key => $aa) {
1436 if ($aa) {
1437 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1438 } else {
1439 $table->align[$key] = null;
1443 if (!empty($table->size)) {
1444 foreach ($table->size as $key => $ss) {
1445 if ($ss) {
1446 $table->size[$key] = 'width:'. $ss .';';
1447 } else {
1448 $table->size[$key] = null;
1452 if (!empty($table->wrap)) {
1453 foreach ($table->wrap as $key => $ww) {
1454 if ($ww) {
1455 $table->wrap[$key] = 'white-space:nowrap;';
1456 } else {
1457 $table->wrap[$key] = '';
1461 if (!empty($table->head)) {
1462 foreach ($table->head as $key => $val) {
1463 if (!isset($table->align[$key])) {
1464 $table->align[$key] = null;
1466 if (!isset($table->size[$key])) {
1467 $table->size[$key] = null;
1469 if (!isset($table->wrap[$key])) {
1470 $table->wrap[$key] = null;
1475 if (empty($table->attributes['class'])) {
1476 $table->attributes['class'] = 'generaltable';
1478 if (!empty($table->tablealign)) {
1479 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1482 // explicitly assigned properties override those defined via $table->attributes
1483 $table->attributes['class'] = trim($table->attributes['class']);
1484 $attributes = array_merge($table->attributes, array(
1485 'id' => $table->id,
1486 'width' => $table->width,
1487 'summary' => $table->summary,
1488 'cellpadding' => $table->cellpadding,
1489 'cellspacing' => $table->cellspacing,
1491 $output = html_writer::start_tag('table', $attributes) . "\n";
1493 $countcols = 0;
1495 if (!empty($table->head)) {
1496 $countcols = count($table->head);
1498 $output .= html_writer::start_tag('thead', array()) . "\n";
1499 $output .= html_writer::start_tag('tr', array()) . "\n";
1500 $keys = array_keys($table->head);
1501 $lastkey = end($keys);
1503 foreach ($table->head as $key => $heading) {
1504 // Convert plain string headings into html_table_cell objects
1505 if (!($heading instanceof html_table_cell)) {
1506 $headingtext = $heading;
1507 $heading = new html_table_cell();
1508 $heading->text = $headingtext;
1509 $heading->header = true;
1512 if ($heading->header !== false) {
1513 $heading->header = true;
1516 if ($heading->header && empty($heading->scope)) {
1517 $heading->scope = 'col';
1520 $heading->attributes['class'] .= ' header c' . $key;
1521 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1522 $heading->colspan = $table->headspan[$key];
1523 $countcols += $table->headspan[$key] - 1;
1526 if ($key == $lastkey) {
1527 $heading->attributes['class'] .= ' lastcol';
1529 if (isset($table->colclasses[$key])) {
1530 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1532 $heading->attributes['class'] = trim($heading->attributes['class']);
1533 $attributes = array_merge($heading->attributes, array(
1534 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1535 'scope' => $heading->scope,
1536 'colspan' => $heading->colspan,
1539 $tagtype = 'td';
1540 if ($heading->header === true) {
1541 $tagtype = 'th';
1543 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1545 $output .= html_writer::end_tag('tr') . "\n";
1546 $output .= html_writer::end_tag('thead') . "\n";
1548 if (empty($table->data)) {
1549 // For valid XHTML strict every table must contain either a valid tr
1550 // or a valid tbody... both of which must contain a valid td
1551 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1552 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1553 $output .= html_writer::end_tag('tbody');
1557 if (!empty($table->data)) {
1558 $oddeven = 1;
1559 $keys = array_keys($table->data);
1560 $lastrowkey = end($keys);
1561 $output .= html_writer::start_tag('tbody', array());
1563 foreach ($table->data as $key => $row) {
1564 if (($row === 'hr') && ($countcols)) {
1565 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1566 } else {
1567 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1568 if (!($row instanceof html_table_row)) {
1569 $newrow = new html_table_row();
1571 foreach ($row as $cell) {
1572 if (!($cell instanceof html_table_cell)) {
1573 $cell = new html_table_cell($cell);
1575 $newrow->cells[] = $cell;
1577 $row = $newrow;
1580 $oddeven = $oddeven ? 0 : 1;
1581 if (isset($table->rowclasses[$key])) {
1582 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1585 $row->attributes['class'] .= ' r' . $oddeven;
1586 if ($key == $lastrowkey) {
1587 $row->attributes['class'] .= ' lastrow';
1590 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1591 $keys2 = array_keys($row->cells);
1592 $lastkey = end($keys2);
1594 $gotlastkey = false; //flag for sanity checking
1595 foreach ($row->cells as $key => $cell) {
1596 if ($gotlastkey) {
1597 //This should never happen. Why do we have a cell after the last cell?
1598 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1601 if (!($cell instanceof html_table_cell)) {
1602 $mycell = new html_table_cell();
1603 $mycell->text = $cell;
1604 $cell = $mycell;
1607 if (($cell->header === true) && empty($cell->scope)) {
1608 $cell->scope = 'row';
1611 if (isset($table->colclasses[$key])) {
1612 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1615 $cell->attributes['class'] .= ' cell c' . $key;
1616 if ($key == $lastkey) {
1617 $cell->attributes['class'] .= ' lastcol';
1618 $gotlastkey = true;
1620 $tdstyle = '';
1621 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1622 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1623 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1624 $cell->attributes['class'] = trim($cell->attributes['class']);
1625 $tdattributes = array_merge($cell->attributes, array(
1626 'style' => $tdstyle . $cell->style,
1627 'colspan' => $cell->colspan,
1628 'rowspan' => $cell->rowspan,
1629 'id' => $cell->id,
1630 'abbr' => $cell->abbr,
1631 'scope' => $cell->scope,
1633 $tagtype = 'td';
1634 if ($cell->header === true) {
1635 $tagtype = 'th';
1637 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1640 $output .= html_writer::end_tag('tr') . "\n";
1642 $output .= html_writer::end_tag('tbody') . "\n";
1644 $output .= html_writer::end_tag('table') . "\n";
1646 return $output;
1650 * Renders form element label
1652 * By default, the label is suffixed with a label separator defined in the
1653 * current language pack (colon by default in the English lang pack).
1654 * Adding the colon can be explicitly disabled if needed. Label separators
1655 * are put outside the label tag itself so they are not read by
1656 * screenreaders (accessibility).
1658 * Parameter $for explicitly associates the label with a form control. When
1659 * set, the value of this attribute must be the same as the value of
1660 * the id attribute of the form control in the same document. When null,
1661 * the label being defined is associated with the control inside the label
1662 * element.
1664 * @param string $text content of the label tag
1665 * @param string|null $for id of the element this label is associated with, null for no association
1666 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1667 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1668 * @return string HTML of the label element
1670 public static function label($text, $for, $colonize = true, array $attributes=array()) {
1671 if (!is_null($for)) {
1672 $attributes = array_merge($attributes, array('for' => $for));
1674 $text = trim($text);
1675 $label = self::tag('label', $text, $attributes);
1677 // TODO MDL-12192 $colonize disabled for now yet
1678 // if (!empty($text) and $colonize) {
1679 // // the $text may end with the colon already, though it is bad string definition style
1680 // $colon = get_string('labelsep', 'langconfig');
1681 // if (!empty($colon)) {
1682 // $trimmed = trim($colon);
1683 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1684 // //debugging('The label text should not end with colon or other label separator,
1685 // // please fix the string definition.', DEBUG_DEVELOPER);
1686 // } else {
1687 // $label .= $colon;
1688 // }
1689 // }
1690 // }
1692 return $label;
1696 * Combines a class parameter with other attributes. Aids in code reduction
1697 * because the class parameter is very frequently used.
1699 * If the class attribute is specified both in the attributes and in the
1700 * class parameter, the two values are combined with a space between.
1702 * @param string $class Optional CSS class (or classes as space-separated list)
1703 * @param array $attributes Optional other attributes as array
1704 * @return array Attributes (or null if still none)
1706 private static function add_class($class = '', array $attributes = null) {
1707 if ($class !== '') {
1708 $classattribute = array('class' => $class);
1709 if ($attributes) {
1710 if (array_key_exists('class', $attributes)) {
1711 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
1712 } else {
1713 $attributes = $classattribute + $attributes;
1715 } else {
1716 $attributes = $classattribute;
1719 return $attributes;
1723 * Creates a <div> tag. (Shortcut function.)
1725 * @param string $content HTML content of tag
1726 * @param string $class Optional CSS class (or classes as space-separated list)
1727 * @param array $attributes Optional other attributes as array
1728 * @return string HTML code for div
1730 public static function div($content, $class = '', array $attributes = null) {
1731 return self::tag('div', $content, self::add_class($class, $attributes));
1735 * Starts a <div> tag. (Shortcut function.)
1737 * @param string $class Optional CSS class (or classes as space-separated list)
1738 * @param array $attributes Optional other attributes as array
1739 * @return string HTML code for open div tag
1741 public static function start_div($class = '', array $attributes = null) {
1742 return self::start_tag('div', self::add_class($class, $attributes));
1746 * Ends a <div> tag. (Shortcut function.)
1748 * @return string HTML code for close div tag
1750 public static function end_div() {
1751 return self::end_tag('div');
1755 * Creates a <span> tag. (Shortcut function.)
1757 * @param string $content HTML content of tag
1758 * @param string $class Optional CSS class (or classes as space-separated list)
1759 * @param array $attributes Optional other attributes as array
1760 * @return string HTML code for span
1762 public static function span($content, $class = '', array $attributes = null) {
1763 return self::tag('span', $content, self::add_class($class, $attributes));
1767 * Starts a <span> tag. (Shortcut function.)
1769 * @param string $class Optional CSS class (or classes as space-separated list)
1770 * @param array $attributes Optional other attributes as array
1771 * @return string HTML code for open span tag
1773 public static function start_span($class = '', array $attributes = null) {
1774 return self::start_tag('span', self::add_class($class, $attributes));
1778 * Ends a <span> tag. (Shortcut function.)
1780 * @return string HTML code for close span tag
1782 public static function end_span() {
1783 return self::end_tag('span');
1788 * Simple javascript output class
1790 * @copyright 2010 Petr Skoda
1791 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1792 * @since Moodle 2.0
1793 * @package core
1794 * @category output
1796 class js_writer {
1799 * Returns javascript code calling the function
1801 * @param string $function function name, can be complex like Y.Event.purgeElement
1802 * @param array $arguments parameters
1803 * @param int $delay execution delay in seconds
1804 * @return string JS code fragment
1806 public static function function_call($function, array $arguments = null, $delay=0) {
1807 if ($arguments) {
1808 $arguments = array_map('json_encode', convert_to_array($arguments));
1809 $arguments = implode(', ', $arguments);
1810 } else {
1811 $arguments = '';
1813 $js = "$function($arguments);";
1815 if ($delay) {
1816 $delay = $delay * 1000; // in miliseconds
1817 $js = "setTimeout(function() { $js }, $delay);";
1819 return $js . "\n";
1823 * Special function which adds Y as first argument of function call.
1825 * @param string $function The function to call
1826 * @param array $extraarguments Any arguments to pass to it
1827 * @return string Some JS code
1829 public static function function_call_with_Y($function, array $extraarguments = null) {
1830 if ($extraarguments) {
1831 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1832 $arguments = 'Y, ' . implode(', ', $extraarguments);
1833 } else {
1834 $arguments = 'Y';
1836 return "$function($arguments);\n";
1840 * Returns JavaScript code to initialise a new object
1842 * @param string $var If it is null then no var is assigned the new object.
1843 * @param string $class The class to initialise an object for.
1844 * @param array $arguments An array of args to pass to the init method.
1845 * @param array $requirements Any modules required for this class.
1846 * @param int $delay The delay before initialisation. 0 = no delay.
1847 * @return string Some JS code
1849 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1850 if (is_array($arguments)) {
1851 $arguments = array_map('json_encode', convert_to_array($arguments));
1852 $arguments = implode(', ', $arguments);
1855 if ($var === null) {
1856 $js = "new $class(Y, $arguments);";
1857 } else if (strpos($var, '.')!==false) {
1858 $js = "$var = new $class(Y, $arguments);";
1859 } else {
1860 $js = "var $var = new $class(Y, $arguments);";
1863 if ($delay) {
1864 $delay = $delay * 1000; // in miliseconds
1865 $js = "setTimeout(function() { $js }, $delay);";
1868 if (count($requirements) > 0) {
1869 $requirements = implode("', '", $requirements);
1870 $js = "Y.use('$requirements', function(Y){ $js });";
1872 return $js."\n";
1876 * Returns code setting value to variable
1878 * @param string $name
1879 * @param mixed $value json serialised value
1880 * @param bool $usevar add var definition, ignored for nested properties
1881 * @return string JS code fragment
1883 public static function set_variable($name, $value, $usevar = true) {
1884 $output = '';
1886 if ($usevar) {
1887 if (strpos($name, '.')) {
1888 $output .= '';
1889 } else {
1890 $output .= 'var ';
1894 $output .= "$name = ".json_encode($value).";";
1896 return $output;
1900 * Writes event handler attaching code
1902 * @param array|string $selector standard YUI selector for elements, may be
1903 * array or string, element id is in the form "#idvalue"
1904 * @param string $event A valid DOM event (click, mousedown, change etc.)
1905 * @param string $function The name of the function to call
1906 * @param array $arguments An optional array of argument parameters to pass to the function
1907 * @return string JS code fragment
1909 public static function event_handler($selector, $event, $function, array $arguments = null) {
1910 $selector = json_encode($selector);
1911 $output = "Y.on('$event', $function, $selector, null";
1912 if (!empty($arguments)) {
1913 $output .= ', ' . json_encode($arguments);
1915 return $output . ");\n";
1920 * Holds all the information required to render a <table> by {@link core_renderer::table()}
1922 * Example of usage:
1923 * $t = new html_table();
1924 * ... // set various properties of the object $t as described below
1925 * echo html_writer::table($t);
1927 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1928 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1929 * @since Moodle 2.0
1930 * @package core
1931 * @category output
1933 class html_table {
1936 * @var string Value to use for the id attribute of the table
1938 public $id = null;
1941 * @var array Attributes of HTML attributes for the <table> element
1943 public $attributes = array();
1946 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
1947 * For more control over the rendering of the headers, an array of html_table_cell objects
1948 * can be passed instead of an array of strings.
1950 * Example of usage:
1951 * $t->head = array('Student', 'Grade');
1953 public $head;
1956 * @var array An array that can be used to make a heading span multiple columns.
1957 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1958 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
1960 * Example of usage:
1961 * $t->headspan = array(2,1);
1963 public $headspan;
1966 * @var array An array of column alignments.
1967 * The value is used as CSS 'text-align' property. Therefore, possible
1968 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1969 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1971 * Examples of usage:
1972 * $t->align = array(null, 'right');
1973 * or
1974 * $t->align[1] = 'right';
1976 public $align;
1979 * @var array The value is used as CSS 'size' property.
1981 * Examples of usage:
1982 * $t->size = array('50%', '50%');
1983 * or
1984 * $t->size[1] = '120px';
1986 public $size;
1989 * @var array An array of wrapping information.
1990 * The only possible value is 'nowrap' that sets the
1991 * CSS property 'white-space' to the value 'nowrap' in the given column.
1993 * Example of usage:
1994 * $t->wrap = array(null, 'nowrap');
1996 public $wrap;
1999 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2000 * $head specified, the string 'hr' (for horizontal ruler) can be used
2001 * instead of an array of cells data resulting in a divider rendered.
2003 * Example of usage with array of arrays:
2004 * $row1 = array('Harry Potter', '76 %');
2005 * $row2 = array('Hermione Granger', '100 %');
2006 * $t->data = array($row1, $row2);
2008 * Example with array of html_table_row objects: (used for more fine-grained control)
2009 * $cell1 = new html_table_cell();
2010 * $cell1->text = 'Harry Potter';
2011 * $cell1->colspan = 2;
2012 * $row1 = new html_table_row();
2013 * $row1->cells[] = $cell1;
2014 * $cell2 = new html_table_cell();
2015 * $cell2->text = 'Hermione Granger';
2016 * $cell3 = new html_table_cell();
2017 * $cell3->text = '100 %';
2018 * $row2 = new html_table_row();
2019 * $row2->cells = array($cell2, $cell3);
2020 * $t->data = array($row1, $row2);
2022 public $data;
2025 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2026 * @var string Width of the table, percentage of the page preferred.
2028 public $width = null;
2031 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2032 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2034 public $tablealign = null;
2037 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2038 * @var int Padding on each cell, in pixels
2040 public $cellpadding = null;
2043 * @var int Spacing between cells, in pixels
2044 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2046 public $cellspacing = null;
2049 * @var array Array of classes to add to particular rows, space-separated string.
2050 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
2051 * respectively. Class 'lastrow' is added automatically for the last row
2052 * in the table.
2054 * Example of usage:
2055 * $t->rowclasses[9] = 'tenth'
2057 public $rowclasses;
2060 * @var array An array of classes to add to every cell in a particular column,
2061 * space-separated string. Class 'cell' is added automatically by the renderer.
2062 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2063 * respectively. Class 'lastcol' is added automatically for all last cells
2064 * in a row.
2066 * Example of usage:
2067 * $t->colclasses = array(null, 'grade');
2069 public $colclasses;
2072 * @var string Description of the contents for screen readers.
2074 public $summary;
2077 * Constructor
2079 public function __construct() {
2080 $this->attributes['class'] = '';
2085 * Component representing a table row.
2087 * @copyright 2009 Nicolas Connault
2088 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2089 * @since Moodle 2.0
2090 * @package core
2091 * @category output
2093 class html_table_row {
2096 * @var string Value to use for the id attribute of the row.
2098 public $id = null;
2101 * @var array Array of html_table_cell objects
2103 public $cells = array();
2106 * @var string Value to use for the style attribute of the table row
2108 public $style = null;
2111 * @var array Attributes of additional HTML attributes for the <tr> element
2113 public $attributes = array();
2116 * Constructor
2117 * @param array $cells
2119 public function __construct(array $cells=null) {
2120 $this->attributes['class'] = '';
2121 $cells = (array)$cells;
2122 foreach ($cells as $cell) {
2123 if ($cell instanceof html_table_cell) {
2124 $this->cells[] = $cell;
2125 } else {
2126 $this->cells[] = new html_table_cell($cell);
2133 * Component representing a table cell.
2135 * @copyright 2009 Nicolas Connault
2136 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2137 * @since Moodle 2.0
2138 * @package core
2139 * @category output
2141 class html_table_cell {
2144 * @var string Value to use for the id attribute of the cell.
2146 public $id = null;
2149 * @var string The contents of the cell.
2151 public $text;
2154 * @var string Abbreviated version of the contents of the cell.
2156 public $abbr = null;
2159 * @var int Number of columns this cell should span.
2161 public $colspan = null;
2164 * @var int Number of rows this cell should span.
2166 public $rowspan = null;
2169 * @var string Defines a way to associate header cells and data cells in a table.
2171 public $scope = null;
2174 * @var bool Whether or not this cell is a header cell.
2176 public $header = null;
2179 * @var string Value to use for the style attribute of the table cell
2181 public $style = null;
2184 * @var array Attributes of additional HTML attributes for the <td> element
2186 public $attributes = array();
2189 * Constructs a table cell
2191 * @param string $text
2193 public function __construct($text = null) {
2194 $this->text = $text;
2195 $this->attributes['class'] = '';
2200 * Component representing a paging bar.
2202 * @copyright 2009 Nicolas Connault
2203 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2204 * @since Moodle 2.0
2205 * @package core
2206 * @category output
2208 class paging_bar implements renderable {
2211 * @var int The maximum number of pagelinks to display.
2213 public $maxdisplay = 18;
2216 * @var int The total number of entries to be pages through..
2218 public $totalcount;
2221 * @var int The page you are currently viewing.
2223 public $page;
2226 * @var int The number of entries that should be shown per page.
2228 public $perpage;
2231 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2232 * an equals sign and the page number.
2233 * If this is a moodle_url object then the pagevar param will be replaced by
2234 * the page no, for each page.
2236 public $baseurl;
2239 * @var string This is the variable name that you use for the pagenumber in your
2240 * code (ie. 'tablepage', 'blogpage', etc)
2242 public $pagevar;
2245 * @var string A HTML link representing the "previous" page.
2247 public $previouslink = null;
2250 * @var string A HTML link representing the "next" page.
2252 public $nextlink = null;
2255 * @var string A HTML link representing the first page.
2257 public $firstlink = null;
2260 * @var string A HTML link representing the last page.
2262 public $lastlink = null;
2265 * @var array An array of strings. One of them is just a string: the current page
2267 public $pagelinks = array();
2270 * Constructor paging_bar with only the required params.
2272 * @param int $totalcount The total number of entries available to be paged through
2273 * @param int $page The page you are currently viewing
2274 * @param int $perpage The number of entries that should be shown per page
2275 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2276 * @param string $pagevar name of page parameter that holds the page number
2278 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2279 $this->totalcount = $totalcount;
2280 $this->page = $page;
2281 $this->perpage = $perpage;
2282 $this->baseurl = $baseurl;
2283 $this->pagevar = $pagevar;
2287 * Prepares the paging bar for output.
2289 * This method validates the arguments set up for the paging bar and then
2290 * produces fragments of HTML to assist display later on.
2292 * @param renderer_base $output
2293 * @param moodle_page $page
2294 * @param string $target
2295 * @throws coding_exception
2297 public function prepare(renderer_base $output, moodle_page $page, $target) {
2298 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2299 throw new coding_exception('paging_bar requires a totalcount value.');
2301 if (!isset($this->page) || is_null($this->page)) {
2302 throw new coding_exception('paging_bar requires a page value.');
2304 if (empty($this->perpage)) {
2305 throw new coding_exception('paging_bar requires a perpage value.');
2307 if (empty($this->baseurl)) {
2308 throw new coding_exception('paging_bar requires a baseurl value.');
2311 if ($this->totalcount > $this->perpage) {
2312 $pagenum = $this->page - 1;
2314 if ($this->page > 0) {
2315 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2318 if ($this->perpage > 0) {
2319 $lastpage = ceil($this->totalcount / $this->perpage);
2320 } else {
2321 $lastpage = 1;
2324 if ($this->page > round(($this->maxdisplay/3)*2)) {
2325 $currpage = $this->page - round($this->maxdisplay/3);
2327 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2328 } else {
2329 $currpage = 0;
2332 $displaycount = $displaypage = 0;
2334 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2335 $displaypage = $currpage + 1;
2337 if ($this->page == $currpage) {
2338 $this->pagelinks[] = $displaypage;
2339 } else {
2340 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2341 $this->pagelinks[] = $pagelink;
2344 $displaycount++;
2345 $currpage++;
2348 if ($currpage < $lastpage) {
2349 $lastpageactual = $lastpage - 1;
2350 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2353 $pagenum = $this->page + 1;
2355 if ($pagenum != $displaypage) {
2356 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2363 * This class represents how a block appears on a page.
2365 * During output, each block instance is asked to return a block_contents object,
2366 * those are then passed to the $OUTPUT->block function for display.
2368 * contents should probably be generated using a moodle_block_..._renderer.
2370 * Other block-like things that need to appear on the page, for example the
2371 * add new block UI, are also represented as block_contents objects.
2373 * @copyright 2009 Tim Hunt
2374 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2375 * @since Moodle 2.0
2376 * @package core
2377 * @category output
2379 class block_contents {
2381 /** Used when the block cannot be collapsed **/
2382 const NOT_HIDEABLE = 0;
2384 /** Used when the block can be collapsed but currently is not **/
2385 const VISIBLE = 1;
2387 /** Used when the block has been collapsed **/
2388 const HIDDEN = 2;
2391 * @var int Used to set $skipid.
2393 protected static $idcounter = 1;
2396 * @var int All the blocks (or things that look like blocks) printed on
2397 * a page are given a unique number that can be used to construct id="" attributes.
2398 * This is set automatically be the {@link prepare()} method.
2399 * Do not try to set it manually.
2401 public $skipid;
2404 * @var int If this is the contents of a real block, this should be set
2405 * to the block_instance.id. Otherwise this should be set to 0.
2407 public $blockinstanceid = 0;
2410 * @var int If this is a real block instance, and there is a corresponding
2411 * block_position.id for the block on this page, this should be set to that id.
2412 * Otherwise it should be 0.
2414 public $blockpositionid = 0;
2417 * @var array An array of attribute => value pairs that are put on the outer div of this
2418 * block. {@link $id} and {@link $classes} attributes should be set separately.
2420 public $attributes;
2423 * @var string The title of this block. If this came from user input, it should already
2424 * have had format_string() processing done on it. This will be output inside
2425 * <h2> tags. Please do not cause invalid XHTML.
2427 public $title = '';
2430 * @var string The label to use when the block does not, or will not have a visible title.
2431 * You should never set this as well as title... it will just be ignored.
2433 public $arialabel = '';
2436 * @var string HTML for the content
2438 public $content = '';
2441 * @var array An alternative to $content, it you want a list of things with optional icons.
2443 public $footer = '';
2446 * @var string Any small print that should appear under the block to explain
2447 * to the teacher about the block, for example 'This is a sticky block that was
2448 * added in the system context.'
2450 public $annotation = '';
2453 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2454 * the user can toggle whether this block is visible.
2456 public $collapsible = self::NOT_HIDEABLE;
2459 * Set this to true if the block is dockable.
2460 * @var bool
2462 public $dockable = false;
2465 * @var array A (possibly empty) array of editing controls. Each element of
2466 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2467 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2469 public $controls = array();
2473 * Create new instance of block content
2474 * @param array $attributes
2476 public function __construct(array $attributes = null) {
2477 $this->skipid = self::$idcounter;
2478 self::$idcounter += 1;
2480 if ($attributes) {
2481 // standard block
2482 $this->attributes = $attributes;
2483 } else {
2484 // simple "fake" blocks used in some modules and "Add new block" block
2485 $this->attributes = array('class'=>'block');
2490 * Add html class to block
2492 * @param string $class
2494 public function add_class($class) {
2495 $this->attributes['class'] .= ' '.$class;
2501 * This class represents a target for where a block can go when it is being moved.
2503 * This needs to be rendered as a form with the given hidden from fields, and
2504 * clicking anywhere in the form should submit it. The form action should be
2505 * $PAGE->url.
2507 * @copyright 2009 Tim Hunt
2508 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2509 * @since Moodle 2.0
2510 * @package core
2511 * @category output
2513 class block_move_target {
2516 * @var moodle_url Move url
2518 public $url;
2521 * Constructor
2522 * @param moodle_url $url
2524 public function __construct(moodle_url $url) {
2525 $this->url = $url;
2530 * Custom menu item
2532 * This class is used to represent one item within a custom menu that may or may
2533 * not have children.
2535 * @copyright 2010 Sam Hemelryk
2536 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2537 * @since Moodle 2.0
2538 * @package core
2539 * @category output
2541 class custom_menu_item implements renderable {
2544 * @var string The text to show for the item
2546 protected $text;
2549 * @var moodle_url The link to give the icon if it has no children
2551 protected $url;
2554 * @var string A title to apply to the item. By default the text
2556 protected $title;
2559 * @var int A sort order for the item, not necessary if you order things in
2560 * the CFG var.
2562 protected $sort;
2565 * @var custom_menu_item A reference to the parent for this item or NULL if
2566 * it is a top level item
2568 protected $parent;
2571 * @var array A array in which to store children this item has.
2573 protected $children = array();
2576 * @var int A reference to the sort var of the last child that was added
2578 protected $lastsort = 0;
2581 * Constructs the new custom menu item
2583 * @param string $text
2584 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2585 * @param string $title A title to apply to this item [Optional]
2586 * @param int $sort A sort or to use if we need to sort differently [Optional]
2587 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2588 * belongs to, only if the child has a parent. [Optional]
2590 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
2591 $this->text = $text;
2592 $this->url = $url;
2593 $this->title = $title;
2594 $this->sort = (int)$sort;
2595 $this->parent = $parent;
2599 * Adds a custom menu item as a child of this node given its properties.
2601 * @param string $text
2602 * @param moodle_url $url
2603 * @param string $title
2604 * @param int $sort
2605 * @return custom_menu_item
2607 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
2608 $key = count($this->children);
2609 if (empty($sort)) {
2610 $sort = $this->lastsort + 1;
2612 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2613 $this->lastsort = (int)$sort;
2614 return $this->children[$key];
2618 * Returns the text for this item
2619 * @return string
2621 public function get_text() {
2622 return $this->text;
2626 * Returns the url for this item
2627 * @return moodle_url
2629 public function get_url() {
2630 return $this->url;
2634 * Returns the title for this item
2635 * @return string
2637 public function get_title() {
2638 return $this->title;
2642 * Sorts and returns the children for this item
2643 * @return array
2645 public function get_children() {
2646 $this->sort();
2647 return $this->children;
2651 * Gets the sort order for this child
2652 * @return int
2654 public function get_sort_order() {
2655 return $this->sort;
2659 * Gets the parent this child belong to
2660 * @return custom_menu_item
2662 public function get_parent() {
2663 return $this->parent;
2667 * Sorts the children this item has
2669 public function sort() {
2670 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2674 * Returns true if this item has any children
2675 * @return bool
2677 public function has_children() {
2678 return (count($this->children) > 0);
2682 * Sets the text for the node
2683 * @param string $text
2685 public function set_text($text) {
2686 $this->text = (string)$text;
2690 * Sets the title for the node
2691 * @param string $title
2693 public function set_title($title) {
2694 $this->title = (string)$title;
2698 * Sets the url for the node
2699 * @param moodle_url $url
2701 public function set_url(moodle_url $url) {
2702 $this->url = $url;
2707 * Custom menu class
2709 * This class is used to operate a custom menu that can be rendered for the page.
2710 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2711 * of custom_menu_item nodes that can be rendered by the core renderer.
2713 * To configure the custom menu:
2714 * Settings: Administration > Appearance > Themes > Theme settings
2716 * @copyright 2010 Sam Hemelryk
2717 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2718 * @since Moodle 2.0
2719 * @package core
2720 * @category output
2722 class custom_menu extends custom_menu_item {
2725 * @var string The language we should render for, null disables multilang support.
2727 protected $currentlanguage = null;
2730 * Creates the custom menu
2732 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2733 * @param string $currentlanguage the current language code, null disables multilang support
2735 public function __construct($definition = '', $currentlanguage = null) {
2736 $this->currentlanguage = $currentlanguage;
2737 parent::__construct('root'); // create virtual root element of the menu
2738 if (!empty($definition)) {
2739 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2744 * Overrides the children of this custom menu. Useful when getting children
2745 * from $CFG->custommenuitems
2747 * @param array $children
2749 public function override_children(array $children) {
2750 $this->children = array();
2751 foreach ($children as $child) {
2752 if ($child instanceof custom_menu_item) {
2753 $this->children[] = $child;
2759 * Converts a string into a structured array of custom_menu_items which can
2760 * then be added to a custom menu.
2762 * Structure:
2763 * text|url|title|langs
2764 * The number of hyphens at the start determines the depth of the item. The
2765 * languages are optional, comma separated list of languages the line is for.
2767 * Example structure:
2768 * First level first item|http://www.moodle.com/
2769 * -Second level first item|http://www.moodle.com/partners/
2770 * -Second level second item|http://www.moodle.com/hq/
2771 * --Third level first item|http://www.moodle.com/jobs/
2772 * -Second level third item|http://www.moodle.com/development/
2773 * First level second item|http://www.moodle.com/feedback/
2774 * First level third item
2775 * English only|http://moodle.com|English only item|en
2776 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2779 * @static
2780 * @param string $text the menu items definition
2781 * @param string $language the language code, null disables multilang support
2782 * @return array
2784 public static function convert_text_to_menu_nodes($text, $language = null) {
2785 $lines = explode("\n", $text);
2786 $children = array();
2787 $lastchild = null;
2788 $lastdepth = null;
2789 $lastsort = 0;
2790 foreach ($lines as $line) {
2791 $line = trim($line);
2792 $bits = explode('|', $line, 4); // name|url|title|langs
2793 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2794 // Every item must have a name to be valid
2795 continue;
2796 } else {
2797 $bits[0] = ltrim($bits[0],'-');
2799 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2800 // Set the url to null
2801 $bits[1] = null;
2802 } else {
2803 // Make sure the url is a moodle url
2804 $bits[1] = new moodle_url(trim($bits[1]));
2806 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2807 // Set the title to null seeing as there isn't one
2808 $bits[2] = $bits[0];
2810 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2811 // The item is valid for all languages
2812 $itemlangs = null;
2813 } else {
2814 $itemlangs = array_map('trim', explode(',', $bits[3]));
2816 if (!empty($language) and !empty($itemlangs)) {
2817 // check that the item is intended for the current language
2818 if (!in_array($language, $itemlangs)) {
2819 continue;
2822 // Set an incremental sort order to keep it simple.
2823 $lastsort++;
2824 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2825 $depth = strlen($match[1]);
2826 if ($depth < $lastdepth) {
2827 $difference = $lastdepth - $depth;
2828 if ($lastdepth > 1 && $lastdepth != $difference) {
2829 $tempchild = $lastchild->get_parent();
2830 for ($i =0; $i < $difference; $i++) {
2831 $tempchild = $tempchild->get_parent();
2833 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2834 } else {
2835 $depth = 0;
2836 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2837 $children[] = $lastchild;
2839 } else if ($depth > $lastdepth) {
2840 $depth = $lastdepth + 1;
2841 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2842 } else {
2843 if ($depth == 0) {
2844 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2845 $children[] = $lastchild;
2846 } else {
2847 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2850 } else {
2851 $depth = 0;
2852 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2853 $children[] = $lastchild;
2855 $lastdepth = $depth;
2857 return $children;
2861 * Sorts two custom menu items
2863 * This function is designed to be used with the usort method
2864 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2866 * @static
2867 * @param custom_menu_item $itema
2868 * @param custom_menu_item $itemb
2869 * @return int
2871 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2872 $itema = $itema->get_sort_order();
2873 $itemb = $itemb->get_sort_order();
2874 if ($itema == $itemb) {
2875 return 0;
2877 return ($itema > $itemb) ? +1 : -1;
2882 * Stores one tab
2884 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2885 * @package core
2887 class tabobject implements renderable {
2888 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
2889 var $id;
2890 /** @var moodle_url|string link */
2891 var $link;
2892 /** @var string text on the tab */
2893 var $text;
2894 /** @var string title under the link, by defaul equals to text */
2895 var $title;
2896 /** @var bool whether to display a link under the tab name when it's selected */
2897 var $linkedwhenselected = false;
2898 /** @var bool whether the tab is inactive */
2899 var $inactive = false;
2900 /** @var bool indicates that this tab's child is selected */
2901 var $activated = false;
2902 /** @var bool indicates that this tab is selected */
2903 var $selected = false;
2904 /** @var array stores children tabobjects */
2905 var $subtree = array();
2906 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
2907 var $level = 1;
2910 * Constructor
2912 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
2913 * @param string|moodle_url $link
2914 * @param string $text text on the tab
2915 * @param string $title title under the link, by defaul equals to text
2916 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
2918 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
2919 $this->id = $id;
2920 $this->link = $link;
2921 $this->text = $text;
2922 $this->title = $title ? $title : $text;
2923 $this->linkedwhenselected = $linkedwhenselected;
2927 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
2929 * @param string $selected the id of the selected tab (whatever row it's on),
2930 * if null marks all tabs as unselected
2931 * @return bool whether this tab is selected or contains selected tab in its subtree
2933 protected function set_selected($selected) {
2934 if ((string)$selected === (string)$this->id) {
2935 $this->selected = true;
2936 // This tab is selected. No need to travel through subtree.
2937 return true;
2939 foreach ($this->subtree as $subitem) {
2940 if ($subitem->set_selected($selected)) {
2941 // This tab has child that is selected. Mark it as activated. No need to check other children.
2942 $this->activated = true;
2943 return true;
2946 return false;
2950 * Travels through tree and finds a tab with specified id
2952 * @param string $id
2953 * @return tabtree|null
2955 public function find($id) {
2956 if ((string)$this->id === (string)$id) {
2957 return $this;
2959 foreach ($this->subtree as $tab) {
2960 if ($obj = $tab->find($id)) {
2961 return $obj;
2964 return null;
2968 * Allows to mark each tab's level in the tree before rendering.
2970 * @param int $level
2972 protected function set_level($level) {
2973 $this->level = $level;
2974 foreach ($this->subtree as $tab) {
2975 $tab->set_level($level + 1);
2981 * Stores tabs list
2983 * Example how to print a single line tabs:
2984 * $rows = array(
2985 * new tabobject(...),
2986 * new tabobject(...)
2987 * );
2988 * echo $OUTPUT->tabtree($rows, $selectedid);
2990 * Multiple row tabs may not look good on some devices but if you want to use them
2991 * you can specify ->subtree for the active tabobject.
2993 * @copyright 2013 Marina Glancy
2994 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2995 * @since Moodle 2.5
2996 * @package core
2997 * @category output
2999 class tabtree extends tabobject {
3001 * Constuctor
3003 * It is highly recommended to call constructor when list of tabs is already
3004 * populated, this way you ensure that selected and inactive tabs are located
3005 * and attribute level is set correctly.
3007 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3008 * @param string|null $selected which tab to mark as selected, all parent tabs will
3009 * automatically be marked as activated
3010 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3011 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3013 public function __construct($tabs, $selected = null, $inactive = null) {
3014 $this->subtree = $tabs;
3015 if ($selected !== null) {
3016 $this->set_selected($selected);
3018 if ($inactive !== null) {
3019 if (is_array($inactive)) {
3020 foreach ($inactive as $id) {
3021 if ($tab = $this->find($id)) {
3022 $tab->inactive = true;
3025 } else if ($tab = $this->find($inactive)) {
3026 $tab->inactive = true;
3029 $this->set_level(0);
3034 * An action menu.
3036 * This action menu component takes a series of primary and secondary actions.
3037 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
3038 * down menu.
3040 * @package core
3041 * @category output
3042 * @copyright 2013 Sam Hemelryk
3043 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3045 class action_menu implements renderable {
3048 * Top right alignment.
3050 const TL = 1;
3053 * Top right alignment.
3055 const TR = 2;
3058 * Top right alignment.
3060 const BL = 3;
3063 * Top right alignment.
3065 const BR = 4;
3068 * The instance number. This is unique to this instance of the action menu.
3069 * @var int
3071 protected $instance = 0;
3074 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
3075 * @var array
3077 protected $primaryactions = array();
3080 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
3081 * @var array
3083 protected $secondaryactions = array();
3086 * An array of attributes added to the container of the action menu.
3087 * Initialised with defaults during construction.
3088 * @var array
3090 public $attributes = array();
3092 * An array of attributes added to the container of the primary actions.
3093 * Initialised with defaults during construction.
3094 * @var array
3096 public $attributesprimary = array();
3098 * An array of attributes added to the container of the secondary actions.
3099 * Initialised with defaults during construction.
3100 * @var array
3102 public $attributessecondary = array();
3105 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
3106 * @var array
3108 public $actiontext = null;
3111 * An icon to use for the toggling the secondary menu (dropdown).
3112 * @var actionicon
3114 public $actionicon;
3117 * Any text to use for the toggling the secondary menu (dropdown).
3118 * @var menutrigger
3120 public $menutrigger = '';
3123 * Place the action menu before all other actions.
3124 * @var prioritise
3126 public $prioritise = false;
3129 * Constructs the action menu with the given items.
3131 * @param array $actions An array of actions.
3133 public function __construct(array $actions = array()) {
3134 static $initialised = 0;
3135 $this->instance = $initialised;
3136 $initialised++;
3138 $this->attributes = array(
3139 'id' => 'action-menu-'.$this->instance,
3140 'class' => 'moodle-actionmenu',
3141 'data-enhance' => 'moodle-core-actionmenu'
3143 $this->attributesprimary = array(
3144 'id' => 'action-menu-'.$this->instance.'-menubar',
3145 'class' => 'menubar',
3146 'role' => 'menubar'
3148 $this->attributessecondary = array(
3149 'id' => 'action-menu-'.$this->instance.'-menu',
3150 'class' => 'menu',
3151 'data-rel' => 'menu-content',
3152 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
3153 'role' => 'menu'
3155 $this->set_alignment(self::TR, self::BR);
3156 foreach ($actions as $action) {
3157 $this->add($action);
3161 public function set_menu_trigger($trigger) {
3162 $this->menutrigger = $trigger;
3166 * Initialises JS required fore the action menu.
3167 * The JS is only required once as it manages all action menu's on the page.
3169 * @param moodle_page $page
3171 public function initialise_js(moodle_page $page) {
3172 static $initialised = false;
3173 if (!$initialised) {
3174 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
3175 $initialised = true;
3180 * Adds an action to this action menu.
3182 * @param action_menu_link|pix_icon|string $action
3184 public function add($action) {
3185 if ($action instanceof action_link) {
3186 if ($action->primary) {
3187 $this->add_primary_action($action);
3188 } else {
3189 $this->add_secondary_action($action);
3191 } else if ($action instanceof pix_icon) {
3192 $this->add_primary_action($action);
3193 } else {
3194 $this->add_secondary_action($action);
3199 * Adds a primary action to the action menu.
3201 * @param action_menu_link|action_link|pix_icon|string $action
3203 public function add_primary_action($action) {
3204 if ($action instanceof action_link || $action instanceof pix_icon) {
3205 $action->attributes['role'] = 'menuitem';
3206 if ($action instanceof action_menu_link) {
3207 $action->actionmenu = $this;
3210 $this->primaryactions[] = $action;
3214 * Adds a secondary action to the action menu.
3216 * @param action_link|pix_icon|string $action
3218 public function add_secondary_action($action) {
3219 if ($action instanceof action_link || $action instanceof pix_icon) {
3220 $action->attributes['role'] = 'menuitem';
3221 if ($action instanceof action_menu_link) {
3222 $action->actionmenu = $this;
3225 $this->secondaryactions[] = $action;
3229 * Returns the primary actions ready to be rendered.
3231 * @param core_renderer $output The renderer to use for getting icons.
3232 * @return array
3234 public function get_primary_actions(core_renderer $output = null) {
3235 global $OUTPUT;
3236 if ($output === null) {
3237 $output = $OUTPUT;
3239 $pixicon = $this->actionicon;
3240 $linkclasses = array('toggle-display');
3242 $title = '';
3243 if (!empty($this->menutrigger)) {
3244 $pixicon = '<b class="caret"></b>';
3245 $linkclasses[] = 'textmenu';
3246 } else {
3247 $title = new lang_string('actions', 'moodle');
3248 $this->actionicon = new pix_icon(
3249 't/edit_menu',
3251 'moodle',
3252 array('class' => 'iconsmall actionmenu', 'title' => '')
3254 $pixicon = $this->actionicon;
3256 if ($pixicon instanceof renderable) {
3257 $pixicon = $output->render($pixicon);
3258 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
3259 $title = $pixicon->attributes['alt'];
3262 $string = '';
3263 if ($this->actiontext) {
3264 $string = $this->actiontext;
3266 $actions = $this->primaryactions;
3267 $attributes = array(
3268 'class' => implode(' ', $linkclasses),
3269 'title' => $title,
3270 'id' => 'action-menu-toggle-'.$this->instance,
3271 'role' => 'menuitem'
3273 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
3274 if ($this->prioritise) {
3275 array_unshift($actions, $link);
3276 } else {
3277 $actions[] = $link;
3279 return $actions;
3283 * Returns the secondary actions ready to be rendered.
3284 * @return array
3286 public function get_secondary_actions() {
3287 return $this->secondaryactions;
3291 * Sets the selector that should be used to find the owning node of this menu.
3292 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
3294 public function set_owner_selector($selector) {
3295 $this->attributes['data-owner'] = $selector;
3299 * Sets the alignment of the dialogue in relation to button used to toggle it.
3301 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3302 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3304 public function set_alignment($dialogue, $button) {
3305 if (isset($this->attributessecondary['data-align'])) {
3306 // We've already got one set, lets remove the old class so as to avoid troubles.
3307 $class = $this->attributessecondary['class'];
3308 $search = 'align-'.$this->attributessecondary['data-align'];
3309 $this->attributessecondary['class'] = str_replace($search, '', $class);
3311 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
3312 $this->attributessecondary['data-align'] = $align;
3313 $this->attributessecondary['class'] .= ' align-'.$align;
3317 * Returns a string to describe the alignment.
3319 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3320 * @return string
3322 protected function get_align_string($align) {
3323 switch ($align) {
3324 case self::TL :
3325 return 'tl';
3326 case self::TR :
3327 return 'tr';
3328 case self::BL :
3329 return 'bl';
3330 case self::BR :
3331 return 'br';
3332 default :
3333 return 'tl';
3338 * Sets a constraint for the dialogue.
3340 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
3341 * element the constraint identifies.
3343 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
3345 public function set_constraint($ancestorselector) {
3346 $this->attributessecondary['data-constraint'] = $ancestorselector;
3350 * If you call this method the action menu will be displayed but will not be enhanced.
3352 * By not displaying the menu enhanced all items will be displayed in a single row.
3354 public function do_not_enhance() {
3355 unset($this->attributes['data-enhance']);
3359 * Returns true if this action menu will be enhanced.
3361 * @return bool
3363 public function will_be_enhanced() {
3364 return isset($this->attributes['data-enhance']);
3369 * An action menu filler
3371 * @package core
3372 * @category output
3373 * @copyright 2013 Andrew Nicols
3374 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3376 class action_menu_filler extends action_link implements renderable {
3379 * True if this is a primary action. False if not.
3380 * @var bool
3382 public $primary = true;
3385 * Constructs the object.
3387 public function __construct() {
3392 * An action menu action
3394 * @package core
3395 * @category output
3396 * @copyright 2013 Sam Hemelryk
3397 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3399 class action_menu_link extends action_link implements renderable {
3402 * True if this is a primary action. False if not.
3403 * @var bool
3405 public $primary = true;
3408 * The action menu this link has been added to.
3409 * @var action_menu
3411 public $actionmenu = null;
3414 * Constructs the object.
3416 * @param moodle_url $url The URL for the action.
3417 * @param pix_icon $icon The icon to represent the action.
3418 * @param string $text The text to represent the action.
3419 * @param bool $primary Whether this is a primary action or not.
3420 * @param array $attributes Any attribtues associated with the action.
3422 public function __construct(moodle_url $url, pix_icon $icon = null, $text, $primary = true, array $attributes = array()) {
3423 parent::__construct($url, $text, null, $attributes, $icon);
3424 $this->primary = (bool)$primary;
3425 $this->add_class('menu-action');
3426 $this->attributes['role'] = 'menuitem';
3431 * A primary action menu action
3433 * @package core
3434 * @category output
3435 * @copyright 2013 Sam Hemelryk
3436 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3438 class action_menu_link_primary extends action_menu_link {
3440 * Constructs the object.
3442 * @param moodle_url $url
3443 * @param pix_icon $icon
3444 * @param string $text
3445 * @param array $attributes
3447 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
3448 parent::__construct($url, $icon, $text, true, $attributes);
3453 * A secondary action menu action
3455 * @package core
3456 * @category output
3457 * @copyright 2013 Sam Hemelryk
3458 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3460 class action_menu_link_secondary extends action_menu_link {
3462 * Constructs the object.
3464 * @param moodle_url $url
3465 * @param pix_icon $icon
3466 * @param string $text
3467 * @param array $attributes
3469 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
3470 parent::__construct($url, $icon, $text, false, $attributes);