MDL-48804 core: do not set current course until login validated
[moodle.git] / lib / outputcomponents.php
blob6287849ea97891ae686ea0c398bbfeb5233df591
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::start_tag('tr');
1585 $output .= html_writer::start_tag('td', array('colspan' => $countcols));
1586 $output .= html_writer::tag('div', '', array('class' => 'tabledivider'));
1587 $output .= html_writer::end_tag('td');
1588 $output .= html_writer::end_tag('tr') . "\n";
1589 } else {
1590 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
1591 if (!($row instanceof html_table_row)) {
1592 $newrow = new html_table_row();
1594 foreach ($row as $cell) {
1595 if (!($cell instanceof html_table_cell)) {
1596 $cell = new html_table_cell($cell);
1598 $newrow->cells[] = $cell;
1600 $row = $newrow;
1603 $oddeven = $oddeven ? 0 : 1;
1604 if (isset($table->rowclasses[$key])) {
1605 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
1608 $row->attributes['class'] .= ' r' . $oddeven;
1609 if ($key == $lastrowkey) {
1610 $row->attributes['class'] .= ' lastrow';
1613 $output .= html_writer::start_tag('tr', array('class' => trim($row->attributes['class']), 'style' => $row->style, 'id' => $row->id)) . "\n";
1614 $keys2 = array_keys($row->cells);
1615 $lastkey = end($keys2);
1617 $gotlastkey = false; //flag for sanity checking
1618 foreach ($row->cells as $key => $cell) {
1619 if ($gotlastkey) {
1620 //This should never happen. Why do we have a cell after the last cell?
1621 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
1624 if (!($cell instanceof html_table_cell)) {
1625 $mycell = new html_table_cell();
1626 $mycell->text = $cell;
1627 $cell = $mycell;
1630 if (($cell->header === true) && empty($cell->scope)) {
1631 $cell->scope = 'row';
1634 if (isset($table->colclasses[$key])) {
1635 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
1638 $cell->attributes['class'] .= ' cell c' . $key;
1639 if ($key == $lastkey) {
1640 $cell->attributes['class'] .= ' lastcol';
1641 $gotlastkey = true;
1643 $tdstyle = '';
1644 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
1645 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
1646 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
1647 $cell->attributes['class'] = trim($cell->attributes['class']);
1648 $tdattributes = array_merge($cell->attributes, array(
1649 'style' => $tdstyle . $cell->style,
1650 'colspan' => $cell->colspan,
1651 'rowspan' => $cell->rowspan,
1652 'id' => $cell->id,
1653 'abbr' => $cell->abbr,
1654 'scope' => $cell->scope,
1656 $tagtype = 'td';
1657 if ($cell->header === true) {
1658 $tagtype = 'th';
1660 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
1662 $output .= html_writer::end_tag('tr') . "\n";
1665 $output .= html_writer::end_tag('tbody') . "\n";
1667 $output .= html_writer::end_tag('table') . "\n";
1669 return $output;
1673 * Renders form element label
1675 * By default, the label is suffixed with a label separator defined in the
1676 * current language pack (colon by default in the English lang pack).
1677 * Adding the colon can be explicitly disabled if needed. Label separators
1678 * are put outside the label tag itself so they are not read by
1679 * screenreaders (accessibility).
1681 * Parameter $for explicitly associates the label with a form control. When
1682 * set, the value of this attribute must be the same as the value of
1683 * the id attribute of the form control in the same document. When null,
1684 * the label being defined is associated with the control inside the label
1685 * element.
1687 * @param string $text content of the label tag
1688 * @param string|null $for id of the element this label is associated with, null for no association
1689 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
1690 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
1691 * @return string HTML of the label element
1693 public static function label($text, $for, $colonize = true, array $attributes=array()) {
1694 if (!is_null($for)) {
1695 $attributes = array_merge($attributes, array('for' => $for));
1697 $text = trim($text);
1698 $label = self::tag('label', $text, $attributes);
1700 // TODO MDL-12192 $colonize disabled for now yet
1701 // if (!empty($text) and $colonize) {
1702 // // the $text may end with the colon already, though it is bad string definition style
1703 // $colon = get_string('labelsep', 'langconfig');
1704 // if (!empty($colon)) {
1705 // $trimmed = trim($colon);
1706 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
1707 // //debugging('The label text should not end with colon or other label separator,
1708 // // please fix the string definition.', DEBUG_DEVELOPER);
1709 // } else {
1710 // $label .= $colon;
1711 // }
1712 // }
1713 // }
1715 return $label;
1719 * Combines a class parameter with other attributes. Aids in code reduction
1720 * because the class parameter is very frequently used.
1722 * If the class attribute is specified both in the attributes and in the
1723 * class parameter, the two values are combined with a space between.
1725 * @param string $class Optional CSS class (or classes as space-separated list)
1726 * @param array $attributes Optional other attributes as array
1727 * @return array Attributes (or null if still none)
1729 private static function add_class($class = '', array $attributes = null) {
1730 if ($class !== '') {
1731 $classattribute = array('class' => $class);
1732 if ($attributes) {
1733 if (array_key_exists('class', $attributes)) {
1734 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
1735 } else {
1736 $attributes = $classattribute + $attributes;
1738 } else {
1739 $attributes = $classattribute;
1742 return $attributes;
1746 * Creates a <div> tag. (Shortcut function.)
1748 * @param string $content HTML content of tag
1749 * @param string $class Optional CSS class (or classes as space-separated list)
1750 * @param array $attributes Optional other attributes as array
1751 * @return string HTML code for div
1753 public static function div($content, $class = '', array $attributes = null) {
1754 return self::tag('div', $content, self::add_class($class, $attributes));
1758 * Starts a <div> tag. (Shortcut function.)
1760 * @param string $class Optional CSS class (or classes as space-separated list)
1761 * @param array $attributes Optional other attributes as array
1762 * @return string HTML code for open div tag
1764 public static function start_div($class = '', array $attributes = null) {
1765 return self::start_tag('div', self::add_class($class, $attributes));
1769 * Ends a <div> tag. (Shortcut function.)
1771 * @return string HTML code for close div tag
1773 public static function end_div() {
1774 return self::end_tag('div');
1778 * Creates a <span> tag. (Shortcut function.)
1780 * @param string $content HTML content of tag
1781 * @param string $class Optional CSS class (or classes as space-separated list)
1782 * @param array $attributes Optional other attributes as array
1783 * @return string HTML code for span
1785 public static function span($content, $class = '', array $attributes = null) {
1786 return self::tag('span', $content, self::add_class($class, $attributes));
1790 * Starts a <span> tag. (Shortcut function.)
1792 * @param string $class Optional CSS class (or classes as space-separated list)
1793 * @param array $attributes Optional other attributes as array
1794 * @return string HTML code for open span tag
1796 public static function start_span($class = '', array $attributes = null) {
1797 return self::start_tag('span', self::add_class($class, $attributes));
1801 * Ends a <span> tag. (Shortcut function.)
1803 * @return string HTML code for close span tag
1805 public static function end_span() {
1806 return self::end_tag('span');
1811 * Simple javascript output class
1813 * @copyright 2010 Petr Skoda
1814 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1815 * @since Moodle 2.0
1816 * @package core
1817 * @category output
1819 class js_writer {
1822 * Returns javascript code calling the function
1824 * @param string $function function name, can be complex like Y.Event.purgeElement
1825 * @param array $arguments parameters
1826 * @param int $delay execution delay in seconds
1827 * @return string JS code fragment
1829 public static function function_call($function, array $arguments = null, $delay=0) {
1830 if ($arguments) {
1831 $arguments = array_map('json_encode', convert_to_array($arguments));
1832 $arguments = implode(', ', $arguments);
1833 } else {
1834 $arguments = '';
1836 $js = "$function($arguments);";
1838 if ($delay) {
1839 $delay = $delay * 1000; // in miliseconds
1840 $js = "setTimeout(function() { $js }, $delay);";
1842 return $js . "\n";
1846 * Special function which adds Y as first argument of function call.
1848 * @param string $function The function to call
1849 * @param array $extraarguments Any arguments to pass to it
1850 * @return string Some JS code
1852 public static function function_call_with_Y($function, array $extraarguments = null) {
1853 if ($extraarguments) {
1854 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
1855 $arguments = 'Y, ' . implode(', ', $extraarguments);
1856 } else {
1857 $arguments = 'Y';
1859 return "$function($arguments);\n";
1863 * Returns JavaScript code to initialise a new object
1865 * @param string $var If it is null then no var is assigned the new object.
1866 * @param string $class The class to initialise an object for.
1867 * @param array $arguments An array of args to pass to the init method.
1868 * @param array $requirements Any modules required for this class.
1869 * @param int $delay The delay before initialisation. 0 = no delay.
1870 * @return string Some JS code
1872 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
1873 if (is_array($arguments)) {
1874 $arguments = array_map('json_encode', convert_to_array($arguments));
1875 $arguments = implode(', ', $arguments);
1878 if ($var === null) {
1879 $js = "new $class(Y, $arguments);";
1880 } else if (strpos($var, '.')!==false) {
1881 $js = "$var = new $class(Y, $arguments);";
1882 } else {
1883 $js = "var $var = new $class(Y, $arguments);";
1886 if ($delay) {
1887 $delay = $delay * 1000; // in miliseconds
1888 $js = "setTimeout(function() { $js }, $delay);";
1891 if (count($requirements) > 0) {
1892 $requirements = implode("', '", $requirements);
1893 $js = "Y.use('$requirements', function(Y){ $js });";
1895 return $js."\n";
1899 * Returns code setting value to variable
1901 * @param string $name
1902 * @param mixed $value json serialised value
1903 * @param bool $usevar add var definition, ignored for nested properties
1904 * @return string JS code fragment
1906 public static function set_variable($name, $value, $usevar = true) {
1907 $output = '';
1909 if ($usevar) {
1910 if (strpos($name, '.')) {
1911 $output .= '';
1912 } else {
1913 $output .= 'var ';
1917 $output .= "$name = ".json_encode($value).";";
1919 return $output;
1923 * Writes event handler attaching code
1925 * @param array|string $selector standard YUI selector for elements, may be
1926 * array or string, element id is in the form "#idvalue"
1927 * @param string $event A valid DOM event (click, mousedown, change etc.)
1928 * @param string $function The name of the function to call
1929 * @param array $arguments An optional array of argument parameters to pass to the function
1930 * @return string JS code fragment
1932 public static function event_handler($selector, $event, $function, array $arguments = null) {
1933 $selector = json_encode($selector);
1934 $output = "Y.on('$event', $function, $selector, null";
1935 if (!empty($arguments)) {
1936 $output .= ', ' . json_encode($arguments);
1938 return $output . ");\n";
1943 * Holds all the information required to render a <table> by {@link core_renderer::table()}
1945 * Example of usage:
1946 * $t = new html_table();
1947 * ... // set various properties of the object $t as described below
1948 * echo html_writer::table($t);
1950 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
1951 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1952 * @since Moodle 2.0
1953 * @package core
1954 * @category output
1956 class html_table {
1959 * @var string Value to use for the id attribute of the table
1961 public $id = null;
1964 * @var array Attributes of HTML attributes for the <table> element
1966 public $attributes = array();
1969 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
1970 * For more control over the rendering of the headers, an array of html_table_cell objects
1971 * can be passed instead of an array of strings.
1973 * Example of usage:
1974 * $t->head = array('Student', 'Grade');
1976 public $head;
1979 * @var array An array that can be used to make a heading span multiple columns.
1980 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
1981 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
1983 * Example of usage:
1984 * $t->headspan = array(2,1);
1986 public $headspan;
1989 * @var array An array of column alignments.
1990 * The value is used as CSS 'text-align' property. Therefore, possible
1991 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
1992 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
1994 * Examples of usage:
1995 * $t->align = array(null, 'right');
1996 * or
1997 * $t->align[1] = 'right';
1999 public $align;
2002 * @var array The value is used as CSS 'size' property.
2004 * Examples of usage:
2005 * $t->size = array('50%', '50%');
2006 * or
2007 * $t->size[1] = '120px';
2009 public $size;
2012 * @var array An array of wrapping information.
2013 * The only possible value is 'nowrap' that sets the
2014 * CSS property 'white-space' to the value 'nowrap' in the given column.
2016 * Example of usage:
2017 * $t->wrap = array(null, 'nowrap');
2019 public $wrap;
2022 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2023 * $head specified, the string 'hr' (for horizontal ruler) can be used
2024 * instead of an array of cells data resulting in a divider rendered.
2026 * Example of usage with array of arrays:
2027 * $row1 = array('Harry Potter', '76 %');
2028 * $row2 = array('Hermione Granger', '100 %');
2029 * $t->data = array($row1, $row2);
2031 * Example with array of html_table_row objects: (used for more fine-grained control)
2032 * $cell1 = new html_table_cell();
2033 * $cell1->text = 'Harry Potter';
2034 * $cell1->colspan = 2;
2035 * $row1 = new html_table_row();
2036 * $row1->cells[] = $cell1;
2037 * $cell2 = new html_table_cell();
2038 * $cell2->text = 'Hermione Granger';
2039 * $cell3 = new html_table_cell();
2040 * $cell3->text = '100 %';
2041 * $row2 = new html_table_row();
2042 * $row2->cells = array($cell2, $cell3);
2043 * $t->data = array($row1, $row2);
2045 public $data;
2048 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2049 * @var string Width of the table, percentage of the page preferred.
2051 public $width = null;
2054 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2055 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2057 public $tablealign = null;
2060 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2061 * @var int Padding on each cell, in pixels
2063 public $cellpadding = null;
2066 * @var int Spacing between cells, in pixels
2067 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2069 public $cellspacing = null;
2072 * @var array Array of classes to add to particular rows, space-separated string.
2073 * Classes 'r0' or 'r1' are added automatically for every odd or even row,
2074 * respectively. Class 'lastrow' is added automatically for the last row
2075 * in the table.
2077 * Example of usage:
2078 * $t->rowclasses[9] = 'tenth'
2080 public $rowclasses;
2083 * @var array An array of classes to add to every cell in a particular column,
2084 * space-separated string. Class 'cell' is added automatically by the renderer.
2085 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2086 * respectively. Class 'lastcol' is added automatically for all last cells
2087 * in a row.
2089 * Example of usage:
2090 * $t->colclasses = array(null, 'grade');
2092 public $colclasses;
2095 * @var string Description of the contents for screen readers.
2097 public $summary;
2100 * Constructor
2102 public function __construct() {
2103 $this->attributes['class'] = '';
2108 * Component representing a table row.
2110 * @copyright 2009 Nicolas Connault
2111 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2112 * @since Moodle 2.0
2113 * @package core
2114 * @category output
2116 class html_table_row {
2119 * @var string Value to use for the id attribute of the row.
2121 public $id = null;
2124 * @var array Array of html_table_cell objects
2126 public $cells = array();
2129 * @var string Value to use for the style attribute of the table row
2131 public $style = null;
2134 * @var array Attributes of additional HTML attributes for the <tr> element
2136 public $attributes = array();
2139 * Constructor
2140 * @param array $cells
2142 public function __construct(array $cells=null) {
2143 $this->attributes['class'] = '';
2144 $cells = (array)$cells;
2145 foreach ($cells as $cell) {
2146 if ($cell instanceof html_table_cell) {
2147 $this->cells[] = $cell;
2148 } else {
2149 $this->cells[] = new html_table_cell($cell);
2156 * Component representing a table cell.
2158 * @copyright 2009 Nicolas Connault
2159 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2160 * @since Moodle 2.0
2161 * @package core
2162 * @category output
2164 class html_table_cell {
2167 * @var string Value to use for the id attribute of the cell.
2169 public $id = null;
2172 * @var string The contents of the cell.
2174 public $text;
2177 * @var string Abbreviated version of the contents of the cell.
2179 public $abbr = null;
2182 * @var int Number of columns this cell should span.
2184 public $colspan = null;
2187 * @var int Number of rows this cell should span.
2189 public $rowspan = null;
2192 * @var string Defines a way to associate header cells and data cells in a table.
2194 public $scope = null;
2197 * @var bool Whether or not this cell is a header cell.
2199 public $header = null;
2202 * @var string Value to use for the style attribute of the table cell
2204 public $style = null;
2207 * @var array Attributes of additional HTML attributes for the <td> element
2209 public $attributes = array();
2212 * Constructs a table cell
2214 * @param string $text
2216 public function __construct($text = null) {
2217 $this->text = $text;
2218 $this->attributes['class'] = '';
2223 * Component representing a paging bar.
2225 * @copyright 2009 Nicolas Connault
2226 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2227 * @since Moodle 2.0
2228 * @package core
2229 * @category output
2231 class paging_bar implements renderable {
2234 * @var int The maximum number of pagelinks to display.
2236 public $maxdisplay = 18;
2239 * @var int The total number of entries to be pages through..
2241 public $totalcount;
2244 * @var int The page you are currently viewing.
2246 public $page;
2249 * @var int The number of entries that should be shown per page.
2251 public $perpage;
2254 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2255 * an equals sign and the page number.
2256 * If this is a moodle_url object then the pagevar param will be replaced by
2257 * the page no, for each page.
2259 public $baseurl;
2262 * @var string This is the variable name that you use for the pagenumber in your
2263 * code (ie. 'tablepage', 'blogpage', etc)
2265 public $pagevar;
2268 * @var string A HTML link representing the "previous" page.
2270 public $previouslink = null;
2273 * @var string A HTML link representing the "next" page.
2275 public $nextlink = null;
2278 * @var string A HTML link representing the first page.
2280 public $firstlink = null;
2283 * @var string A HTML link representing the last page.
2285 public $lastlink = null;
2288 * @var array An array of strings. One of them is just a string: the current page
2290 public $pagelinks = array();
2293 * Constructor paging_bar with only the required params.
2295 * @param int $totalcount The total number of entries available to be paged through
2296 * @param int $page The page you are currently viewing
2297 * @param int $perpage The number of entries that should be shown per page
2298 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2299 * @param string $pagevar name of page parameter that holds the page number
2301 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2302 $this->totalcount = $totalcount;
2303 $this->page = $page;
2304 $this->perpage = $perpage;
2305 $this->baseurl = $baseurl;
2306 $this->pagevar = $pagevar;
2310 * Prepares the paging bar for output.
2312 * This method validates the arguments set up for the paging bar and then
2313 * produces fragments of HTML to assist display later on.
2315 * @param renderer_base $output
2316 * @param moodle_page $page
2317 * @param string $target
2318 * @throws coding_exception
2320 public function prepare(renderer_base $output, moodle_page $page, $target) {
2321 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2322 throw new coding_exception('paging_bar requires a totalcount value.');
2324 if (!isset($this->page) || is_null($this->page)) {
2325 throw new coding_exception('paging_bar requires a page value.');
2327 if (empty($this->perpage)) {
2328 throw new coding_exception('paging_bar requires a perpage value.');
2330 if (empty($this->baseurl)) {
2331 throw new coding_exception('paging_bar requires a baseurl value.');
2334 if ($this->totalcount > $this->perpage) {
2335 $pagenum = $this->page - 1;
2337 if ($this->page > 0) {
2338 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2341 if ($this->perpage > 0) {
2342 $lastpage = ceil($this->totalcount / $this->perpage);
2343 } else {
2344 $lastpage = 1;
2347 if ($this->page > round(($this->maxdisplay/3)*2)) {
2348 $currpage = $this->page - round($this->maxdisplay/3);
2350 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2351 } else {
2352 $currpage = 0;
2355 $displaycount = $displaypage = 0;
2357 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2358 $displaypage = $currpage + 1;
2360 if ($this->page == $currpage) {
2361 $this->pagelinks[] = html_writer::span($displaypage, 'current-page');
2362 } else {
2363 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2364 $this->pagelinks[] = $pagelink;
2367 $displaycount++;
2368 $currpage++;
2371 if ($currpage < $lastpage) {
2372 $lastpageactual = $lastpage - 1;
2373 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2376 $pagenum = $this->page + 1;
2378 if ($pagenum != $displaypage) {
2379 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2386 * This class represents how a block appears on a page.
2388 * During output, each block instance is asked to return a block_contents object,
2389 * those are then passed to the $OUTPUT->block function for display.
2391 * contents should probably be generated using a moodle_block_..._renderer.
2393 * Other block-like things that need to appear on the page, for example the
2394 * add new block UI, are also represented as block_contents objects.
2396 * @copyright 2009 Tim Hunt
2397 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2398 * @since Moodle 2.0
2399 * @package core
2400 * @category output
2402 class block_contents {
2404 /** Used when the block cannot be collapsed **/
2405 const NOT_HIDEABLE = 0;
2407 /** Used when the block can be collapsed but currently is not **/
2408 const VISIBLE = 1;
2410 /** Used when the block has been collapsed **/
2411 const HIDDEN = 2;
2414 * @var int Used to set $skipid.
2416 protected static $idcounter = 1;
2419 * @var int All the blocks (or things that look like blocks) printed on
2420 * a page are given a unique number that can be used to construct id="" attributes.
2421 * This is set automatically be the {@link prepare()} method.
2422 * Do not try to set it manually.
2424 public $skipid;
2427 * @var int If this is the contents of a real block, this should be set
2428 * to the block_instance.id. Otherwise this should be set to 0.
2430 public $blockinstanceid = 0;
2433 * @var int If this is a real block instance, and there is a corresponding
2434 * block_position.id for the block on this page, this should be set to that id.
2435 * Otherwise it should be 0.
2437 public $blockpositionid = 0;
2440 * @var array An array of attribute => value pairs that are put on the outer div of this
2441 * block. {@link $id} and {@link $classes} attributes should be set separately.
2443 public $attributes;
2446 * @var string The title of this block. If this came from user input, it should already
2447 * have had format_string() processing done on it. This will be output inside
2448 * <h2> tags. Please do not cause invalid XHTML.
2450 public $title = '';
2453 * @var string The label to use when the block does not, or will not have a visible title.
2454 * You should never set this as well as title... it will just be ignored.
2456 public $arialabel = '';
2459 * @var string HTML for the content
2461 public $content = '';
2464 * @var array An alternative to $content, it you want a list of things with optional icons.
2466 public $footer = '';
2469 * @var string Any small print that should appear under the block to explain
2470 * to the teacher about the block, for example 'This is a sticky block that was
2471 * added in the system context.'
2473 public $annotation = '';
2476 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
2477 * the user can toggle whether this block is visible.
2479 public $collapsible = self::NOT_HIDEABLE;
2482 * Set this to true if the block is dockable.
2483 * @var bool
2485 public $dockable = false;
2488 * @var array A (possibly empty) array of editing controls. Each element of
2489 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
2490 * $icon is the icon name. Fed to $OUTPUT->pix_url.
2492 public $controls = array();
2496 * Create new instance of block content
2497 * @param array $attributes
2499 public function __construct(array $attributes = null) {
2500 $this->skipid = self::$idcounter;
2501 self::$idcounter += 1;
2503 if ($attributes) {
2504 // standard block
2505 $this->attributes = $attributes;
2506 } else {
2507 // simple "fake" blocks used in some modules and "Add new block" block
2508 $this->attributes = array('class'=>'block');
2513 * Add html class to block
2515 * @param string $class
2517 public function add_class($class) {
2518 $this->attributes['class'] .= ' '.$class;
2524 * This class represents a target for where a block can go when it is being moved.
2526 * This needs to be rendered as a form with the given hidden from fields, and
2527 * clicking anywhere in the form should submit it. The form action should be
2528 * $PAGE->url.
2530 * @copyright 2009 Tim Hunt
2531 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2532 * @since Moodle 2.0
2533 * @package core
2534 * @category output
2536 class block_move_target {
2539 * @var moodle_url Move url
2541 public $url;
2544 * Constructor
2545 * @param moodle_url $url
2547 public function __construct(moodle_url $url) {
2548 $this->url = $url;
2553 * Custom menu item
2555 * This class is used to represent one item within a custom menu that may or may
2556 * not have children.
2558 * @copyright 2010 Sam Hemelryk
2559 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2560 * @since Moodle 2.0
2561 * @package core
2562 * @category output
2564 class custom_menu_item implements renderable {
2567 * @var string The text to show for the item
2569 protected $text;
2572 * @var moodle_url The link to give the icon if it has no children
2574 protected $url;
2577 * @var string A title to apply to the item. By default the text
2579 protected $title;
2582 * @var int A sort order for the item, not necessary if you order things in
2583 * the CFG var.
2585 protected $sort;
2588 * @var custom_menu_item A reference to the parent for this item or NULL if
2589 * it is a top level item
2591 protected $parent;
2594 * @var array A array in which to store children this item has.
2596 protected $children = array();
2599 * @var int A reference to the sort var of the last child that was added
2601 protected $lastsort = 0;
2604 * Constructs the new custom menu item
2606 * @param string $text
2607 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
2608 * @param string $title A title to apply to this item [Optional]
2609 * @param int $sort A sort or to use if we need to sort differently [Optional]
2610 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
2611 * belongs to, only if the child has a parent. [Optional]
2613 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
2614 $this->text = $text;
2615 $this->url = $url;
2616 $this->title = $title;
2617 $this->sort = (int)$sort;
2618 $this->parent = $parent;
2622 * Adds a custom menu item as a child of this node given its properties.
2624 * @param string $text
2625 * @param moodle_url $url
2626 * @param string $title
2627 * @param int $sort
2628 * @return custom_menu_item
2630 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
2631 $key = count($this->children);
2632 if (empty($sort)) {
2633 $sort = $this->lastsort + 1;
2635 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
2636 $this->lastsort = (int)$sort;
2637 return $this->children[$key];
2641 * Returns the text for this item
2642 * @return string
2644 public function get_text() {
2645 return $this->text;
2649 * Returns the url for this item
2650 * @return moodle_url
2652 public function get_url() {
2653 return $this->url;
2657 * Returns the title for this item
2658 * @return string
2660 public function get_title() {
2661 return $this->title;
2665 * Sorts and returns the children for this item
2666 * @return array
2668 public function get_children() {
2669 $this->sort();
2670 return $this->children;
2674 * Gets the sort order for this child
2675 * @return int
2677 public function get_sort_order() {
2678 return $this->sort;
2682 * Gets the parent this child belong to
2683 * @return custom_menu_item
2685 public function get_parent() {
2686 return $this->parent;
2690 * Sorts the children this item has
2692 public function sort() {
2693 usort($this->children, array('custom_menu','sort_custom_menu_items'));
2697 * Returns true if this item has any children
2698 * @return bool
2700 public function has_children() {
2701 return (count($this->children) > 0);
2705 * Sets the text for the node
2706 * @param string $text
2708 public function set_text($text) {
2709 $this->text = (string)$text;
2713 * Sets the title for the node
2714 * @param string $title
2716 public function set_title($title) {
2717 $this->title = (string)$title;
2721 * Sets the url for the node
2722 * @param moodle_url $url
2724 public function set_url(moodle_url $url) {
2725 $this->url = $url;
2730 * Custom menu class
2732 * This class is used to operate a custom menu that can be rendered for the page.
2733 * The custom menu is built using $CFG->custommenuitems and is a structured collection
2734 * of custom_menu_item nodes that can be rendered by the core renderer.
2736 * To configure the custom menu:
2737 * Settings: Administration > Appearance > Themes > Theme settings
2739 * @copyright 2010 Sam Hemelryk
2740 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2741 * @since Moodle 2.0
2742 * @package core
2743 * @category output
2745 class custom_menu extends custom_menu_item {
2748 * @var string The language we should render for, null disables multilang support.
2750 protected $currentlanguage = null;
2753 * Creates the custom menu
2755 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
2756 * @param string $currentlanguage the current language code, null disables multilang support
2758 public function __construct($definition = '', $currentlanguage = null) {
2759 $this->currentlanguage = $currentlanguage;
2760 parent::__construct('root'); // create virtual root element of the menu
2761 if (!empty($definition)) {
2762 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
2767 * Overrides the children of this custom menu. Useful when getting children
2768 * from $CFG->custommenuitems
2770 * @param array $children
2772 public function override_children(array $children) {
2773 $this->children = array();
2774 foreach ($children as $child) {
2775 if ($child instanceof custom_menu_item) {
2776 $this->children[] = $child;
2782 * Converts a string into a structured array of custom_menu_items which can
2783 * then be added to a custom menu.
2785 * Structure:
2786 * text|url|title|langs
2787 * The number of hyphens at the start determines the depth of the item. The
2788 * languages are optional, comma separated list of languages the line is for.
2790 * Example structure:
2791 * First level first item|http://www.moodle.com/
2792 * -Second level first item|http://www.moodle.com/partners/
2793 * -Second level second item|http://www.moodle.com/hq/
2794 * --Third level first item|http://www.moodle.com/jobs/
2795 * -Second level third item|http://www.moodle.com/development/
2796 * First level second item|http://www.moodle.com/feedback/
2797 * First level third item
2798 * English only|http://moodle.com|English only item|en
2799 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
2802 * @static
2803 * @param string $text the menu items definition
2804 * @param string $language the language code, null disables multilang support
2805 * @return array
2807 public static function convert_text_to_menu_nodes($text, $language = null) {
2808 $lines = explode("\n", $text);
2809 $children = array();
2810 $lastchild = null;
2811 $lastdepth = null;
2812 $lastsort = 0;
2813 foreach ($lines as $line) {
2814 $line = trim($line);
2815 $bits = explode('|', $line, 4); // name|url|title|langs
2816 if (!array_key_exists(0, $bits) or empty($bits[0])) {
2817 // Every item must have a name to be valid
2818 continue;
2819 } else {
2820 $bits[0] = ltrim($bits[0],'-');
2822 if (!array_key_exists(1, $bits) or empty($bits[1])) {
2823 // Set the url to null
2824 $bits[1] = null;
2825 } else {
2826 // Make sure the url is a moodle url
2827 try {
2828 $bits[1] = new moodle_url(trim($bits[1]));
2829 } catch (moodle_exception $exception) {
2830 // We're not actually worried about this, we don't want to mess up the display
2831 // just for a wrongly entered URL.
2832 $bits[1] = null;
2835 if (!array_key_exists(2, $bits) or empty($bits[2])) {
2836 // Set the title to null seeing as there isn't one
2837 $bits[2] = $bits[0];
2839 if (!array_key_exists(3, $bits) or empty($bits[3])) {
2840 // The item is valid for all languages
2841 $itemlangs = null;
2842 } else {
2843 $itemlangs = array_map('trim', explode(',', $bits[3]));
2845 if (!empty($language) and !empty($itemlangs)) {
2846 // check that the item is intended for the current language
2847 if (!in_array($language, $itemlangs)) {
2848 continue;
2851 // Set an incremental sort order to keep it simple.
2852 $lastsort++;
2853 if (preg_match('/^(\-*)/', $line, $match) && $lastchild != null && $lastdepth !== null) {
2854 $depth = strlen($match[1]);
2855 if ($depth < $lastdepth) {
2856 $difference = $lastdepth - $depth;
2857 if ($lastdepth > 1 && $lastdepth != $difference) {
2858 $tempchild = $lastchild->get_parent();
2859 for ($i =0; $i < $difference; $i++) {
2860 $tempchild = $tempchild->get_parent();
2862 $lastchild = $tempchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2863 } else {
2864 $depth = 0;
2865 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2866 $children[] = $lastchild;
2868 } else if ($depth > $lastdepth) {
2869 $depth = $lastdepth + 1;
2870 $lastchild = $lastchild->add($bits[0], $bits[1], $bits[2], $lastsort);
2871 } else {
2872 if ($depth == 0) {
2873 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2874 $children[] = $lastchild;
2875 } else {
2876 $lastchild = $lastchild->get_parent()->add($bits[0], $bits[1], $bits[2], $lastsort);
2879 } else {
2880 $depth = 0;
2881 $lastchild = new custom_menu_item($bits[0], $bits[1], $bits[2], $lastsort);
2882 $children[] = $lastchild;
2884 $lastdepth = $depth;
2886 return $children;
2890 * Sorts two custom menu items
2892 * This function is designed to be used with the usort method
2893 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
2895 * @static
2896 * @param custom_menu_item $itema
2897 * @param custom_menu_item $itemb
2898 * @return int
2900 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
2901 $itema = $itema->get_sort_order();
2902 $itemb = $itemb->get_sort_order();
2903 if ($itema == $itemb) {
2904 return 0;
2906 return ($itema > $itemb) ? +1 : -1;
2911 * Stores one tab
2913 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2914 * @package core
2916 class tabobject implements renderable {
2917 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
2918 var $id;
2919 /** @var moodle_url|string link */
2920 var $link;
2921 /** @var string text on the tab */
2922 var $text;
2923 /** @var string title under the link, by defaul equals to text */
2924 var $title;
2925 /** @var bool whether to display a link under the tab name when it's selected */
2926 var $linkedwhenselected = false;
2927 /** @var bool whether the tab is inactive */
2928 var $inactive = false;
2929 /** @var bool indicates that this tab's child is selected */
2930 var $activated = false;
2931 /** @var bool indicates that this tab is selected */
2932 var $selected = false;
2933 /** @var array stores children tabobjects */
2934 var $subtree = array();
2935 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
2936 var $level = 1;
2939 * Constructor
2941 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
2942 * @param string|moodle_url $link
2943 * @param string $text text on the tab
2944 * @param string $title title under the link, by defaul equals to text
2945 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
2947 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
2948 $this->id = $id;
2949 $this->link = $link;
2950 $this->text = $text;
2951 $this->title = $title ? $title : $text;
2952 $this->linkedwhenselected = $linkedwhenselected;
2956 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
2958 * @param string $selected the id of the selected tab (whatever row it's on),
2959 * if null marks all tabs as unselected
2960 * @return bool whether this tab is selected or contains selected tab in its subtree
2962 protected function set_selected($selected) {
2963 if ((string)$selected === (string)$this->id) {
2964 $this->selected = true;
2965 // This tab is selected. No need to travel through subtree.
2966 return true;
2968 foreach ($this->subtree as $subitem) {
2969 if ($subitem->set_selected($selected)) {
2970 // This tab has child that is selected. Mark it as activated. No need to check other children.
2971 $this->activated = true;
2972 return true;
2975 return false;
2979 * Travels through tree and finds a tab with specified id
2981 * @param string $id
2982 * @return tabtree|null
2984 public function find($id) {
2985 if ((string)$this->id === (string)$id) {
2986 return $this;
2988 foreach ($this->subtree as $tab) {
2989 if ($obj = $tab->find($id)) {
2990 return $obj;
2993 return null;
2997 * Allows to mark each tab's level in the tree before rendering.
2999 * @param int $level
3001 protected function set_level($level) {
3002 $this->level = $level;
3003 foreach ($this->subtree as $tab) {
3004 $tab->set_level($level + 1);
3010 * Stores tabs list
3012 * Example how to print a single line tabs:
3013 * $rows = array(
3014 * new tabobject(...),
3015 * new tabobject(...)
3016 * );
3017 * echo $OUTPUT->tabtree($rows, $selectedid);
3019 * Multiple row tabs may not look good on some devices but if you want to use them
3020 * you can specify ->subtree for the active tabobject.
3022 * @copyright 2013 Marina Glancy
3023 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3024 * @since Moodle 2.5
3025 * @package core
3026 * @category output
3028 class tabtree extends tabobject {
3030 * Constuctor
3032 * It is highly recommended to call constructor when list of tabs is already
3033 * populated, this way you ensure that selected and inactive tabs are located
3034 * and attribute level is set correctly.
3036 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3037 * @param string|null $selected which tab to mark as selected, all parent tabs will
3038 * automatically be marked as activated
3039 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3040 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3042 public function __construct($tabs, $selected = null, $inactive = null) {
3043 $this->subtree = $tabs;
3044 if ($selected !== null) {
3045 $this->set_selected($selected);
3047 if ($inactive !== null) {
3048 if (is_array($inactive)) {
3049 foreach ($inactive as $id) {
3050 if ($tab = $this->find($id)) {
3051 $tab->inactive = true;
3054 } else if ($tab = $this->find($inactive)) {
3055 $tab->inactive = true;
3058 $this->set_level(0);
3063 * An action menu.
3065 * This action menu component takes a series of primary and secondary actions.
3066 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
3067 * down menu.
3069 * @package core
3070 * @category output
3071 * @copyright 2013 Sam Hemelryk
3072 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3074 class action_menu implements renderable {
3077 * Top right alignment.
3079 const TL = 1;
3082 * Top right alignment.
3084 const TR = 2;
3087 * Top right alignment.
3089 const BL = 3;
3092 * Top right alignment.
3094 const BR = 4;
3097 * The instance number. This is unique to this instance of the action menu.
3098 * @var int
3100 protected $instance = 0;
3103 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
3104 * @var array
3106 protected $primaryactions = array();
3109 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
3110 * @var array
3112 protected $secondaryactions = array();
3115 * An array of attributes added to the container of the action menu.
3116 * Initialised with defaults during construction.
3117 * @var array
3119 public $attributes = array();
3121 * An array of attributes added to the container of the primary actions.
3122 * Initialised with defaults during construction.
3123 * @var array
3125 public $attributesprimary = array();
3127 * An array of attributes added to the container of the secondary actions.
3128 * Initialised with defaults during construction.
3129 * @var array
3131 public $attributessecondary = array();
3134 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
3135 * @var array
3137 public $actiontext = null;
3140 * An icon to use for the toggling the secondary menu (dropdown).
3141 * @var actionicon
3143 public $actionicon;
3146 * Any text to use for the toggling the secondary menu (dropdown).
3147 * @var menutrigger
3149 public $menutrigger = '';
3152 * Place the action menu before all other actions.
3153 * @var prioritise
3155 public $prioritise = false;
3158 * Constructs the action menu with the given items.
3160 * @param array $actions An array of actions.
3162 public function __construct(array $actions = array()) {
3163 static $initialised = 0;
3164 $this->instance = $initialised;
3165 $initialised++;
3167 $this->attributes = array(
3168 'id' => 'action-menu-'.$this->instance,
3169 'class' => 'moodle-actionmenu',
3170 'data-enhance' => 'moodle-core-actionmenu'
3172 $this->attributesprimary = array(
3173 'id' => 'action-menu-'.$this->instance.'-menubar',
3174 'class' => 'menubar',
3175 'role' => 'menubar'
3177 $this->attributessecondary = array(
3178 'id' => 'action-menu-'.$this->instance.'-menu',
3179 'class' => 'menu',
3180 'data-rel' => 'menu-content',
3181 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
3182 'role' => 'menu'
3184 $this->set_alignment(self::TR, self::BR);
3185 foreach ($actions as $action) {
3186 $this->add($action);
3190 public function set_menu_trigger($trigger) {
3191 $this->menutrigger = $trigger;
3195 * Initialises JS required fore the action menu.
3196 * The JS is only required once as it manages all action menu's on the page.
3198 * @param moodle_page $page
3200 public function initialise_js(moodle_page $page) {
3201 static $initialised = false;
3202 if (!$initialised) {
3203 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
3204 $initialised = true;
3209 * Adds an action to this action menu.
3211 * @param action_menu_link|pix_icon|string $action
3213 public function add($action) {
3214 if ($action instanceof action_link) {
3215 if ($action->primary) {
3216 $this->add_primary_action($action);
3217 } else {
3218 $this->add_secondary_action($action);
3220 } else if ($action instanceof pix_icon) {
3221 $this->add_primary_action($action);
3222 } else {
3223 $this->add_secondary_action($action);
3228 * Adds a primary action to the action menu.
3230 * @param action_menu_link|action_link|pix_icon|string $action
3232 public function add_primary_action($action) {
3233 if ($action instanceof action_link || $action instanceof pix_icon) {
3234 $action->attributes['role'] = 'menuitem';
3235 if ($action instanceof action_menu_link) {
3236 $action->actionmenu = $this;
3239 $this->primaryactions[] = $action;
3243 * Adds a secondary action to the action menu.
3245 * @param action_link|pix_icon|string $action
3247 public function add_secondary_action($action) {
3248 if ($action instanceof action_link || $action instanceof pix_icon) {
3249 $action->attributes['role'] = 'menuitem';
3250 if ($action instanceof action_menu_link) {
3251 $action->actionmenu = $this;
3254 $this->secondaryactions[] = $action;
3258 * Returns the primary actions ready to be rendered.
3260 * @param core_renderer $output The renderer to use for getting icons.
3261 * @return array
3263 public function get_primary_actions(core_renderer $output = null) {
3264 global $OUTPUT;
3265 if ($output === null) {
3266 $output = $OUTPUT;
3268 $pixicon = $this->actionicon;
3269 $linkclasses = array('toggle-display');
3271 $title = '';
3272 if (!empty($this->menutrigger)) {
3273 $pixicon = '<b class="caret"></b>';
3274 $linkclasses[] = 'textmenu';
3275 } else {
3276 $title = new lang_string('actions', 'moodle');
3277 $this->actionicon = new pix_icon(
3278 't/edit_menu',
3280 'moodle',
3281 array('class' => 'iconsmall actionmenu', 'title' => '')
3283 $pixicon = $this->actionicon;
3285 if ($pixicon instanceof renderable) {
3286 $pixicon = $output->render($pixicon);
3287 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
3288 $title = $pixicon->attributes['alt'];
3291 $string = '';
3292 if ($this->actiontext) {
3293 $string = $this->actiontext;
3295 $actions = $this->primaryactions;
3296 $attributes = array(
3297 'class' => implode(' ', $linkclasses),
3298 'title' => $title,
3299 'id' => 'action-menu-toggle-'.$this->instance,
3300 'role' => 'menuitem'
3302 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
3303 if ($this->prioritise) {
3304 array_unshift($actions, $link);
3305 } else {
3306 $actions[] = $link;
3308 return $actions;
3312 * Returns the secondary actions ready to be rendered.
3313 * @return array
3315 public function get_secondary_actions() {
3316 return $this->secondaryactions;
3320 * Sets the selector that should be used to find the owning node of this menu.
3321 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
3323 public function set_owner_selector($selector) {
3324 $this->attributes['data-owner'] = $selector;
3328 * Sets the alignment of the dialogue in relation to button used to toggle it.
3330 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3331 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3333 public function set_alignment($dialogue, $button) {
3334 if (isset($this->attributessecondary['data-align'])) {
3335 // We've already got one set, lets remove the old class so as to avoid troubles.
3336 $class = $this->attributessecondary['class'];
3337 $search = 'align-'.$this->attributessecondary['data-align'];
3338 $this->attributessecondary['class'] = str_replace($search, '', $class);
3340 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
3341 $this->attributessecondary['data-align'] = $align;
3342 $this->attributessecondary['class'] .= ' align-'.$align;
3346 * Returns a string to describe the alignment.
3348 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
3349 * @return string
3351 protected function get_align_string($align) {
3352 switch ($align) {
3353 case self::TL :
3354 return 'tl';
3355 case self::TR :
3356 return 'tr';
3357 case self::BL :
3358 return 'bl';
3359 case self::BR :
3360 return 'br';
3361 default :
3362 return 'tl';
3367 * Sets a constraint for the dialogue.
3369 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
3370 * element the constraint identifies.
3372 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
3374 public function set_constraint($ancestorselector) {
3375 $this->attributessecondary['data-constraint'] = $ancestorselector;
3379 * If you call this method the action menu will be displayed but will not be enhanced.
3381 * By not displaying the menu enhanced all items will be displayed in a single row.
3383 public function do_not_enhance() {
3384 unset($this->attributes['data-enhance']);
3388 * Returns true if this action menu will be enhanced.
3390 * @return bool
3392 public function will_be_enhanced() {
3393 return isset($this->attributes['data-enhance']);
3398 * An action menu filler
3400 * @package core
3401 * @category output
3402 * @copyright 2013 Andrew Nicols
3403 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3405 class action_menu_filler extends action_link implements renderable {
3408 * True if this is a primary action. False if not.
3409 * @var bool
3411 public $primary = true;
3414 * Constructs the object.
3416 public function __construct() {
3421 * An action menu action
3423 * @package core
3424 * @category output
3425 * @copyright 2013 Sam Hemelryk
3426 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3428 class action_menu_link extends action_link implements renderable {
3431 * True if this is a primary action. False if not.
3432 * @var bool
3434 public $primary = true;
3437 * The action menu this link has been added to.
3438 * @var action_menu
3440 public $actionmenu = null;
3443 * Constructs the object.
3445 * @param moodle_url $url The URL for the action.
3446 * @param pix_icon $icon The icon to represent the action.
3447 * @param string $text The text to represent the action.
3448 * @param bool $primary Whether this is a primary action or not.
3449 * @param array $attributes Any attribtues associated with the action.
3451 public function __construct(moodle_url $url, pix_icon $icon = null, $text, $primary = true, array $attributes = array()) {
3452 parent::__construct($url, $text, null, $attributes, $icon);
3453 $this->primary = (bool)$primary;
3454 $this->add_class('menu-action');
3455 $this->attributes['role'] = 'menuitem';
3460 * A primary action menu action
3462 * @package core
3463 * @category output
3464 * @copyright 2013 Sam Hemelryk
3465 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3467 class action_menu_link_primary extends action_menu_link {
3469 * Constructs the object.
3471 * @param moodle_url $url
3472 * @param pix_icon $icon
3473 * @param string $text
3474 * @param array $attributes
3476 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
3477 parent::__construct($url, $icon, $text, true, $attributes);
3482 * A secondary action menu action
3484 * @package core
3485 * @category output
3486 * @copyright 2013 Sam Hemelryk
3487 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3489 class action_menu_link_secondary extends action_menu_link {
3491 * Constructs the object.
3493 * @param moodle_url $url
3494 * @param pix_icon $icon
3495 * @param string $text
3496 * @param array $attributes
3498 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
3499 parent::__construct($url, $icon, $text, false, $attributes);