MDL-10115 User profile: Allow full list of courses to be viewed on a user's profile
[moodle.git] / lib / outputcomponents.php
blob76b0c834387f0809aa391b31ae417d6fa9aaa40a
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 a simple image tag with attributes.
1107 * @param string $src The source of image
1108 * @param string $alt The alternate text for image
1109 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1110 * @return string HTML fragment
1112 public static function img($src, $alt, array $attributes = null) {
1113 $attributes = (array)$attributes;
1114 $attributes['src'] = $src;
1115 $attributes['alt'] = $alt;
1117 return self::empty_tag('img', $attributes);
1121 * Generates random html element id.
1123 * @staticvar int $counter
1124 * @staticvar type $uniq
1125 * @param string $base A string fragment that will be included in the random ID.
1126 * @return string A unique ID
1128 public static function random_id($base='random') {
1129 static $counter = 0;
1130 static $uniq;
1132 if (!isset($uniq)) {
1133 $uniq = uniqid();
1136 $counter++;
1137 return $base.$uniq.$counter;
1141 * Generates a simple html link
1143 * @param string|moodle_url $url The URL
1144 * @param string $text The text
1145 * @param array $attributes HTML attributes
1146 * @return string HTML fragment
1148 public static function link($url, $text, array $attributes = null) {
1149 $attributes = (array)$attributes;
1150 $attributes['href'] = $url;
1151 return self::tag('a', $text, $attributes);
1155 * Generates a simple checkbox with optional label
1157 * @param string $name The name of the checkbox
1158 * @param string $value The value of the checkbox
1159 * @param bool $checked Whether the checkbox is checked
1160 * @param string $label The label for the checkbox
1161 * @param array $attributes Any attributes to apply to the checkbox
1162 * @return string html fragment
1164 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1165 $attributes = (array)$attributes;
1166 $output = '';
1168 if ($label !== '' and !is_null($label)) {
1169 if (empty($attributes['id'])) {
1170 $attributes['id'] = self::random_id('checkbox_');
1173 $attributes['type'] = 'checkbox';
1174 $attributes['value'] = $value;
1175 $attributes['name'] = $name;
1176 $attributes['checked'] = $checked ? 'checked' : null;
1178 $output .= self::empty_tag('input', $attributes);
1180 if ($label !== '' and !is_null($label)) {
1181 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1184 return $output;
1188 * Generates a simple select yes/no form field
1190 * @param string $name name of select element
1191 * @param bool $selected
1192 * @param array $attributes - html select element attributes
1193 * @return string HTML fragment
1195 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1196 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1197 return self::select($options, $name, $selected, null, $attributes);
1201 * Generates a simple select form field
1203 * @param array $options associative array value=>label ex.:
1204 * array(1=>'One, 2=>Two)
1205 * it is also possible to specify optgroup as complex label array ex.:
1206 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1207 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1208 * @param string $name name of select element
1209 * @param string|array $selected value or array of values depending on multiple attribute
1210 * @param array|bool $nothing add nothing selected option, or false of not added
1211 * @param array $attributes html select element attributes
1212 * @return string HTML fragment
1214 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1215 $attributes = (array)$attributes;
1216 if (is_array($nothing)) {
1217 foreach ($nothing as $k=>$v) {
1218 if ($v === 'choose' or $v === 'choosedots') {
1219 $nothing[$k] = get_string('choosedots');
1222 $options = $nothing + $options; // keep keys, do not override
1224 } else if (is_string($nothing) and $nothing !== '') {
1225 // BC
1226 $options = array(''=>$nothing) + $options;
1229 // we may accept more values if multiple attribute specified
1230 $selected = (array)$selected;
1231 foreach ($selected as $k=>$v) {
1232 $selected[$k] = (string)$v;
1235 if (!isset($attributes['id'])) {
1236 $id = 'menu'.$name;
1237 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1238 $id = str_replace('[', '', $id);
1239 $id = str_replace(']', '', $id);
1240 $attributes['id'] = $id;
1243 if (!isset($attributes['class'])) {
1244 $class = 'menu'.$name;
1245 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1246 $class = str_replace('[', '', $class);
1247 $class = str_replace(']', '', $class);
1248 $attributes['class'] = $class;
1250 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
1252 $attributes['name'] = $name;
1254 if (!empty($attributes['disabled'])) {
1255 $attributes['disabled'] = 'disabled';
1256 } else {
1257 unset($attributes['disabled']);
1260 $output = '';
1261 foreach ($options as $value=>$label) {
1262 if (is_array($label)) {
1263 // ignore key, it just has to be unique
1264 $output .= self::select_optgroup(key($label), current($label), $selected);
1265 } else {
1266 $output .= self::select_option($label, $value, $selected);
1269 return self::tag('select', $output, $attributes);
1273 * Returns HTML to display a select box option.
1275 * @param string $label The label to display as the option.
1276 * @param string|int $value The value the option represents
1277 * @param array $selected An array of selected options
1278 * @return string HTML fragment
1280 private static function select_option($label, $value, array $selected) {
1281 $attributes = array();
1282 $value = (string)$value;
1283 if (in_array($value, $selected, true)) {
1284 $attributes['selected'] = 'selected';
1286 $attributes['value'] = $value;
1287 return self::tag('option', $label, $attributes);
1291 * Returns HTML to display a select box option group.
1293 * @param string $groupname The label to use for the group
1294 * @param array $options The options in the group
1295 * @param array $selected An array of selected values.
1296 * @return string HTML fragment.
1298 private static function select_optgroup($groupname, $options, array $selected) {
1299 if (empty($options)) {
1300 return '';
1302 $attributes = array('label'=>$groupname);
1303 $output = '';
1304 foreach ($options as $value=>$label) {
1305 $output .= self::select_option($label, $value, $selected);
1307 return self::tag('optgroup', $output, $attributes);
1311 * This is a shortcut for making an hour selector menu.
1313 * @param string $type The type of selector (years, months, days, hours, minutes)
1314 * @param string $name fieldname
1315 * @param int $currenttime A default timestamp in GMT
1316 * @param int $step minute spacing
1317 * @param array $attributes - html select element attributes
1318 * @return HTML fragment
1320 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1321 if (!$currenttime) {
1322 $currenttime = time();
1324 $currentdate = usergetdate($currenttime);
1325 $userdatetype = $type;
1326 $timeunits = array();
1328 switch ($type) {
1329 case 'years':
1330 for ($i=1970; $i<=2020; $i++) {
1331 $timeunits[$i] = $i;
1333 $userdatetype = 'year';
1334 break;
1335 case 'months':
1336 for ($i=1; $i<=12; $i++) {
1337 $timeunits[$i] = userdate(gmmktime(12,0,0,$i,15,2000), "%B");
1339 $userdatetype = 'month';
1340 $currentdate['month'] = (int)$currentdate['mon'];
1341 break;
1342 case 'days':
1343 for ($i=1; $i<=31; $i++) {
1344 $timeunits[$i] = $i;
1346 $userdatetype = 'mday';
1347 break;
1348 case 'hours':
1349 for ($i=0; $i<=23; $i++) {
1350 $timeunits[$i] = sprintf("%02d",$i);
1352 break;
1353 case 'minutes':
1354 if ($step != 1) {
1355 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1358 for ($i=0; $i<=59; $i+=$step) {
1359 $timeunits[$i] = sprintf("%02d",$i);
1361 break;
1362 default:
1363 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1366 if (empty($attributes['id'])) {
1367 $attributes['id'] = self::random_id('ts_');
1369 $timerselector = self::select($timeunits, $name, $currentdate[$userdatetype], null, $attributes);
1370 $label = self::tag('label', get_string(substr($type, 0, -1), 'form'), array('for'=>$attributes['id'], 'class'=>'accesshide'));
1372 return $label.$timerselector;
1376 * Shortcut for quick making of lists
1378 * Note: 'list' is a reserved keyword ;-)
1380 * @param array $items
1381 * @param array $attributes
1382 * @param string $tag ul or ol
1383 * @return string
1385 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1386 $output = html_writer::start_tag($tag, $attributes)."\n";
1387 foreach ($items as $item) {
1388 $output .= html_writer::tag('li', $item)."\n";
1390 $output .= html_writer::end_tag($tag);
1391 return $output;
1395 * Returns hidden input fields created from url parameters.
1397 * @param moodle_url $url
1398 * @param array $exclude list of excluded parameters
1399 * @return string HTML fragment
1401 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1402 $exclude = (array)$exclude;
1403 $params = $url->params();
1404 foreach ($exclude as $key) {
1405 unset($params[$key]);
1408 $output = '';
1409 foreach ($params as $key => $value) {
1410 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1411 $output .= self::empty_tag('input', $attributes)."\n";
1413 return $output;
1417 * Generate a script tag containing the the specified code.
1419 * @param string $jscode the JavaScript code
1420 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
1421 * @return string HTML, the code wrapped in <script> tags.
1423 public static function script($jscode, $url=null) {
1424 if ($jscode) {
1425 $attributes = array('type'=>'text/javascript');
1426 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1428 } else if ($url) {
1429 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1430 return self::tag('script', '', $attributes) . "\n";
1432 } else {
1433 return '';
1438 * Renders HTML table
1440 * This method may modify the passed instance by adding some default properties if they are not set yet.
1441 * If this is not what you want, you should make a full clone of your data before passing them to this
1442 * method. In most cases this is not an issue at all so we do not clone by default for performance
1443 * and memory consumption reasons.
1445 * Please do not use .r0/.r1 for css, as they will be removed in Moodle 2.9.
1446 * @todo MDL-43902 , remove r0 and r1 from tr classes.
1448 * @param html_table $table data to be rendered
1449 * @return string HTML code
1451 public static function table(html_table $table) {
1452 // prepare table data and populate missing properties with reasonable defaults
1453 if (!empty($table->align)) {
1454 foreach ($table->align as $key => $aa) {
1455 if ($aa) {
1456 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1457 } else {
1458 $table->align[$key] = null;
1462 if (!empty($table->size)) {
1463 foreach ($table->size as $key => $ss) {
1464 if ($ss) {
1465 $table->size[$key] = 'width:'. $ss .';';
1466 } else {
1467 $table->size[$key] = null;
1471 if (!empty($table->wrap)) {
1472 foreach ($table->wrap as $key => $ww) {
1473 if ($ww) {
1474 $table->wrap[$key] = 'white-space:nowrap;';
1475 } else {
1476 $table->wrap[$key] = '';
1480 if (!empty($table->head)) {
1481 foreach ($table->head as $key => $val) {
1482 if (!isset($table->align[$key])) {
1483 $table->align[$key] = null;
1485 if (!isset($table->size[$key])) {
1486 $table->size[$key] = null;
1488 if (!isset($table->wrap[$key])) {
1489 $table->wrap[$key] = null;
1494 if (empty($table->attributes['class'])) {
1495 $table->attributes['class'] = 'generaltable';
1497 if (!empty($table->tablealign)) {
1498 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1501 // explicitly assigned properties override those defined via $table->attributes
1502 $table->attributes['class'] = trim($table->attributes['class']);
1503 $attributes = array_merge($table->attributes, array(
1504 'id' => $table->id,
1505 'width' => $table->width,
1506 'summary' => $table->summary,
1507 'cellpadding' => $table->cellpadding,
1508 'cellspacing' => $table->cellspacing,
1510 $output = html_writer::start_tag('table', $attributes) . "\n";
1512 $countcols = 0;
1514 if (!empty($table->head)) {
1515 $countcols = count($table->head);
1517 $output .= html_writer::start_tag('thead', array()) . "\n";
1518 $output .= html_writer::start_tag('tr', array()) . "\n";
1519 $keys = array_keys($table->head);
1520 $lastkey = end($keys);
1522 foreach ($table->head as $key => $heading) {
1523 // Convert plain string headings into html_table_cell objects
1524 if (!($heading instanceof html_table_cell)) {
1525 $headingtext = $heading;
1526 $heading = new html_table_cell();
1527 $heading->text = $headingtext;
1528 $heading->header = true;
1531 if ($heading->header !== false) {
1532 $heading->header = true;
1535 if ($heading->header && empty($heading->scope)) {
1536 $heading->scope = 'col';
1539 $heading->attributes['class'] .= ' header c' . $key;
1540 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1541 $heading->colspan = $table->headspan[$key];
1542 $countcols += $table->headspan[$key] - 1;
1545 if ($key == $lastkey) {
1546 $heading->attributes['class'] .= ' lastcol';
1548 if (isset($table->colclasses[$key])) {
1549 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
1551 $heading->attributes['class'] = trim($heading->attributes['class']);
1552 $attributes = array_merge($heading->attributes, array(
1553 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
1554 'scope' => $heading->scope,
1555 'colspan' => $heading->colspan,
1558 $tagtype = 'td';
1559 if ($heading->header === true) {
1560 $tagtype = 'th';
1562 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
1564 $output .= html_writer::end_tag('tr') . "\n";
1565 $output .= html_writer::end_tag('thead') . "\n";
1567 if (empty($table->data)) {
1568 // For valid XHTML strict every table must contain either a valid tr
1569 // or a valid tbody... both of which must contain a valid td
1570 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
1571 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
1572 $output .= html_writer::end_tag('tbody');
1576 if (!empty($table->data)) {
1577 $oddeven = 1;
1578 $keys = array_keys($table->data);
1579 $lastrowkey = end($keys);
1580 $output .= html_writer::start_tag('tbody', array());
1582 foreach ($table->data as $key => $row) {
1583 if (($row === 'hr') && ($countcols)) {
1584 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
1585 } else {
1586 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1587 if (!($row instanceof html_table_row)) {
1588 $newrow = new html_table_row();
1590 foreach ($row as $cell) {
1591 if (!($cell instanceof html_table_cell)) {
1592 $cell = new html_table_cell($cell);
1594 $newrow->cells[] = $cell;
1596 $row = $newrow;
1599 $oddeven = $oddeven ? 0 : 1;
1600 if (isset($table->rowclasses[$key])) {
1601 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1604 $row->attributes['class'] .= ' r' . $oddeven;
1605 if ($key == $lastrowkey) {
1606 $row->attributes['class'] .= ' lastrow';
1609 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1610 $keys2 = array_keys($row->cells);
1611 $lastkey = end($keys2);
1613 $gotlastkey = false; //flag for sanity checking
1614 foreach ($row->cells as $key => $cell) {
1615 if ($gotlastkey) {
1616 //This should never happen. Why do we have a cell after the last cell?
1617 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1620 if (!($cell instanceof html_table_cell)) {
1621 $mycell = new html_table_cell();
1622 $mycell->text = $cell;
1623 $cell = $mycell;
1626 if (($cell->header === true) && empty($cell->scope)) {
1627 $cell->scope = 'row';
1630 if (isset($table->colclasses[$key])) {
1631 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1634 $cell->attributes['class'] .= ' cell c' . $key;
1635 if ($key == $lastkey) {
1636 $cell->attributes['class'] .= ' lastcol';
1637 $gotlastkey = true;
1639 $tdstyle = '';
1640 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1641 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1642 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1643 $cell->attributes['class'] = trim($cell->attributes['class']);
1644 $tdattributes = array_merge($cell->attributes, array(
1645 'style' => $tdstyle . $cell->style,
1646 'colspan' => $cell->colspan,
1647 'rowspan' => $cell->rowspan,
1648 'id' => $cell->id,
1649 'abbr' => $cell->abbr,
1650 'scope' => $cell->scope,
1652 $tagtype = 'td';
1653 if ($cell->header === true) {
1654 $tagtype = 'th';
1656 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1659 $output .= html_writer::end_tag('tr') . "\n";
1661 $output .= html_writer::end_tag('tbody') . "\n";
1663 $output .= html_writer::end_tag('table') . "\n";
1665 return $output;
1669 * Renders form element label
1671 * By default, the label is suffixed with a label separator defined in the
1672 * current language pack (colon by default in the English lang pack).
1673 * Adding the colon can be explicitly disabled if needed. Label separators
1674 * are put outside the label tag itself so they are not read by
1675 * screenreaders (accessibility).
1677 * Parameter $for explicitly associates the label with a form control. When
1678 * set, the value of this attribute must be the same as the value of
1679 * the id attribute of the form control in the same document. When null,
1680 * the label being defined is associated with the control inside the label
1681 * element.
1683 * @param string $text content of the label tag
1684 * @param string|null $for id of the element this label is associated with, null for no association
1685 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1686 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1687 * @return string HTML of the label element
1689 public static function label($text, $for, $colonize = true, array $attributes=array()) {
1690 if (!is_null($for)) {
1691 $attributes = array_merge($attributes, array('for' => $for));
1693 $text = trim($text);
1694 $label = self::tag('label', $text, $attributes);
1696 // TODO MDL-12192 $colonize disabled for now yet
1697 // if (!empty($text) and $colonize) {
1698 // // the $text may end with the colon already, though it is bad string definition style
1699 // $colon = get_string('labelsep', 'langconfig');
1700 // if (!empty($colon)) {
1701 // $trimmed = trim($colon);
1702 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1703 // //debugging('The label text should not end with colon or other label separator,
1704 // // please fix the string definition.', DEBUG_DEVELOPER);
1705 // } else {
1706 // $label .= $colon;
1707 // }
1708 // }
1709 // }
1711 return $label;
1715 * Combines a class parameter with other attributes. Aids in code reduction
1716 * because the class parameter is very frequently used.
1718 * If the class attribute is specified both in the attributes and in the
1719 * class parameter, the two values are combined with a space between.
1721 * @param string $class Optional CSS class (or classes as space-separated list)
1722 * @param array $attributes Optional other attributes as array
1723 * @return array Attributes (or null if still none)
1725 private static function add_class($class = '', array $attributes = null) {
1726 if ($class !== '') {
1727 $classattribute = array('class' => $class);
1728 if ($attributes) {
1729 if (array_key_exists('class', $attributes)) {
1730 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
1731 } else {
1732 $attributes = $classattribute + $attributes;
1734 } else {
1735 $attributes = $classattribute;
1738 return $attributes;
1742 * Creates a <div> tag. (Shortcut function.)
1744 * @param string $content HTML content of tag
1745 * @param string $class Optional CSS class (or classes as space-separated list)
1746 * @param array $attributes Optional other attributes as array
1747 * @return string HTML code for div
1749 public static function div($content, $class = '', array $attributes = null) {
1750 return self::tag('div', $content, self::add_class($class, $attributes));
1754 * Starts a <div> tag. (Shortcut function.)
1756 * @param string $class Optional CSS class (or classes as space-separated list)
1757 * @param array $attributes Optional other attributes as array
1758 * @return string HTML code for open div tag
1760 public static function start_div($class = '', array $attributes = null) {
1761 return self::start_tag('div', self::add_class($class, $attributes));
1765 * Ends a <div> tag. (Shortcut function.)
1767 * @return string HTML code for close div tag
1769 public static function end_div() {
1770 return self::end_tag('div');
1774 * Creates a <span> tag. (Shortcut function.)
1776 * @param string $content HTML content of tag
1777 * @param string $class Optional CSS class (or classes as space-separated list)
1778 * @param array $attributes Optional other attributes as array
1779 * @return string HTML code for span
1781 public static function span($content, $class = '', array $attributes = null) {
1782 return self::tag('span', $content, self::add_class($class, $attributes));
1786 * Starts a <span> tag. (Shortcut function.)
1788 * @param string $class Optional CSS class (or classes as space-separated list)
1789 * @param array $attributes Optional other attributes as array
1790 * @return string HTML code for open span tag
1792 public static function start_span($class = '', array $attributes = null) {
1793 return self::start_tag('span', self::add_class($class, $attributes));
1797 * Ends a <span> tag. (Shortcut function.)
1799 * @return string HTML code for close span tag
1801 public static function end_span() {
1802 return self::end_tag('span');
1807 * Simple javascript output class
1809 * @copyright 2010 Petr Skoda
1810 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1811 * @since Moodle 2.0
1812 * @package core
1813 * @category output
1815 class js_writer {
1818 * Returns javascript code calling the function
1820 * @param string $function function name, can be complex like Y.Event.purgeElement
1821 * @param array $arguments parameters
1822 * @param int $delay execution delay in seconds
1823 * @return string JS code fragment
1825 public static function function_call($function, array $arguments = null, $delay=0) {
1826 if ($arguments) {
1827 $arguments = array_map('json_encode', convert_to_array($arguments));
1828 $arguments = implode(', ', $arguments);
1829 } else {
1830 $arguments = '';
1832 $js = "$function($arguments);";
1834 if ($delay) {
1835 $delay = $delay * 1000; // in miliseconds
1836 $js = "setTimeout(function() { $js }, $delay);";
1838 return $js . "\n";
1842 * Special function which adds Y as first argument of function call.
1844 * @param string $function The function to call
1845 * @param array $extraarguments Any arguments to pass to it
1846 * @return string Some JS code
1848 public static function function_call_with_Y($function, array $extraarguments = null) {
1849 if ($extraarguments) {
1850 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1851 $arguments = 'Y, ' . implode(', ', $extraarguments);
1852 } else {
1853 $arguments = 'Y';
1855 return "$function($arguments);\n";
1859 * Returns JavaScript code to initialise a new object
1861 * @param string $var If it is null then no var is assigned the new object.
1862 * @param string $class The class to initialise an object for.
1863 * @param array $arguments An array of args to pass to the init method.
1864 * @param array $requirements Any modules required for this class.
1865 * @param int $delay The delay before initialisation. 0 = no delay.
1866 * @return string Some JS code
1868 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1869 if (is_array($arguments)) {
1870 $arguments = array_map('json_encode', convert_to_array($arguments));
1871 $arguments = implode(', ', $arguments);
1874 if ($var === null) {
1875 $js = "new $class(Y, $arguments);";
1876 } else if (strpos($var, '.')!==false) {
1877 $js = "$var = new $class(Y, $arguments);";
1878 } else {
1879 $js = "var $var = new $class(Y, $arguments);";
1882 if ($delay) {
1883 $delay = $delay * 1000; // in miliseconds
1884 $js = "setTimeout(function() { $js }, $delay);";
1887 if (count($requirements) > 0) {
1888 $requirements = implode("', '", $requirements);
1889 $js = "Y.use('$requirements', function(Y){ $js });";
1891 return $js."\n";
1895 * Returns code setting value to variable
1897 * @param string $name
1898 * @param mixed $value json serialised value
1899 * @param bool $usevar add var definition, ignored for nested properties
1900 * @return string JS code fragment
1902 public static function set_variable($name, $value, $usevar = true) {
1903 $output = '';
1905 if ($usevar) {
1906 if (strpos($name, '.')) {
1907 $output .= '';
1908 } else {
1909 $output .= 'var ';
1913 $output .= "$name = ".json_encode($value).";";
1915 return $output;
1919 * Writes event handler attaching code
1921 * @param array|string $selector standard YUI selector for elements, may be
1922 * array or string, element id is in the form "#idvalue"
1923 * @param string $event A valid DOM event (click, mousedown, change etc.)
1924 * @param string $function The name of the function to call
1925 * @param array $arguments An optional array of argument parameters to pass to the function
1926 * @return string JS code fragment
1928 public static function event_handler($selector, $event, $function, array $arguments = null) {
1929 $selector = json_encode($selector);
1930 $output = "Y.on('$event', $function, $selector, null";
1931 if (!empty($arguments)) {
1932 $output .= ', ' . json_encode($arguments);
1934 return $output . ");\n";
1939 * Holds all the information required to render a <table> by {@link core_renderer::table()}
1941 * Example of usage:
1942 * $t = new html_table();
1943 * ... // set various properties of the object $t as described below
1944 * echo html_writer::table($t);
1946 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1947 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1948 * @since Moodle 2.0
1949 * @package core
1950 * @category output
1952 class html_table {
1955 * @var string Value to use for the id attribute of the table
1957 public $id = null;
1960 * @var array Attributes of HTML attributes for the <table> element
1962 public $attributes = array();
1965 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
1966 * For more control over the rendering of the headers, an array of html_table_cell objects
1967 * can be passed instead of an array of strings.
1969 * Example of usage:
1970 * $t->head = array('Student', 'Grade');
1972 public $head;
1975 * @var array An array that can be used to make a heading span multiple columns.
1976 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1977 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
1979 * Example of usage:
1980 * $t->headspan = array(2,1);
1982 public $headspan;
1985 * @var array An array of column alignments.
1986 * The value is used as CSS 'text-align' property. Therefore, possible
1987 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1988 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1990 * Examples of usage:
1991 * $t->align = array(null, 'right');
1992 * or
1993 * $t->align[1] = 'right';
1995 public $align;
1998 * @var array The value is used as CSS 'size' property.
2000 * Examples of usage:
2001 * $t->size = array('50%', '50%');
2002 * or
2003 * $t->size[1] = '120px';
2005 public $size;
2008 * @var array An array of wrapping information.
2009 * The only possible value is 'nowrap' that sets the
2010 * CSS property 'white-space' to the value 'nowrap' in the given column.
2012 * Example of usage:
2013 * $t->wrap = array(null, 'nowrap');
2015 public $wrap;
2018 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2019 * $head specified, the string 'hr' (for horizontal ruler) can be used
2020 * instead of an array of cells data resulting in a divider rendered.
2022 * Example of usage with array of arrays:
2023 * $row1 = array('Harry Potter', '76 %');
2024 * $row2 = array('Hermione Granger', '100 %');
2025 * $t->data = array($row1, $row2);
2027 * Example with array of html_table_row objects: (used for more fine-grained control)
2028 * $cell1 = new html_table_cell();
2029 * $cell1->text = 'Harry Potter';
2030 * $cell1->colspan = 2;
2031 * $row1 = new html_table_row();
2032 * $row1->cells[] = $cell1;
2033 * $cell2 = new html_table_cell();
2034 * $cell2->text = 'Hermione Granger';
2035 * $cell3 = new html_table_cell();
2036 * $cell3->text = '100 %';
2037 * $row2 = new html_table_row();
2038 * $row2->cells = array($cell2, $cell3);
2039 * $t->data = array($row1, $row2);
2041 public $data;
2044 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2045 * @var string Width of the table, percentage of the page preferred.
2047 public $width = null;
2050 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2051 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2053 public $tablealign = null;
2056 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2057 * @var int Padding on each cell, in pixels
2059 public $cellpadding = null;
2062 * @var int Spacing between cells, in pixels
2063 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2065 public $cellspacing = null;
2068 * @var array Array of classes to add to particular rows, space-separated string.
2069 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
2070 * respectively. Class 'lastrow' is added automatically for the last row
2071 * in the table.
2073 * Example of usage:
2074 * $t->rowclasses[9] = 'tenth'
2076 public $rowclasses;
2079 * @var array An array of classes to add to every cell in a particular column,
2080 * space-separated string. Class 'cell' is added automatically by the renderer.
2081 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2082 * respectively. Class 'lastcol' is added automatically for all last cells
2083 * in a row.
2085 * Example of usage:
2086 * $t->colclasses = array(null, 'grade');
2088 public $colclasses;
2091 * @var string Description of the contents for screen readers.
2093 public $summary;
2096 * Constructor
2098 public function __construct() {
2099 $this->attributes['class'] = '';
2104 * Component representing a table row.
2106 * @copyright 2009 Nicolas Connault
2107 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2108 * @since Moodle 2.0
2109 * @package core
2110 * @category output
2112 class html_table_row {
2115 * @var string Value to use for the id attribute of the row.
2117 public $id = null;
2120 * @var array Array of html_table_cell objects
2122 public $cells = array();
2125 * @var string Value to use for the style attribute of the table row
2127 public $style = null;
2130 * @var array Attributes of additional HTML attributes for the <tr> element
2132 public $attributes = array();
2135 * Constructor
2136 * @param array $cells
2138 public function __construct(array $cells=null) {
2139 $this->attributes['class'] = '';
2140 $cells = (array)$cells;
2141 foreach ($cells as $cell) {
2142 if ($cell instanceof html_table_cell) {
2143 $this->cells[] = $cell;
2144 } else {
2145 $this->cells[] = new html_table_cell($cell);
2152 * Component representing a table cell.
2154 * @copyright 2009 Nicolas Connault
2155 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2156 * @since Moodle 2.0
2157 * @package core
2158 * @category output
2160 class html_table_cell {
2163 * @var string Value to use for the id attribute of the cell.
2165 public $id = null;
2168 * @var string The contents of the cell.
2170 public $text;
2173 * @var string Abbreviated version of the contents of the cell.
2175 public $abbr = null;
2178 * @var int Number of columns this cell should span.
2180 public $colspan = null;
2183 * @var int Number of rows this cell should span.
2185 public $rowspan = null;
2188 * @var string Defines a way to associate header cells and data cells in a table.
2190 public $scope = null;
2193 * @var bool Whether or not this cell is a header cell.
2195 public $header = null;
2198 * @var string Value to use for the style attribute of the table cell
2200 public $style = null;
2203 * @var array Attributes of additional HTML attributes for the <td> element
2205 public $attributes = array();
2208 * Constructs a table cell
2210 * @param string $text
2212 public function __construct($text = null) {
2213 $this->text = $text;
2214 $this->attributes['class'] = '';
2219 * Component representing a paging bar.
2221 * @copyright 2009 Nicolas Connault
2222 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2223 * @since Moodle 2.0
2224 * @package core
2225 * @category output
2227 class paging_bar implements renderable {
2230 * @var int The maximum number of pagelinks to display.
2232 public $maxdisplay = 18;
2235 * @var int The total number of entries to be pages through..
2237 public $totalcount;
2240 * @var int The page you are currently viewing.
2242 public $page;
2245 * @var int The number of entries that should be shown per page.
2247 public $perpage;
2250 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2251 * an equals sign and the page number.
2252 * If this is a moodle_url object then the pagevar param will be replaced by
2253 * the page no, for each page.
2255 public $baseurl;
2258 * @var string This is the variable name that you use for the pagenumber in your
2259 * code (ie. 'tablepage', 'blogpage', etc)
2261 public $pagevar;
2264 * @var string A HTML link representing the "previous" page.
2266 public $previouslink = null;
2269 * @var string A HTML link representing the "next" page.
2271 public $nextlink = null;
2274 * @var string A HTML link representing the first page.
2276 public $firstlink = null;
2279 * @var string A HTML link representing the last page.
2281 public $lastlink = null;
2284 * @var array An array of strings. One of them is just a string: the current page
2286 public $pagelinks = array();
2289 * Constructor paging_bar with only the required params.
2291 * @param int $totalcount The total number of entries available to be paged through
2292 * @param int $page The page you are currently viewing
2293 * @param int $perpage The number of entries that should be shown per page
2294 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2295 * @param string $pagevar name of page parameter that holds the page number
2297 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2298 $this->totalcount = $totalcount;
2299 $this->page = $page;
2300 $this->perpage = $perpage;
2301 $this->baseurl = $baseurl;
2302 $this->pagevar = $pagevar;
2306 * Prepares the paging bar for output.
2308 * This method validates the arguments set up for the paging bar and then
2309 * produces fragments of HTML to assist display later on.
2311 * @param renderer_base $output
2312 * @param moodle_page $page
2313 * @param string $target
2314 * @throws coding_exception
2316 public function prepare(renderer_base $output, moodle_page $page, $target) {
2317 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2318 throw new coding_exception('paging_bar requires a totalcount value.');
2320 if (!isset($this->page) || is_null($this->page)) {
2321 throw new coding_exception('paging_bar requires a page value.');
2323 if (empty($this->perpage)) {
2324 throw new coding_exception('paging_bar requires a perpage value.');
2326 if (empty($this->baseurl)) {
2327 throw new coding_exception('paging_bar requires a baseurl value.');
2330 if ($this->totalcount > $this->perpage) {
2331 $pagenum = $this->page - 1;
2333 if ($this->page > 0) {
2334 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2337 if ($this->perpage > 0) {
2338 $lastpage = ceil($this->totalcount / $this->perpage);
2339 } else {
2340 $lastpage = 1;
2343 if ($this->page > round(($this->maxdisplay/3)*2)) {
2344 $currpage = $this->page - round($this->maxdisplay/3);
2346 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2347 } else {
2348 $currpage = 0;
2351 $displaycount = $displaypage = 0;
2353 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2354 $displaypage = $currpage + 1;
2356 if ($this->page == $currpage) {
2357 $this->pagelinks[] = $displaypage;
2358 } else {
2359 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2360 $this->pagelinks[] = $pagelink;
2363 $displaycount++;
2364 $currpage++;
2367 if ($currpage < $lastpage) {
2368 $lastpageactual = $lastpage - 1;
2369 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2372 $pagenum = $this->page + 1;
2374 if ($pagenum != $displaypage) {
2375 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2382 * This class represents how a block appears on a page.
2384 * During output, each block instance is asked to return a block_contents object,
2385 * those are then passed to the $OUTPUT->block function for display.
2387 * contents should probably be generated using a moodle_block_..._renderer.
2389 * Other block-like things that need to appear on the page, for example the
2390 * add new block UI, are also represented as block_contents objects.
2392 * @copyright 2009 Tim Hunt
2393 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2394 * @since Moodle 2.0
2395 * @package core
2396 * @category output
2398 class block_contents {
2400 /** Used when the block cannot be collapsed **/
2401 const NOT_HIDEABLE = 0;
2403 /** Used when the block can be collapsed but currently is not **/
2404 const VISIBLE = 1;
2406 /** Used when the block has been collapsed **/
2407 const HIDDEN = 2;
2410 * @var int Used to set $skipid.
2412 protected static $idcounter = 1;
2415 * @var int All the blocks (or things that look like blocks) printed on
2416 * a page are given a unique number that can be used to construct id="" attributes.
2417 * This is set automatically be the {@link prepare()} method.
2418 * Do not try to set it manually.
2420 public $skipid;
2423 * @var int If this is the contents of a real block, this should be set
2424 * to the block_instance.id. Otherwise this should be set to 0.
2426 public $blockinstanceid = 0;
2429 * @var int If this is a real block instance, and there is a corresponding
2430 * block_position.id for the block on this page, this should be set to that id.
2431 * Otherwise it should be 0.
2433 public $blockpositionid = 0;
2436 * @var array An array of attribute => value pairs that are put on the outer div of this
2437 * block. {@link $id} and {@link $classes} attributes should be set separately.
2439 public $attributes;
2442 * @var string The title of this block. If this came from user input, it should already
2443 * have had format_string() processing done on it. This will be output inside
2444 * <h2> tags. Please do not cause invalid XHTML.
2446 public $title = '';
2449 * @var string The label to use when the block does not, or will not have a visible title.
2450 * You should never set this as well as title... it will just be ignored.
2452 public $arialabel = '';
2455 * @var string HTML for the content
2457 public $content = '';
2460 * @var array An alternative to $content, it you want a list of things with optional icons.
2462 public $footer = '';
2465 * @var string Any small print that should appear under the block to explain
2466 * to the teacher about the block, for example 'This is a sticky block that was
2467 * added in the system context.'
2469 public $annotation = '';
2472 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2473 * the user can toggle whether this block is visible.
2475 public $collapsible = self::NOT_HIDEABLE;
2478 * Set this to true if the block is dockable.
2479 * @var bool
2481 public $dockable = false;
2484 * @var array A (possibly empty) array of editing controls. Each element of
2485 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2486 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2488 public $controls = array();
2492 * Create new instance of block content
2493 * @param array $attributes
2495 public function __construct(array $attributes = null) {
2496 $this->skipid = self::$idcounter;
2497 self::$idcounter += 1;
2499 if ($attributes) {
2500 // standard block
2501 $this->attributes = $attributes;
2502 } else {
2503 // simple "fake" blocks used in some modules and "Add new block" block
2504 $this->attributes = array('class'=>'block');
2509 * Add html class to block
2511 * @param string $class
2513 public function add_class($class) {
2514 $this->attributes['class'] .= ' '.$class;
2520 * This class represents a target for where a block can go when it is being moved.
2522 * This needs to be rendered as a form with the given hidden from fields, and
2523 * clicking anywhere in the form should submit it. The form action should be
2524 * $PAGE->url.
2526 * @copyright 2009 Tim Hunt
2527 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2528 * @since Moodle 2.0
2529 * @package core
2530 * @category output
2532 class block_move_target {
2535 * @var moodle_url Move url
2537 public $url;
2540 * Constructor
2541 * @param moodle_url $url
2543 public function __construct(moodle_url $url) {
2544 $this->url = $url;
2549 * Custom menu item
2551 * This class is used to represent one item within a custom menu that may or may
2552 * not have children.
2554 * @copyright 2010 Sam Hemelryk
2555 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2556 * @since Moodle 2.0
2557 * @package core
2558 * @category output
2560 class custom_menu_item implements renderable {
2563 * @var string The text to show for the item
2565 protected $text;
2568 * @var moodle_url The link to give the icon if it has no children
2570 protected $url;
2573 * @var string A title to apply to the item. By default the text
2575 protected $title;
2578 * @var int A sort order for the item, not necessary if you order things in
2579 * the CFG var.
2581 protected $sort;
2584 * @var custom_menu_item A reference to the parent for this item or NULL if
2585 * it is a top level item
2587 protected $parent;
2590 * @var array A array in which to store children this item has.
2592 protected $children = array();
2595 * @var int A reference to the sort var of the last child that was added
2597 protected $lastsort = 0;
2600 * Constructs the new custom menu item
2602 * @param string $text
2603 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2604 * @param string $title A title to apply to this item [Optional]
2605 * @param int $sort A sort or to use if we need to sort differently [Optional]
2606 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2607 * belongs to, only if the child has a parent. [Optional]
2609 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
2610 $this->text = $text;
2611 $this->url = $url;
2612 $this->title = $title;
2613 $this->sort = (int)$sort;
2614 $this->parent = $parent;
2618 * Adds a custom menu item as a child of this node given its properties.
2620 * @param string $text
2621 * @param moodle_url $url
2622 * @param string $title
2623 * @param int $sort
2624 * @return custom_menu_item
2626 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
2627 $key = count($this->children);
2628 if (empty($sort)) {
2629 $sort = $this->lastsort + 1;
2631 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2632 $this->lastsort = (int)$sort;
2633 return $this->children[$key];
2637 * Returns the text for this item
2638 * @return string
2640 public function get_text() {
2641 return $this->text;
2645 * Returns the url for this item
2646 * @return moodle_url
2648 public function get_url() {
2649 return $this->url;
2653 * Returns the title for this item
2654 * @return string
2656 public function get_title() {
2657 return $this->title;
2661 * Sorts and returns the children for this item
2662 * @return array
2664 public function get_children() {
2665 $this->sort();
2666 return $this->children;
2670 * Gets the sort order for this child
2671 * @return int
2673 public function get_sort_order() {
2674 return $this->sort;
2678 * Gets the parent this child belong to
2679 * @return custom_menu_item
2681 public function get_parent() {
2682 return $this->parent;
2686 * Sorts the children this item has
2688 public function sort() {
2689 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2693 * Returns true if this item has any children
2694 * @return bool
2696 public function has_children() {
2697 return (count($this->children) > 0);
2701 * Sets the text for the node
2702 * @param string $text
2704 public function set_text($text) {
2705 $this->text = (string)$text;
2709 * Sets the title for the node
2710 * @param string $title
2712 public function set_title($title) {
2713 $this->title = (string)$title;
2717 * Sets the url for the node
2718 * @param moodle_url $url
2720 public function set_url(moodle_url $url) {
2721 $this->url = $url;
2726 * Custom menu class
2728 * This class is used to operate a custom menu that can be rendered for the page.
2729 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2730 * of custom_menu_item nodes that can be rendered by the core renderer.
2732 * To configure the custom menu:
2733 * Settings: Administration > Appearance > Themes > Theme settings
2735 * @copyright 2010 Sam Hemelryk
2736 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2737 * @since Moodle 2.0
2738 * @package core
2739 * @category output
2741 class custom_menu extends custom_menu_item {
2744 * @var string The language we should render for, null disables multilang support.
2746 protected $currentlanguage = null;
2749 * Creates the custom menu
2751 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2752 * @param string $currentlanguage the current language code, null disables multilang support
2754 public function __construct($definition = '', $currentlanguage = null) {
2755 $this->currentlanguage = $currentlanguage;
2756 parent::__construct('root'); // create virtual root element of the menu
2757 if (!empty($definition)) {
2758 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2763 * Overrides the children of this custom menu. Useful when getting children
2764 * from $CFG->custommenuitems
2766 * @param array $children
2768 public function override_children(array $children) {
2769 $this->children = array();
2770 foreach ($children as $child) {
2771 if ($child instanceof custom_menu_item) {
2772 $this->children[] = $child;
2778 * Converts a string into a structured array of custom_menu_items which can
2779 * then be added to a custom menu.
2781 * Structure:
2782 * text|url|title|langs
2783 * The number of hyphens at the start determines the depth of the item. The
2784 * languages are optional, comma separated list of languages the line is for.
2786 * Example structure:
2787 * First level first item|http://www.moodle.com/
2788 * -Second level first item|http://www.moodle.com/partners/
2789 * -Second level second item|http://www.moodle.com/hq/
2790 * --Third level first item|http://www.moodle.com/jobs/
2791 * -Second level third item|http://www.moodle.com/development/
2792 * First level second item|http://www.moodle.com/feedback/
2793 * First level third item
2794 * English only|http://moodle.com|English only item|en
2795 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2798 * @static
2799 * @param string $text the menu items definition
2800 * @param string $language the language code, null disables multilang support
2801 * @return array
2803 public static function convert_text_to_menu_nodes($text, $language = null) {
2804 $lines = explode("\n", $text);
2805 $children = array();
2806 $lastchild = null;
2807 $lastdepth = null;
2808 $lastsort = 0;
2809 foreach ($lines as $line) {
2810 $line = trim($line);
2811 $bits = explode('|', $line, 4); // name|url|title|langs
2812 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2813 // Every item must have a name to be valid
2814 continue;
2815 } else {
2816 $bits[0] = ltrim($bits[0],'-');
2818 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2819 // Set the url to null
2820 $bits[1] = null;
2821 } else {
2822 // Make sure the url is a moodle url
2823 $bits[1] = new moodle_url(trim($bits[1]));
2825 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2826 // Set the title to null seeing as there isn't one
2827 $bits[2] = $bits[0];
2829 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2830 // The item is valid for all languages
2831 $itemlangs = null;
2832 } else {
2833 $itemlangs = array_map('trim', explode(',', $bits[3]));
2835 if (!empty($language) and !empty($itemlangs)) {
2836 // check that the item is intended for the current language
2837 if (!in_array($language, $itemlangs)) {
2838 continue;
2841 // Set an incremental sort order to keep it simple.
2842 $lastsort++;
2843 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2844 $depth = strlen($match[1]);
2845 if ($depth < $lastdepth) {
2846 $difference = $lastdepth - $depth;
2847 if ($lastdepth > 1 && $lastdepth != $difference) {
2848 $tempchild = $lastchild->get_parent();
2849 for ($i =0; $i < $difference; $i++) {
2850 $tempchild = $tempchild->get_parent();
2852 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2853 } else {
2854 $depth = 0;
2855 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2856 $children[] = $lastchild;
2858 } else if ($depth > $lastdepth) {
2859 $depth = $lastdepth + 1;
2860 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2861 } else {
2862 if ($depth == 0) {
2863 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2864 $children[] = $lastchild;
2865 } else {
2866 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2869 } else {
2870 $depth = 0;
2871 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2872 $children[] = $lastchild;
2874 $lastdepth = $depth;
2876 return $children;
2880 * Sorts two custom menu items
2882 * This function is designed to be used with the usort method
2883 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2885 * @static
2886 * @param custom_menu_item $itema
2887 * @param custom_menu_item $itemb
2888 * @return int
2890 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2891 $itema = $itema->get_sort_order();
2892 $itemb = $itemb->get_sort_order();
2893 if ($itema == $itemb) {
2894 return 0;
2896 return ($itema > $itemb) ? +1 : -1;
2901 * Stores one tab
2903 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2904 * @package core
2906 class tabobject implements renderable {
2907 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
2908 var $id;
2909 /** @var moodle_url|string link */
2910 var $link;
2911 /** @var string text on the tab */
2912 var $text;
2913 /** @var string title under the link, by defaul equals to text */
2914 var $title;
2915 /** @var bool whether to display a link under the tab name when it's selected */
2916 var $linkedwhenselected = false;
2917 /** @var bool whether the tab is inactive */
2918 var $inactive = false;
2919 /** @var bool indicates that this tab's child is selected */
2920 var $activated = false;
2921 /** @var bool indicates that this tab is selected */
2922 var $selected = false;
2923 /** @var array stores children tabobjects */
2924 var $subtree = array();
2925 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
2926 var $level = 1;
2929 * Constructor
2931 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
2932 * @param string|moodle_url $link
2933 * @param string $text text on the tab
2934 * @param string $title title under the link, by defaul equals to text
2935 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
2937 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
2938 $this->id = $id;
2939 $this->link = $link;
2940 $this->text = $text;
2941 $this->title = $title ? $title : $text;
2942 $this->linkedwhenselected = $linkedwhenselected;
2946 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
2948 * @param string $selected the id of the selected tab (whatever row it's on),
2949 * if null marks all tabs as unselected
2950 * @return bool whether this tab is selected or contains selected tab in its subtree
2952 protected function set_selected($selected) {
2953 if ((string)$selected === (string)$this->id) {
2954 $this->selected = true;
2955 // This tab is selected. No need to travel through subtree.
2956 return true;
2958 foreach ($this->subtree as $subitem) {
2959 if ($subitem->set_selected($selected)) {
2960 // This tab has child that is selected. Mark it as activated. No need to check other children.
2961 $this->activated = true;
2962 return true;
2965 return false;
2969 * Travels through tree and finds a tab with specified id
2971 * @param string $id
2972 * @return tabtree|null
2974 public function find($id) {
2975 if ((string)$this->id === (string)$id) {
2976 return $this;
2978 foreach ($this->subtree as $tab) {
2979 if ($obj = $tab->find($id)) {
2980 return $obj;
2983 return null;
2987 * Allows to mark each tab's level in the tree before rendering.
2989 * @param int $level
2991 protected function set_level($level) {
2992 $this->level = $level;
2993 foreach ($this->subtree as $tab) {
2994 $tab->set_level($level + 1);
3000 * Stores tabs list
3002 * Example how to print a single line tabs:
3003 * $rows = array(
3004 * new tabobject(...),
3005 * new tabobject(...)
3006 * );
3007 * echo $OUTPUT->tabtree($rows, $selectedid);
3009 * Multiple row tabs may not look good on some devices but if you want to use them
3010 * you can specify ->subtree for the active tabobject.
3012 * @copyright 2013 Marina Glancy
3013 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3014 * @since Moodle 2.5
3015 * @package core
3016 * @category output
3018 class tabtree extends tabobject {
3020 * Constuctor
3022 * It is highly recommended to call constructor when list of tabs is already
3023 * populated, this way you ensure that selected and inactive tabs are located
3024 * and attribute level is set correctly.
3026 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3027 * @param string|null $selected which tab to mark as selected, all parent tabs will
3028 * automatically be marked as activated
3029 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3030 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3032 public function __construct($tabs, $selected = null, $inactive = null) {
3033 $this->subtree = $tabs;
3034 if ($selected !== null) {
3035 $this->set_selected($selected);
3037 if ($inactive !== null) {
3038 if (is_array($inactive)) {
3039 foreach ($inactive as $id) {
3040 if ($tab = $this->find($id)) {
3041 $tab->inactive = true;
3044 } else if ($tab = $this->find($inactive)) {
3045 $tab->inactive = true;
3048 $this->set_level(0);
3053 * An action menu.
3055 * This action menu component takes a series of primary and secondary actions.
3056 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
3057 * down menu.
3059 * @package core
3060 * @category output
3061 * @copyright 2013 Sam Hemelryk
3062 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3064 class action_menu implements renderable {
3067 * Top right alignment.
3069 const TL = 1;
3072 * Top right alignment.
3074 const TR = 2;
3077 * Top right alignment.
3079 const BL = 3;
3082 * Top right alignment.
3084 const BR = 4;
3087 * The instance number. This is unique to this instance of the action menu.
3088 * @var int
3090 protected $instance = 0;
3093 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
3094 * @var array
3096 protected $primaryactions = array();
3099 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
3100 * @var array
3102 protected $secondaryactions = array();
3105 * An array of attributes added to the container of the action menu.
3106 * Initialised with defaults during construction.
3107 * @var array
3109 public $attributes = array();
3111 * An array of attributes added to the container of the primary actions.
3112 * Initialised with defaults during construction.
3113 * @var array
3115 public $attributesprimary = array();
3117 * An array of attributes added to the container of the secondary actions.
3118 * Initialised with defaults during construction.
3119 * @var array
3121 public $attributessecondary = array();
3124 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
3125 * @var array
3127 public $actiontext = null;
3130 * An icon to use for the toggling the secondary menu (dropdown).
3131 * @var actionicon
3133 public $actionicon;
3136 * Any text to use for the toggling the secondary menu (dropdown).
3137 * @var menutrigger
3139 public $menutrigger = '';
3142 * Place the action menu before all other actions.
3143 * @var prioritise
3145 public $prioritise = false;
3148 * Constructs the action menu with the given items.
3150 * @param array $actions An array of actions.
3152 public function __construct(array $actions = array()) {
3153 static $initialised = 0;
3154 $this->instance = $initialised;
3155 $initialised++;
3157 $this->attributes = array(
3158 'id' => 'action-menu-'.$this->instance,
3159 'class' => 'moodle-actionmenu',
3160 'data-enhance' => 'moodle-core-actionmenu'
3162 $this->attributesprimary = array(
3163 'id' => 'action-menu-'.$this->instance.'-menubar',
3164 'class' => 'menubar',
3165 'role' => 'menubar'
3167 $this->attributessecondary = array(
3168 'id' => 'action-menu-'.$this->instance.'-menu',
3169 'class' => 'menu',
3170 'data-rel' => 'menu-content',
3171 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
3172 'role' => 'menu'
3174 $this->set_alignment(self::TR, self::BR);
3175 foreach ($actions as $action) {
3176 $this->add($action);
3180 public function set_menu_trigger($trigger) {
3181 $this->menutrigger = $trigger;
3185 * Initialises JS required fore the action menu.
3186 * The JS is only required once as it manages all action menu's on the page.
3188 * @param moodle_page $page
3190 public function initialise_js(moodle_page $page) {
3191 static $initialised = false;
3192 if (!$initialised) {
3193 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
3194 $initialised = true;
3199 * Adds an action to this action menu.
3201 * @param action_menu_link|pix_icon|string $action
3203 public function add($action) {
3204 if ($action instanceof action_link) {
3205 if ($action->primary) {
3206 $this->add_primary_action($action);
3207 } else {
3208 $this->add_secondary_action($action);
3210 } else if ($action instanceof pix_icon) {
3211 $this->add_primary_action($action);
3212 } else {
3213 $this->add_secondary_action($action);
3218 * Adds a primary action to the action menu.
3220 * @param action_menu_link|action_link|pix_icon|string $action
3222 public function add_primary_action($action) {
3223 if ($action instanceof action_link || $action instanceof pix_icon) {
3224 $action->attributes['role'] = 'menuitem';
3225 if ($action instanceof action_menu_link) {
3226 $action->actionmenu = $this;
3229 $this->primaryactions[] = $action;
3233 * Adds a secondary action to the action menu.
3235 * @param action_link|pix_icon|string $action
3237 public function add_secondary_action($action) {
3238 if ($action instanceof action_link || $action instanceof pix_icon) {
3239 $action->attributes['role'] = 'menuitem';
3240 if ($action instanceof action_menu_link) {
3241 $action->actionmenu = $this;
3244 $this->secondaryactions[] = $action;
3248 * Returns the primary actions ready to be rendered.
3250 * @param core_renderer $output The renderer to use for getting icons.
3251 * @return array
3253 public function get_primary_actions(core_renderer $output = null) {
3254 global $OUTPUT;
3255 if ($output === null) {
3256 $output = $OUTPUT;
3258 $pixicon = $this->actionicon;
3259 $linkclasses = array('toggle-display');
3261 $title = '';
3262 if (!empty($this->menutrigger)) {
3263 $pixicon = '<b class="caret"></b>';
3264 $linkclasses[] = 'textmenu';
3265 } else {
3266 $title = new lang_string('actions', 'moodle');
3267 $this->actionicon = new pix_icon(
3268 't/edit_menu',
3270 'moodle',
3271 array('class' => 'iconsmall actionmenu', 'title' => '')
3273 $pixicon = $this->actionicon;
3275 if ($pixicon instanceof renderable) {
3276 $pixicon = $output->render($pixicon);
3277 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
3278 $title = $pixicon->attributes['alt'];
3281 $string = '';
3282 if ($this->actiontext) {
3283 $string = $this->actiontext;
3285 $actions = $this->primaryactions;
3286 $attributes = array(
3287 'class' => implode(' ', $linkclasses),
3288 'title' => $title,
3289 'id' => 'action-menu-toggle-'.$this->instance,
3290 'role' => 'menuitem'
3292 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
3293 if ($this->prioritise) {
3294 array_unshift($actions, $link);
3295 } else {
3296 $actions[] = $link;
3298 return $actions;
3302 * Returns the secondary actions ready to be rendered.
3303 * @return array
3305 public function get_secondary_actions() {
3306 return $this->secondaryactions;
3310 * Sets the selector that should be used to find the owning node of this menu.
3311 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
3313 public function set_owner_selector($selector) {
3314 $this->attributes['data-owner'] = $selector;
3318 * Sets the alignment of the dialogue in relation to button used to toggle it.
3320 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3321 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3323 public function set_alignment($dialogue, $button) {
3324 if (isset($this->attributessecondary['data-align'])) {
3325 // We've already got one set, lets remove the old class so as to avoid troubles.
3326 $class = $this->attributessecondary['class'];
3327 $search = 'align-'.$this->attributessecondary['data-align'];
3328 $this->attributessecondary['class'] = str_replace($search, '', $class);
3330 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
3331 $this->attributessecondary['data-align'] = $align;
3332 $this->attributessecondary['class'] .= ' align-'.$align;
3336 * Returns a string to describe the alignment.
3338 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3339 * @return string
3341 protected function get_align_string($align) {
3342 switch ($align) {
3343 case self::TL :
3344 return 'tl';
3345 case self::TR :
3346 return 'tr';
3347 case self::BL :
3348 return 'bl';
3349 case self::BR :
3350 return 'br';
3351 default :
3352 return 'tl';
3357 * Sets a constraint for the dialogue.
3359 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
3360 * element the constraint identifies.
3362 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
3364 public function set_constraint($ancestorselector) {
3365 $this->attributessecondary['data-constraint'] = $ancestorselector;
3369 * If you call this method the action menu will be displayed but will not be enhanced.
3371 * By not displaying the menu enhanced all items will be displayed in a single row.
3373 public function do_not_enhance() {
3374 unset($this->attributes['data-enhance']);
3378 * Returns true if this action menu will be enhanced.
3380 * @return bool
3382 public function will_be_enhanced() {
3383 return isset($this->attributes['data-enhance']);
3388 * An action menu filler
3390 * @package core
3391 * @category output
3392 * @copyright 2013 Andrew Nicols
3393 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3395 class action_menu_filler extends action_link implements renderable {
3398 * True if this is a primary action. False if not.
3399 * @var bool
3401 public $primary = true;
3404 * Constructs the object.
3406 public function __construct() {
3411 * An action menu action
3413 * @package core
3414 * @category output
3415 * @copyright 2013 Sam Hemelryk
3416 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3418 class action_menu_link extends action_link implements renderable {
3421 * True if this is a primary action. False if not.
3422 * @var bool
3424 public $primary = true;
3427 * The action menu this link has been added to.
3428 * @var action_menu
3430 public $actionmenu = null;
3433 * Constructs the object.
3435 * @param moodle_url $url The URL for the action.
3436 * @param pix_icon $icon The icon to represent the action.
3437 * @param string $text The text to represent the action.
3438 * @param bool $primary Whether this is a primary action or not.
3439 * @param array $attributes Any attribtues associated with the action.
3441 public function __construct(moodle_url $url, pix_icon $icon = null, $text, $primary = true, array $attributes = array()) {
3442 parent::__construct($url, $text, null, $attributes, $icon);
3443 $this->primary = (bool)$primary;
3444 $this->add_class('menu-action');
3445 $this->attributes['role'] = 'menuitem';
3450 * A primary action menu action
3452 * @package core
3453 * @category output
3454 * @copyright 2013 Sam Hemelryk
3455 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3457 class action_menu_link_primary extends action_menu_link {
3459 * Constructs the object.
3461 * @param moodle_url $url
3462 * @param pix_icon $icon
3463 * @param string $text
3464 * @param array $attributes
3466 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
3467 parent::__construct($url, $icon, $text, true, $attributes);
3472 * A secondary action menu action
3474 * @package core
3475 * @category output
3476 * @copyright 2013 Sam Hemelryk
3477 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3479 class action_menu_link_secondary extends action_menu_link {
3481 * Constructs the object.
3483 * @param moodle_url $url
3484 * @param pix_icon $icon
3485 * @param string $text
3486 * @param array $attributes
3488 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
3489 parent::__construct($url, $icon, $text, false, $attributes);