MDL-61954 gradeimport_xml: Implement privacy API
[moodle.git] / lib / outputcomponents.php
blobdb773a63e25a8a77411fca4abfdd69f5ae877151
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 * Interface marking other classes having the ability to export their data for use by templates.
45 * @copyright 2015 Damyon Wiese
46 * @package core
47 * @category output
48 * @since 2.9
50 interface templatable {
52 /**
53 * Function to export the renderer data in a format that is suitable for a
54 * mustache template. This means:
55 * 1. No complex types - only stdClass, array, int, string, float, bool
56 * 2. Any additional info that is required for the template is pre-calculated (e.g. capability checks).
58 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
59 * @return stdClass|array
61 public function export_for_template(renderer_base $output);
64 /**
65 * Data structure representing a file picker.
67 * @copyright 2010 Dongsheng Cai
68 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
69 * @since Moodle 2.0
70 * @package core
71 * @category output
73 class file_picker implements renderable {
75 /**
76 * @var stdClass An object containing options for the file picker
78 public $options;
80 /**
81 * Constructs a file picker object.
83 * The following are possible options for the filepicker:
84 * - accepted_types (*)
85 * - return_types (FILE_INTERNAL)
86 * - env (filepicker)
87 * - client_id (uniqid)
88 * - itemid (0)
89 * - maxbytes (-1)
90 * - maxfiles (1)
91 * - buttonname (false)
93 * @param stdClass $options An object containing options for the file picker.
95 public function __construct(stdClass $options) {
96 global $CFG, $USER, $PAGE;
97 require_once($CFG->dirroot. '/repository/lib.php');
98 $defaults = array(
99 'accepted_types'=>'*',
100 'return_types'=>FILE_INTERNAL,
101 'env' => 'filepicker',
102 'client_id' => uniqid(),
103 'itemid' => 0,
104 'maxbytes'=>-1,
105 'maxfiles'=>1,
106 'buttonname'=>false
108 foreach ($defaults as $key=>$value) {
109 if (empty($options->$key)) {
110 $options->$key = $value;
114 $options->currentfile = '';
115 if (!empty($options->itemid)) {
116 $fs = get_file_storage();
117 $usercontext = context_user::instance($USER->id);
118 if (empty($options->filename)) {
119 if ($files = $fs->get_area_files($usercontext->id, 'user', 'draft', $options->itemid, 'id DESC', false)) {
120 $file = reset($files);
122 } else {
123 $file = $fs->get_file($usercontext->id, 'user', 'draft', $options->itemid, $options->filepath, $options->filename);
125 if (!empty($file)) {
126 $options->currentfile = html_writer::link(moodle_url::make_draftfile_url($file->get_itemid(), $file->get_filepath(), $file->get_filename()), $file->get_filename());
130 // initilise options, getting files in root path
131 $this->options = initialise_filepicker($options);
133 // copying other options
134 foreach ($options as $name=>$value) {
135 if (!isset($this->options->$name)) {
136 $this->options->$name = $value;
143 * Data structure representing a user picture.
145 * @copyright 2009 Nicolas Connault, 2010 Petr Skoda
146 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
147 * @since Modle 2.0
148 * @package core
149 * @category output
151 class user_picture implements renderable {
153 * @var array List of mandatory fields in user record here. (do not include
154 * TEXT columns because it would break SELECT DISTINCT in MSSQL and ORACLE)
156 protected static $fields = array('id', 'picture', 'firstname', 'lastname', 'firstnamephonetic', 'lastnamephonetic',
157 'middlename', 'alternatename', 'imagealt', 'email');
160 * @var stdClass A user object with at least fields all columns specified
161 * in $fields array constant set.
163 public $user;
166 * @var int The course id. Used when constructing the link to the user's
167 * profile, page course id used if not specified.
169 public $courseid;
172 * @var bool Add course profile link to image
174 public $link = true;
177 * @var int Size in pixels. Special values are (true/1 = 100px) and
178 * (false/0 = 35px)
179 * for backward compatibility.
181 public $size = 35;
184 * @var bool Add non-blank alt-text to the image.
185 * Default true, set to false when image alt just duplicates text in screenreaders.
187 public $alttext = true;
190 * @var bool Whether or not to open the link in a popup window.
192 public $popup = false;
195 * @var string Image class attribute
197 public $class = 'userpicture';
200 * @var bool Whether to be visible to screen readers.
202 public $visibletoscreenreaders = true;
205 * @var bool Whether to include the fullname in the user picture link.
207 public $includefullname = false;
210 * User picture constructor.
212 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
213 * It is recommended to add also contextid of the user for performance reasons.
215 public function __construct(stdClass $user) {
216 global $DB;
218 if (empty($user->id)) {
219 throw new coding_exception('User id is required when printing user avatar image.');
222 // only touch the DB if we are missing data and complain loudly...
223 $needrec = false;
224 foreach (self::$fields as $field) {
225 if (!array_key_exists($field, $user)) {
226 $needrec = true;
227 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
228 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
229 break;
233 if ($needrec) {
234 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
235 } else {
236 $this->user = clone($user);
241 * Returns a list of required user fields, useful when fetching required user info from db.
243 * In some cases we have to fetch the user data together with some other information,
244 * the idalias is useful there because the id would otherwise override the main
245 * id of the result record. Please note it has to be converted back to id before rendering.
247 * @param string $tableprefix name of database table prefix in query
248 * @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)
249 * @param string $idalias alias of id field
250 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
251 * @return string
253 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
254 if (!$tableprefix and !$extrafields and !$idalias) {
255 return implode(',', self::$fields);
257 if ($tableprefix) {
258 $tableprefix .= '.';
260 foreach (self::$fields as $field) {
261 if ($field === 'id' and $idalias and $idalias !== 'id') {
262 $fields[$field] = "$tableprefix$field AS $idalias";
263 } else {
264 if ($fieldprefix and $field !== 'id') {
265 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
266 } else {
267 $fields[$field] = "$tableprefix$field";
271 // add extra fields if not already there
272 if ($extrafields) {
273 foreach ($extrafields as $e) {
274 if ($e === 'id' or isset($fields[$e])) {
275 continue;
277 if ($fieldprefix) {
278 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
279 } else {
280 $fields[$e] = "$tableprefix$e";
284 return implode(',', $fields);
288 * Extract the aliased user fields from a given record
290 * Given a record that was previously obtained using {@link self::fields()} with aliases,
291 * this method extracts user related unaliased fields.
293 * @param stdClass $record containing user picture fields
294 * @param array $extrafields extra fields included in the $record
295 * @param string $idalias alias of the id field
296 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
297 * @return stdClass object with unaliased user fields
299 public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
301 if (empty($idalias)) {
302 $idalias = 'id';
305 $return = new stdClass();
307 foreach (self::$fields as $field) {
308 if ($field === 'id') {
309 if (property_exists($record, $idalias)) {
310 $return->id = $record->{$idalias};
312 } else {
313 if (property_exists($record, $fieldprefix.$field)) {
314 $return->{$field} = $record->{$fieldprefix.$field};
318 // add extra fields if not already there
319 if ($extrafields) {
320 foreach ($extrafields as $e) {
321 if ($e === 'id' or property_exists($return, $e)) {
322 continue;
324 $return->{$e} = $record->{$fieldprefix.$e};
328 return $return;
332 * Works out the URL for the users picture.
334 * This method is recommended as it avoids costly redirects of user pictures
335 * if requests are made for non-existent files etc.
337 * @param moodle_page $page
338 * @param renderer_base $renderer
339 * @return moodle_url
341 public function get_url(moodle_page $page, renderer_base $renderer = null) {
342 global $CFG;
344 if (is_null($renderer)) {
345 $renderer = $page->get_renderer('core');
348 // Sort out the filename and size. Size is only required for the gravatar
349 // implementation presently.
350 if (empty($this->size)) {
351 $filename = 'f2';
352 $size = 35;
353 } else if ($this->size === true or $this->size == 1) {
354 $filename = 'f1';
355 $size = 100;
356 } else if ($this->size > 100) {
357 $filename = 'f3';
358 $size = (int)$this->size;
359 } else if ($this->size >= 50) {
360 $filename = 'f1';
361 $size = (int)$this->size;
362 } else {
363 $filename = 'f2';
364 $size = (int)$this->size;
367 $defaulturl = $renderer->image_url('u/'.$filename); // default image
369 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
370 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
371 // Protect images if login required and not logged in;
372 // also if login is required for profile images and is not logged in or guest
373 // do not use require_login() because it is expensive and not suitable here anyway.
374 return $defaulturl;
377 // First try to detect deleted users - but do not read from database for performance reasons!
378 if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
379 // All deleted users should have email replaced by md5 hash,
380 // all active users are expected to have valid email.
381 return $defaulturl;
384 // Did the user upload a picture?
385 if ($this->user->picture > 0) {
386 if (!empty($this->user->contextid)) {
387 $contextid = $this->user->contextid;
388 } else {
389 $context = context_user::instance($this->user->id, IGNORE_MISSING);
390 if (!$context) {
391 // This must be an incorrectly deleted user, all other users have context.
392 return $defaulturl;
394 $contextid = $context->id;
397 $path = '/';
398 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
399 // We append the theme name to the file path if we have it so that
400 // in the circumstance that the profile picture is not available
401 // when the user actually requests it they still get the profile
402 // picture for the correct theme.
403 $path .= $page->theme->name.'/';
405 // Set the image URL to the URL for the uploaded file and return.
406 $url = moodle_url::make_pluginfile_url($contextid, 'user', 'icon', NULL, $path, $filename);
407 $url->param('rev', $this->user->picture);
408 return $url;
411 if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
412 // Normalise the size variable to acceptable bounds
413 if ($size < 1 || $size > 512) {
414 $size = 35;
416 // Hash the users email address
417 $md5 = md5(strtolower(trim($this->user->email)));
418 // Build a gravatar URL with what we know.
420 // Find the best default image URL we can (MDL-35669)
421 if (empty($CFG->gravatardefaulturl)) {
422 $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
423 if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
424 $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
425 } else {
426 $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
428 } else {
429 $gravatardefault = $CFG->gravatardefaulturl;
432 // If the currently requested page is https then we'll return an
433 // https gravatar page.
434 if (is_https()) {
435 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
436 } else {
437 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
441 return $defaulturl;
446 * Data structure representing a help icon.
448 * @copyright 2010 Petr Skoda (info@skodak.org)
449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
450 * @since Moodle 2.0
451 * @package core
452 * @category output
454 class help_icon implements renderable, templatable {
457 * @var string lang pack identifier (without the "_help" suffix),
458 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
459 * must exist.
461 public $identifier;
464 * @var string Component name, the same as in get_string()
466 public $component;
469 * @var string Extra descriptive text next to the icon
471 public $linktext = null;
474 * Constructor
476 * @param string $identifier string for help page title,
477 * string with _help suffix is used for the actual help text.
478 * string with _link suffix is used to create a link to further info (if it exists)
479 * @param string $component
481 public function __construct($identifier, $component) {
482 $this->identifier = $identifier;
483 $this->component = $component;
487 * Verifies that both help strings exists, shows debug warnings if not
489 public function diag_strings() {
490 $sm = get_string_manager();
491 if (!$sm->string_exists($this->identifier, $this->component)) {
492 debugging("Help title string does not exist: [$this->identifier, $this->component]");
494 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
495 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
500 * Export this data so it can be used as the context for a mustache template.
502 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
503 * @return array
505 public function export_for_template(renderer_base $output) {
506 global $CFG;
508 $title = get_string($this->identifier, $this->component);
510 if (empty($this->linktext)) {
511 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
512 } else {
513 $alt = get_string('helpwiththis');
516 $data = get_formatted_help_string($this->identifier, $this->component, false);
518 $data->alt = $alt;
519 $data->icon = (new pix_icon('help', $alt, 'core', ['class' => 'iconhelp']))->export_for_template($output);
520 $data->linktext = $this->linktext;
521 $data->title = get_string('helpprefix2', '', trim($title, ". \t"));
522 $data->url = (new moodle_url('/help.php', [
523 'component' => $this->component,
524 'identifier' => $this->identifier,
525 'lang' => current_language()
526 ]))->out(false);
528 $data->ltr = !right_to_left();
529 return $data;
535 * Data structure representing an icon font.
537 * @copyright 2016 Damyon Wiese
538 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
539 * @package core
540 * @category output
542 class pix_icon_font implements templatable {
545 * @var pix_icon $pixicon The original icon.
547 private $pixicon = null;
550 * @var string $key The mapped key.
552 private $key;
555 * @var bool $mapped The icon could not be mapped.
557 private $mapped;
560 * Constructor
562 * @param pix_icon $pixicon The original icon
564 public function __construct(pix_icon $pixicon) {
565 global $PAGE;
567 $this->pixicon = $pixicon;
568 $this->mapped = false;
569 $iconsystem = \core\output\icon_system::instance();
571 $this->key = $iconsystem->remap_icon_name($pixicon->pix, $pixicon->component);
572 if (!empty($this->key)) {
573 $this->mapped = true;
578 * Return true if this pix_icon was successfully mapped to an icon font.
580 * @return bool
582 public function is_mapped() {
583 return $this->mapped;
587 * Export this data so it can be used as the context for a mustache template.
589 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
590 * @return array
592 public function export_for_template(renderer_base $output) {
594 $pixdata = $this->pixicon->export_for_template($output);
596 $title = isset($this->pixicon->attributes['title']) ? $this->pixicon->attributes['title'] : '';
597 $alt = isset($this->pixicon->attributes['alt']) ? $this->pixicon->attributes['alt'] : '';
598 if (empty($title)) {
599 $title = $alt;
601 $data = array(
602 'extraclasses' => $pixdata['extraclasses'],
603 'title' => $title,
604 'alt' => $alt,
605 'key' => $this->key
608 return $data;
613 * Data structure representing an icon subtype.
615 * @copyright 2016 Damyon Wiese
616 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
617 * @package core
618 * @category output
620 class pix_icon_fontawesome extends pix_icon_font {
625 * Data structure representing an icon.
627 * @copyright 2010 Petr Skoda
628 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
629 * @since Moodle 2.0
630 * @package core
631 * @category output
633 class pix_icon implements renderable, templatable {
636 * @var string The icon name
638 var $pix;
641 * @var string The component the icon belongs to.
643 var $component;
646 * @var array An array of attributes to use on the icon
648 var $attributes = array();
651 * Constructor
653 * @param string $pix short icon name
654 * @param string $alt The alt text to use for the icon
655 * @param string $component component name
656 * @param array $attributes html attributes
658 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
659 global $PAGE;
661 $this->pix = $pix;
662 $this->component = $component;
663 $this->attributes = (array)$attributes;
665 if (empty($this->attributes['class'])) {
666 $this->attributes['class'] = '';
669 // Set an additional class for big icons so that they can be styled properly.
670 if (substr($pix, 0, 2) === 'b/') {
671 $this->attributes['class'] .= ' iconsize-big';
674 // If the alt is empty, don't place it in the attributes, otherwise it will override parent alt text.
675 if (!is_null($alt)) {
676 $this->attributes['alt'] = $alt;
678 // If there is no title, set it to the attribute.
679 if (!isset($this->attributes['title'])) {
680 $this->attributes['title'] = $this->attributes['alt'];
682 } else {
683 unset($this->attributes['alt']);
686 if (empty($this->attributes['title'])) {
687 // Remove the title attribute if empty, we probably want to use the parent node's title
688 // and some browsers might overwrite it with an empty title.
689 unset($this->attributes['title']);
694 * Export this data so it can be used as the context for a mustache template.
696 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
697 * @return array
699 public function export_for_template(renderer_base $output) {
700 $attributes = $this->attributes;
701 $extraclasses = '';
703 foreach ($attributes as $key => $item) {
704 if ($key == 'class') {
705 $extraclasses = $item;
706 unset($attributes[$key]);
707 break;
711 $attributes['src'] = $output->image_url($this->pix, $this->component)->out(false);
712 $templatecontext = array();
713 foreach ($attributes as $name => $value) {
714 $templatecontext[] = array('name' => $name, 'value' => $value);
716 $title = isset($attributes['title']) ? $attributes['title'] : '';
717 if (empty($title)) {
718 $title = isset($attributes['alt']) ? $attributes['alt'] : '';
720 $data = array(
721 'attributes' => $templatecontext,
722 'extraclasses' => $extraclasses
725 return $data;
729 * Much simpler version of export that will produce the data required to render this pix with the
730 * pix helper in a mustache tag.
732 * @return array
734 public function export_for_pix() {
735 $title = isset($this->attributes['title']) ? $this->attributes['title'] : '';
736 if (empty($title)) {
737 $title = isset($this->attributes['alt']) ? $this->attributes['alt'] : '';
739 return [
740 'key' => $this->pix,
741 'component' => $this->component,
742 'title' => $title
748 * Data structure representing an activity icon.
750 * The difference is that activity icons will always render with the standard icon system (no font icons).
752 * @copyright 2017 Damyon Wiese
753 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
754 * @package core
756 class image_icon extends pix_icon {
760 * Data structure representing an emoticon image
762 * @copyright 2010 David Mudrak
763 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
764 * @since Moodle 2.0
765 * @package core
766 * @category output
768 class pix_emoticon extends pix_icon implements renderable {
771 * Constructor
772 * @param string $pix short icon name
773 * @param string $alt alternative text
774 * @param string $component emoticon image provider
775 * @param array $attributes explicit HTML attributes
777 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
778 if (empty($attributes['class'])) {
779 $attributes['class'] = 'emoticon';
781 parent::__construct($pix, $alt, $component, $attributes);
786 * Data structure representing a simple form with only one button.
788 * @copyright 2009 Petr Skoda
789 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
790 * @since Moodle 2.0
791 * @package core
792 * @category output
794 class single_button implements renderable {
797 * @var moodle_url Target url
799 public $url;
802 * @var string Button label
804 public $label;
807 * @var string Form submit method post or get
809 public $method = 'post';
812 * @var string Wrapping div class
814 public $class = 'singlebutton';
817 * @var bool True if button is primary button. Used for styling.
819 public $primary = false;
822 * @var bool True if button disabled, false if normal
824 public $disabled = false;
827 * @var string Button tooltip
829 public $tooltip = null;
832 * @var string Form id
834 public $formid;
837 * @var array List of attached actions
839 public $actions = array();
842 * @var array $params URL Params
844 public $params;
847 * @var string Action id
849 public $actionid;
852 * Constructor
853 * @param moodle_url $url
854 * @param string $label button text
855 * @param string $method get or post submit method
857 public function __construct(moodle_url $url, $label, $method='post', $primary=false) {
858 $this->url = clone($url);
859 $this->label = $label;
860 $this->method = $method;
861 $this->primary = $primary;
865 * Shortcut for adding a JS confirm dialog when the button is clicked.
866 * The message must be a yes/no question.
868 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
870 public function add_confirm_action($confirmmessage) {
871 $this->add_action(new confirm_action($confirmmessage));
875 * Add action to the button.
876 * @param component_action $action
878 public function add_action(component_action $action) {
879 $this->actions[] = $action;
883 * Export data.
885 * @param renderer_base $output Renderer.
886 * @return stdClass
888 public function export_for_template(renderer_base $output) {
889 $url = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
891 $data = new stdClass();
892 $data->id = html_writer::random_id('single_button');
893 $data->formid = $this->formid;
894 $data->method = $this->method;
895 $data->url = $url === '' ? '#' : $url;
896 $data->label = $this->label;
897 $data->classes = $this->class;
898 $data->disabled = $this->disabled;
899 $data->tooltip = $this->tooltip;
900 $data->primary = $this->primary;
902 // Form parameters.
903 $params = $this->url->params();
904 if ($this->method === 'post') {
905 $params['sesskey'] = sesskey();
907 $data->params = array_map(function($key) use ($params) {
908 return ['name' => $key, 'value' => $params[$key]];
909 }, array_keys($params));
911 // Button actions.
912 $actions = $this->actions;
913 $data->actions = array_map(function($action) use ($output) {
914 return $action->export_for_template($output);
915 }, $actions);
916 $data->hasactions = !empty($data->actions);
918 return $data;
924 * Simple form with just one select field that gets submitted automatically.
926 * If JS not enabled small go button is printed too.
928 * @copyright 2009 Petr Skoda
929 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
930 * @since Moodle 2.0
931 * @package core
932 * @category output
934 class single_select implements renderable, templatable {
937 * @var moodle_url Target url - includes hidden fields
939 var $url;
942 * @var string Name of the select element.
944 var $name;
947 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
948 * it is also possible to specify optgroup as complex label array ex.:
949 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
950 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
952 var $options;
955 * @var string Selected option
957 var $selected;
960 * @var array Nothing selected
962 var $nothing;
965 * @var array Extra select field attributes
967 var $attributes = array();
970 * @var string Button label
972 var $label = '';
975 * @var array Button label's attributes
977 var $labelattributes = array();
980 * @var string Form submit method post or get
982 var $method = 'get';
985 * @var string Wrapping div class
987 var $class = 'singleselect';
990 * @var bool True if button disabled, false if normal
992 var $disabled = false;
995 * @var string Button tooltip
997 var $tooltip = null;
1000 * @var string Form id
1002 var $formid = null;
1005 * @var array List of attached actions
1007 var $helpicon = null;
1010 * Constructor
1011 * @param moodle_url $url form action target, includes hidden fields
1012 * @param string $name name of selection field - the changing parameter in url
1013 * @param array $options list of options
1014 * @param string $selected selected element
1015 * @param array $nothing
1016 * @param string $formid
1018 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1019 $this->url = $url;
1020 $this->name = $name;
1021 $this->options = $options;
1022 $this->selected = $selected;
1023 $this->nothing = $nothing;
1024 $this->formid = $formid;
1028 * Shortcut for adding a JS confirm dialog when the button is clicked.
1029 * The message must be a yes/no question.
1031 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
1033 public function add_confirm_action($confirmmessage) {
1034 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
1038 * Add action to the button.
1040 * @param component_action $action
1042 public function add_action(component_action $action) {
1043 $this->actions[] = $action;
1047 * Adds help icon.
1049 * @deprecated since Moodle 2.0
1051 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1052 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1056 * Adds help icon.
1058 * @param string $identifier The keyword that defines a help page
1059 * @param string $component
1061 public function set_help_icon($identifier, $component = 'moodle') {
1062 $this->helpicon = new help_icon($identifier, $component);
1066 * Sets select's label
1068 * @param string $label
1069 * @param array $attributes (optional)
1071 public function set_label($label, $attributes = array()) {
1072 $this->label = $label;
1073 $this->labelattributes = $attributes;
1078 * Export data.
1080 * @param renderer_base $output Renderer.
1081 * @return stdClass
1083 public function export_for_template(renderer_base $output) {
1084 $attributes = $this->attributes;
1086 $data = new stdClass();
1087 $data->name = $this->name;
1088 $data->method = $this->method;
1089 $data->action = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
1090 $data->classes = $this->class;
1091 $data->label = $this->label;
1092 $data->disabled = $this->disabled;
1093 $data->title = $this->tooltip;
1094 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('single_select_f');
1095 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('single_select');
1096 unset($attributes['id']);
1098 // Form parameters.
1099 $params = $this->url->params();
1100 if ($this->method === 'post') {
1101 $params['sesskey'] = sesskey();
1103 $data->params = array_map(function($key) use ($params) {
1104 return ['name' => $key, 'value' => $params[$key]];
1105 }, array_keys($params));
1107 // Select options.
1108 $hasnothing = false;
1109 if (is_string($this->nothing) && $this->nothing !== '') {
1110 $nothing = ['' => $this->nothing];
1111 $hasnothing = true;
1112 $nothingkey = '';
1113 } else if (is_array($this->nothing)) {
1114 $nothingvalue = reset($this->nothing);
1115 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1116 $nothing = [key($this->nothing) => get_string('choosedots')];
1117 } else {
1118 $nothing = $this->nothing;
1120 $hasnothing = true;
1121 $nothingkey = key($this->nothing);
1123 if ($hasnothing) {
1124 $options = $nothing + $this->options;
1125 } else {
1126 $options = $this->options;
1129 foreach ($options as $value => $name) {
1130 if (is_array($options[$value])) {
1131 foreach ($options[$value] as $optgroupname => $optgroupvalues) {
1132 $sublist = [];
1133 foreach ($optgroupvalues as $optvalue => $optname) {
1134 $option = [
1135 'value' => $optvalue,
1136 'name' => $optname,
1137 'selected' => strval($this->selected) === strval($optvalue),
1140 if ($hasnothing && $nothingkey === $optvalue) {
1141 $option['ignore'] = 'data-ignore';
1144 $sublist[] = $option;
1146 $data->options[] = [
1147 'name' => $optgroupname,
1148 'optgroup' => true,
1149 'options' => $sublist
1152 } else {
1153 $option = [
1154 'value' => $value,
1155 'name' => $options[$value],
1156 'selected' => strval($this->selected) === strval($value),
1157 'optgroup' => false
1160 if ($hasnothing && $nothingkey === $value) {
1161 $option['ignore'] = 'data-ignore';
1164 $data->options[] = $option;
1168 // Label attributes.
1169 $data->labelattributes = [];
1170 foreach ($this->labelattributes as $key => $value) {
1171 $data->labelattributes = ['name' => $key, 'value' => $value];
1174 // Help icon.
1175 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1177 return $data;
1182 * Simple URL selection widget description.
1184 * @copyright 2009 Petr Skoda
1185 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1186 * @since Moodle 2.0
1187 * @package core
1188 * @category output
1190 class url_select implements renderable, templatable {
1192 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
1193 * it is also possible to specify optgroup as complex label array ex.:
1194 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1195 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1197 var $urls;
1200 * @var string Selected option
1202 var $selected;
1205 * @var array Nothing selected
1207 var $nothing;
1210 * @var array Extra select field attributes
1212 var $attributes = array();
1215 * @var string Button label
1217 var $label = '';
1220 * @var array Button label's attributes
1222 var $labelattributes = array();
1225 * @var string Wrapping div class
1227 var $class = 'urlselect';
1230 * @var bool True if button disabled, false if normal
1232 var $disabled = false;
1235 * @var string Button tooltip
1237 var $tooltip = null;
1240 * @var string Form id
1242 var $formid = null;
1245 * @var array List of attached actions
1247 var $helpicon = null;
1250 * @var string If set, makes button visible with given name for button
1252 var $showbutton = null;
1255 * Constructor
1256 * @param array $urls list of options
1257 * @param string $selected selected element
1258 * @param array $nothing
1259 * @param string $formid
1260 * @param string $showbutton Set to text of button if it should be visible
1261 * or null if it should be hidden (hidden version always has text 'go')
1263 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
1264 $this->urls = $urls;
1265 $this->selected = $selected;
1266 $this->nothing = $nothing;
1267 $this->formid = $formid;
1268 $this->showbutton = $showbutton;
1272 * Adds help icon.
1274 * @deprecated since Moodle 2.0
1276 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1277 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1281 * Adds help icon.
1283 * @param string $identifier The keyword that defines a help page
1284 * @param string $component
1286 public function set_help_icon($identifier, $component = 'moodle') {
1287 $this->helpicon = new help_icon($identifier, $component);
1291 * Sets select's label
1293 * @param string $label
1294 * @param array $attributes (optional)
1296 public function set_label($label, $attributes = array()) {
1297 $this->label = $label;
1298 $this->labelattributes = $attributes;
1302 * Clean a URL.
1304 * @param string $value The URL.
1305 * @return The cleaned URL.
1307 protected function clean_url($value) {
1308 global $CFG;
1310 if (empty($value)) {
1311 // Nothing.
1313 } else if (strpos($value, $CFG->wwwroot . '/') === 0) {
1314 $value = str_replace($CFG->wwwroot, '', $value);
1316 } else if (strpos($value, '/') !== 0) {
1317 debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER);
1320 return $value;
1324 * Flatten the options for Mustache.
1326 * This also cleans the URLs.
1328 * @param array $options The options.
1329 * @param array $nothing The nothing option.
1330 * @return array
1332 protected function flatten_options($options, $nothing) {
1333 $flattened = [];
1335 foreach ($options as $value => $option) {
1336 if (is_array($option)) {
1337 foreach ($option as $groupname => $optoptions) {
1338 if (!isset($flattened[$groupname])) {
1339 $flattened[$groupname] = [
1340 'name' => $groupname,
1341 'isgroup' => true,
1342 'options' => []
1345 foreach ($optoptions as $optvalue => $optoption) {
1346 $cleanedvalue = $this->clean_url($optvalue);
1347 $flattened[$groupname]['options'][$cleanedvalue] = [
1348 'name' => $optoption,
1349 'value' => $cleanedvalue,
1350 'selected' => $this->selected == $optvalue,
1355 } else {
1356 $cleanedvalue = $this->clean_url($value);
1357 $flattened[$cleanedvalue] = [
1358 'name' => $option,
1359 'value' => $cleanedvalue,
1360 'selected' => $this->selected == $value,
1365 if (!empty($nothing)) {
1366 $value = key($nothing);
1367 $name = reset($nothing);
1368 $flattened = [
1369 $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value]
1370 ] + $flattened;
1373 // Make non-associative array.
1374 foreach ($flattened as $key => $value) {
1375 if (!empty($value['options'])) {
1376 $flattened[$key]['options'] = array_values($value['options']);
1379 $flattened = array_values($flattened);
1381 return $flattened;
1385 * Export for template.
1387 * @param renderer_base $output Renderer.
1388 * @return stdClass
1390 public function export_for_template(renderer_base $output) {
1391 $attributes = $this->attributes;
1393 $data = new stdClass();
1394 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('url_select_f');
1395 $data->classes = $this->class;
1396 $data->label = $this->label;
1397 $data->disabled = $this->disabled;
1398 $data->title = $this->tooltip;
1399 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('url_select');
1400 $data->sesskey = sesskey();
1401 $data->action = (new moodle_url('/course/jumpto.php'))->out(false);
1403 // Remove attributes passed as property directly.
1404 unset($attributes['class']);
1405 unset($attributes['id']);
1406 unset($attributes['name']);
1407 unset($attributes['title']);
1409 $data->showbutton = $this->showbutton;
1411 // Select options.
1412 $nothing = false;
1413 if (is_string($this->nothing) && $this->nothing !== '') {
1414 $nothing = ['' => $this->nothing];
1415 } else if (is_array($this->nothing)) {
1416 $nothingvalue = reset($this->nothing);
1417 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1418 $nothing = [key($this->nothing) => get_string('choosedots')];
1419 } else {
1420 $nothing = $this->nothing;
1423 $data->options = $this->flatten_options($this->urls, $nothing);
1425 // Label attributes.
1426 $data->labelattributes = [];
1427 foreach ($this->labelattributes as $key => $value) {
1428 $data->labelattributes[] = ['name' => $key, 'value' => $value];
1431 // Help icon.
1432 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1434 // Finally all the remaining attributes.
1435 $data->attributes = [];
1436 foreach ($this->attributes as $key => $value) {
1437 $data->attributes = ['name' => $key, 'value' => $value];
1440 return $data;
1445 * Data structure describing html link with special action attached.
1447 * @copyright 2010 Petr Skoda
1448 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1449 * @since Moodle 2.0
1450 * @package core
1451 * @category output
1453 class action_link implements renderable {
1456 * @var moodle_url Href url
1458 public $url;
1461 * @var string Link text HTML fragment
1463 public $text;
1466 * @var array HTML attributes
1468 public $attributes;
1471 * @var array List of actions attached to link
1473 public $actions;
1476 * @var pix_icon Optional pix icon to render with the link
1478 public $icon;
1481 * Constructor
1482 * @param moodle_url $url
1483 * @param string $text HTML fragment
1484 * @param component_action $action
1485 * @param array $attributes associative array of html link attributes + disabled
1486 * @param pix_icon $icon optional pix_icon to render with the link text
1488 public function __construct(moodle_url $url,
1489 $text,
1490 component_action $action=null,
1491 array $attributes=null,
1492 pix_icon $icon=null) {
1493 $this->url = clone($url);
1494 $this->text = $text;
1495 $this->attributes = (array)$attributes;
1496 if ($action) {
1497 $this->add_action($action);
1499 $this->icon = $icon;
1503 * Add action to the link.
1505 * @param component_action $action
1507 public function add_action(component_action $action) {
1508 $this->actions[] = $action;
1512 * Adds a CSS class to this action link object
1513 * @param string $class
1515 public function add_class($class) {
1516 if (empty($this->attributes['class'])) {
1517 $this->attributes['class'] = $class;
1518 } else {
1519 $this->attributes['class'] .= ' ' . $class;
1524 * Returns true if the specified class has been added to this link.
1525 * @param string $class
1526 * @return bool
1528 public function has_class($class) {
1529 return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
1533 * Return the rendered HTML for the icon. Useful for rendering action links in a template.
1534 * @return string
1536 public function get_icon_html() {
1537 global $OUTPUT;
1538 if (!$this->icon) {
1539 return '';
1541 return $OUTPUT->render($this->icon);
1545 * Export for template.
1547 * @param renderer_base $output The renderer.
1548 * @return stdClass
1550 public function export_for_template(renderer_base $output) {
1551 $data = new stdClass();
1552 $attributes = $this->attributes;
1554 if (empty($attributes['id'])) {
1555 $attributes['id'] = html_writer::random_id('action_link');
1557 $data->id = $attributes['id'];
1558 unset($attributes['id']);
1560 $data->disabled = !empty($attributes['disabled']);
1561 unset($attributes['disabled']);
1563 $data->text = $this->text instanceof renderable ? $output->render($this->text) : (string) $this->text;
1564 $data->url = $this->url ? $this->url->out(false) : '';
1565 $data->icon = $this->icon ? $this->icon->export_for_pix() : null;
1566 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
1567 unset($attributes['class']);
1569 $data->attributes = array_map(function($key, $value) {
1570 return [
1571 'name' => $key,
1572 'value' => $value
1574 }, array_keys($attributes), $attributes);
1576 $data->actions = array_map(function($action) use ($output) {
1577 return $action->export_for_template($output);
1578 }, !empty($this->actions) ? $this->actions : []);
1579 $data->hasactions = !empty($this->actions);
1581 return $data;
1586 * Simple html output class
1588 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1589 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1590 * @since Moodle 2.0
1591 * @package core
1592 * @category output
1594 class html_writer {
1597 * Outputs a tag with attributes and contents
1599 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1600 * @param string $contents What goes between the opening and closing tags
1601 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1602 * @return string HTML fragment
1604 public static function tag($tagname, $contents, array $attributes = null) {
1605 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1609 * Outputs an opening tag with attributes
1611 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1612 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1613 * @return string HTML fragment
1615 public static function start_tag($tagname, array $attributes = null) {
1616 return '<' . $tagname . self::attributes($attributes) . '>';
1620 * Outputs a closing tag
1622 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1623 * @return string HTML fragment
1625 public static function end_tag($tagname) {
1626 return '</' . $tagname . '>';
1630 * Outputs an empty tag with attributes
1632 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1633 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1634 * @return string HTML fragment
1636 public static function empty_tag($tagname, array $attributes = null) {
1637 return '<' . $tagname . self::attributes($attributes) . ' />';
1641 * Outputs a tag, but only if the contents are not empty
1643 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1644 * @param string $contents What goes between the opening and closing tags
1645 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1646 * @return string HTML fragment
1648 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1649 if ($contents === '' || is_null($contents)) {
1650 return '';
1652 return self::tag($tagname, $contents, $attributes);
1656 * Outputs a HTML attribute and value
1658 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1659 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1660 * @return string HTML fragment
1662 public static function attribute($name, $value) {
1663 if ($value instanceof moodle_url) {
1664 return ' ' . $name . '="' . $value->out() . '"';
1667 // special case, we do not want these in output
1668 if ($value === null) {
1669 return '';
1672 // no sloppy trimming here!
1673 return ' ' . $name . '="' . s($value) . '"';
1677 * Outputs a list of HTML attributes and values
1679 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1680 * The values will be escaped with {@link s()}
1681 * @return string HTML fragment
1683 public static function attributes(array $attributes = null) {
1684 $attributes = (array)$attributes;
1685 $output = '';
1686 foreach ($attributes as $name => $value) {
1687 $output .= self::attribute($name, $value);
1689 return $output;
1693 * Generates a simple image tag with attributes.
1695 * @param string $src The source of image
1696 * @param string $alt The alternate text for image
1697 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1698 * @return string HTML fragment
1700 public static function img($src, $alt, array $attributes = null) {
1701 $attributes = (array)$attributes;
1702 $attributes['src'] = $src;
1703 $attributes['alt'] = $alt;
1705 return self::empty_tag('img', $attributes);
1709 * Generates random html element id.
1711 * @staticvar int $counter
1712 * @staticvar type $uniq
1713 * @param string $base A string fragment that will be included in the random ID.
1714 * @return string A unique ID
1716 public static function random_id($base='random') {
1717 static $counter = 0;
1718 static $uniq;
1720 if (!isset($uniq)) {
1721 $uniq = uniqid();
1724 $counter++;
1725 return $base.$uniq.$counter;
1729 * Generates a simple html link
1731 * @param string|moodle_url $url The URL
1732 * @param string $text The text
1733 * @param array $attributes HTML attributes
1734 * @return string HTML fragment
1736 public static function link($url, $text, array $attributes = null) {
1737 $attributes = (array)$attributes;
1738 $attributes['href'] = $url;
1739 return self::tag('a', $text, $attributes);
1743 * Generates a simple checkbox with optional label
1745 * @param string $name The name of the checkbox
1746 * @param string $value The value of the checkbox
1747 * @param bool $checked Whether the checkbox is checked
1748 * @param string $label The label for the checkbox
1749 * @param array $attributes Any attributes to apply to the checkbox
1750 * @return string html fragment
1752 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1753 $attributes = (array)$attributes;
1754 $output = '';
1756 if ($label !== '' and !is_null($label)) {
1757 if (empty($attributes['id'])) {
1758 $attributes['id'] = self::random_id('checkbox_');
1761 $attributes['type'] = 'checkbox';
1762 $attributes['value'] = $value;
1763 $attributes['name'] = $name;
1764 $attributes['checked'] = $checked ? 'checked' : null;
1766 $output .= self::empty_tag('input', $attributes);
1768 if ($label !== '' and !is_null($label)) {
1769 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1772 return $output;
1776 * Generates a simple select yes/no form field
1778 * @param string $name name of select element
1779 * @param bool $selected
1780 * @param array $attributes - html select element attributes
1781 * @return string HTML fragment
1783 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1784 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1785 return self::select($options, $name, $selected, null, $attributes);
1789 * Generates a simple select form field
1791 * @param array $options associative array value=>label ex.:
1792 * array(1=>'One, 2=>Two)
1793 * it is also possible to specify optgroup as complex label array ex.:
1794 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1795 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1796 * @param string $name name of select element
1797 * @param string|array $selected value or array of values depending on multiple attribute
1798 * @param array|bool $nothing add nothing selected option, or false of not added
1799 * @param array $attributes html select element attributes
1800 * @return string HTML fragment
1802 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1803 $attributes = (array)$attributes;
1804 if (is_array($nothing)) {
1805 foreach ($nothing as $k=>$v) {
1806 if ($v === 'choose' or $v === 'choosedots') {
1807 $nothing[$k] = get_string('choosedots');
1810 $options = $nothing + $options; // keep keys, do not override
1812 } else if (is_string($nothing) and $nothing !== '') {
1813 // BC
1814 $options = array(''=>$nothing) + $options;
1817 // we may accept more values if multiple attribute specified
1818 $selected = (array)$selected;
1819 foreach ($selected as $k=>$v) {
1820 $selected[$k] = (string)$v;
1823 if (!isset($attributes['id'])) {
1824 $id = 'menu'.$name;
1825 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1826 $id = str_replace('[', '', $id);
1827 $id = str_replace(']', '', $id);
1828 $attributes['id'] = $id;
1831 if (!isset($attributes['class'])) {
1832 $class = 'menu'.$name;
1833 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1834 $class = str_replace('[', '', $class);
1835 $class = str_replace(']', '', $class);
1836 $attributes['class'] = $class;
1838 $attributes['class'] = 'select custom-select ' . $attributes['class']; // Add 'select' selector always.
1840 $attributes['name'] = $name;
1842 if (!empty($attributes['disabled'])) {
1843 $attributes['disabled'] = 'disabled';
1844 } else {
1845 unset($attributes['disabled']);
1848 $output = '';
1849 foreach ($options as $value=>$label) {
1850 if (is_array($label)) {
1851 // ignore key, it just has to be unique
1852 $output .= self::select_optgroup(key($label), current($label), $selected);
1853 } else {
1854 $output .= self::select_option($label, $value, $selected);
1857 return self::tag('select', $output, $attributes);
1861 * Returns HTML to display a select box option.
1863 * @param string $label The label to display as the option.
1864 * @param string|int $value The value the option represents
1865 * @param array $selected An array of selected options
1866 * @return string HTML fragment
1868 private static function select_option($label, $value, array $selected) {
1869 $attributes = array();
1870 $value = (string)$value;
1871 if (in_array($value, $selected, true)) {
1872 $attributes['selected'] = 'selected';
1874 $attributes['value'] = $value;
1875 return self::tag('option', $label, $attributes);
1879 * Returns HTML to display a select box option group.
1881 * @param string $groupname The label to use for the group
1882 * @param array $options The options in the group
1883 * @param array $selected An array of selected values.
1884 * @return string HTML fragment.
1886 private static function select_optgroup($groupname, $options, array $selected) {
1887 if (empty($options)) {
1888 return '';
1890 $attributes = array('label'=>$groupname);
1891 $output = '';
1892 foreach ($options as $value=>$label) {
1893 $output .= self::select_option($label, $value, $selected);
1895 return self::tag('optgroup', $output, $attributes);
1899 * This is a shortcut for making an hour selector menu.
1901 * @param string $type The type of selector (years, months, days, hours, minutes)
1902 * @param string $name fieldname
1903 * @param int $currenttime A default timestamp in GMT
1904 * @param int $step minute spacing
1905 * @param array $attributes - html select element attributes
1906 * @return HTML fragment
1908 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1909 global $OUTPUT;
1911 if (!$currenttime) {
1912 $currenttime = time();
1914 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1915 $currentdate = $calendartype->timestamp_to_date_array($currenttime);
1916 $userdatetype = $type;
1917 $timeunits = array();
1919 switch ($type) {
1920 case 'years':
1921 $timeunits = $calendartype->get_years();
1922 $userdatetype = 'year';
1923 break;
1924 case 'months':
1925 $timeunits = $calendartype->get_months();
1926 $userdatetype = 'month';
1927 $currentdate['month'] = (int)$currentdate['mon'];
1928 break;
1929 case 'days':
1930 $timeunits = $calendartype->get_days();
1931 $userdatetype = 'mday';
1932 break;
1933 case 'hours':
1934 for ($i=0; $i<=23; $i++) {
1935 $timeunits[$i] = sprintf("%02d",$i);
1937 break;
1938 case 'minutes':
1939 if ($step != 1) {
1940 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1943 for ($i=0; $i<=59; $i+=$step) {
1944 $timeunits[$i] = sprintf("%02d",$i);
1946 break;
1947 default:
1948 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1951 $attributes = (array) $attributes;
1952 $data = (object) [
1953 'name' => $name,
1954 'id' => !empty($attributes['id']) ? $attributes['id'] : self::random_id('ts_'),
1955 'label' => get_string(substr($type, 0, -1), 'form'),
1956 'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) {
1957 return [
1958 'name' => $timeunits[$value],
1959 'value' => $value,
1960 'selected' => $currentdate[$userdatetype] == $value
1962 }, array_keys($timeunits)),
1965 unset($attributes['id']);
1966 unset($attributes['name']);
1967 $data->attributes = array_map(function($name) use ($attributes) {
1968 return [
1969 'name' => $name,
1970 'value' => $attributes[$name]
1972 }, array_keys($attributes));
1974 return $OUTPUT->render_from_template('core/select_time', $data);
1978 * Shortcut for quick making of lists
1980 * Note: 'list' is a reserved keyword ;-)
1982 * @param array $items
1983 * @param array $attributes
1984 * @param string $tag ul or ol
1985 * @return string
1987 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1988 $output = html_writer::start_tag($tag, $attributes)."\n";
1989 foreach ($items as $item) {
1990 $output .= html_writer::tag('li', $item)."\n";
1992 $output .= html_writer::end_tag($tag);
1993 return $output;
1997 * Returns hidden input fields created from url parameters.
1999 * @param moodle_url $url
2000 * @param array $exclude list of excluded parameters
2001 * @return string HTML fragment
2003 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
2004 $exclude = (array)$exclude;
2005 $params = $url->params();
2006 foreach ($exclude as $key) {
2007 unset($params[$key]);
2010 $output = '';
2011 foreach ($params as $key => $value) {
2012 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
2013 $output .= self::empty_tag('input', $attributes)."\n";
2015 return $output;
2019 * Generate a script tag containing the the specified code.
2021 * @param string $jscode the JavaScript code
2022 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
2023 * @return string HTML, the code wrapped in <script> tags.
2025 public static function script($jscode, $url=null) {
2026 if ($jscode) {
2027 $attributes = array('type'=>'text/javascript');
2028 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
2030 } else if ($url) {
2031 $attributes = array('type'=>'text/javascript', 'src'=>$url);
2032 return self::tag('script', '', $attributes) . "\n";
2034 } else {
2035 return '';
2040 * Renders HTML table
2042 * This method may modify the passed instance by adding some default properties if they are not set yet.
2043 * If this is not what you want, you should make a full clone of your data before passing them to this
2044 * method. In most cases this is not an issue at all so we do not clone by default for performance
2045 * and memory consumption reasons.
2047 * @param html_table $table data to be rendered
2048 * @return string HTML code
2050 public static function table(html_table $table) {
2051 // prepare table data and populate missing properties with reasonable defaults
2052 if (!empty($table->align)) {
2053 foreach ($table->align as $key => $aa) {
2054 if ($aa) {
2055 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
2056 } else {
2057 $table->align[$key] = null;
2061 if (!empty($table->size)) {
2062 foreach ($table->size as $key => $ss) {
2063 if ($ss) {
2064 $table->size[$key] = 'width:'. $ss .';';
2065 } else {
2066 $table->size[$key] = null;
2070 if (!empty($table->wrap)) {
2071 foreach ($table->wrap as $key => $ww) {
2072 if ($ww) {
2073 $table->wrap[$key] = 'white-space:nowrap;';
2074 } else {
2075 $table->wrap[$key] = '';
2079 if (!empty($table->head)) {
2080 foreach ($table->head as $key => $val) {
2081 if (!isset($table->align[$key])) {
2082 $table->align[$key] = null;
2084 if (!isset($table->size[$key])) {
2085 $table->size[$key] = null;
2087 if (!isset($table->wrap[$key])) {
2088 $table->wrap[$key] = null;
2093 if (empty($table->attributes['class'])) {
2094 $table->attributes['class'] = 'generaltable';
2096 if (!empty($table->tablealign)) {
2097 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
2100 // explicitly assigned properties override those defined via $table->attributes
2101 $table->attributes['class'] = trim($table->attributes['class']);
2102 $attributes = array_merge($table->attributes, array(
2103 'id' => $table->id,
2104 'width' => $table->width,
2105 'summary' => $table->summary,
2106 'cellpadding' => $table->cellpadding,
2107 'cellspacing' => $table->cellspacing,
2109 $output = html_writer::start_tag('table', $attributes) . "\n";
2111 $countcols = 0;
2113 // Output a caption if present.
2114 if (!empty($table->caption)) {
2115 $captionattributes = array();
2116 if ($table->captionhide) {
2117 $captionattributes['class'] = 'accesshide';
2119 $output .= html_writer::tag(
2120 'caption',
2121 $table->caption,
2122 $captionattributes
2126 if (!empty($table->head)) {
2127 $countcols = count($table->head);
2129 $output .= html_writer::start_tag('thead', array()) . "\n";
2130 $output .= html_writer::start_tag('tr', array()) . "\n";
2131 $keys = array_keys($table->head);
2132 $lastkey = end($keys);
2134 foreach ($table->head as $key => $heading) {
2135 // Convert plain string headings into html_table_cell objects
2136 if (!($heading instanceof html_table_cell)) {
2137 $headingtext = $heading;
2138 $heading = new html_table_cell();
2139 $heading->text = $headingtext;
2140 $heading->header = true;
2143 if ($heading->header !== false) {
2144 $heading->header = true;
2147 if ($heading->header && empty($heading->scope)) {
2148 $heading->scope = 'col';
2151 $heading->attributes['class'] .= ' header c' . $key;
2152 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
2153 $heading->colspan = $table->headspan[$key];
2154 $countcols += $table->headspan[$key] - 1;
2157 if ($key == $lastkey) {
2158 $heading->attributes['class'] .= ' lastcol';
2160 if (isset($table->colclasses[$key])) {
2161 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
2163 $heading->attributes['class'] = trim($heading->attributes['class']);
2164 $attributes = array_merge($heading->attributes, array(
2165 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
2166 'scope' => $heading->scope,
2167 'colspan' => $heading->colspan,
2170 $tagtype = 'td';
2171 if ($heading->header === true) {
2172 $tagtype = 'th';
2174 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
2176 $output .= html_writer::end_tag('tr') . "\n";
2177 $output .= html_writer::end_tag('thead') . "\n";
2179 if (empty($table->data)) {
2180 // For valid XHTML strict every table must contain either a valid tr
2181 // or a valid tbody... both of which must contain a valid td
2182 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
2183 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
2184 $output .= html_writer::end_tag('tbody');
2188 if (!empty($table->data)) {
2189 $keys = array_keys($table->data);
2190 $lastrowkey = end($keys);
2191 $output .= html_writer::start_tag('tbody', array());
2193 foreach ($table->data as $key => $row) {
2194 if (($row === 'hr') && ($countcols)) {
2195 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
2196 } else {
2197 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
2198 if (!($row instanceof html_table_row)) {
2199 $newrow = new html_table_row();
2201 foreach ($row as $cell) {
2202 if (!($cell instanceof html_table_cell)) {
2203 $cell = new html_table_cell($cell);
2205 $newrow->cells[] = $cell;
2207 $row = $newrow;
2210 if (isset($table->rowclasses[$key])) {
2211 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
2214 if ($key == $lastrowkey) {
2215 $row->attributes['class'] .= ' lastrow';
2218 // Explicitly assigned properties should override those defined in the attributes.
2219 $row->attributes['class'] = trim($row->attributes['class']);
2220 $trattributes = array_merge($row->attributes, array(
2221 'id' => $row->id,
2222 'style' => $row->style,
2224 $output .= html_writer::start_tag('tr', $trattributes) . "\n";
2225 $keys2 = array_keys($row->cells);
2226 $lastkey = end($keys2);
2228 $gotlastkey = false; //flag for sanity checking
2229 foreach ($row->cells as $key => $cell) {
2230 if ($gotlastkey) {
2231 //This should never happen. Why do we have a cell after the last cell?
2232 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
2235 if (!($cell instanceof html_table_cell)) {
2236 $mycell = new html_table_cell();
2237 $mycell->text = $cell;
2238 $cell = $mycell;
2241 if (($cell->header === true) && empty($cell->scope)) {
2242 $cell->scope = 'row';
2245 if (isset($table->colclasses[$key])) {
2246 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
2249 $cell->attributes['class'] .= ' cell c' . $key;
2250 if ($key == $lastkey) {
2251 $cell->attributes['class'] .= ' lastcol';
2252 $gotlastkey = true;
2254 $tdstyle = '';
2255 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
2256 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
2257 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
2258 $cell->attributes['class'] = trim($cell->attributes['class']);
2259 $tdattributes = array_merge($cell->attributes, array(
2260 'style' => $tdstyle . $cell->style,
2261 'colspan' => $cell->colspan,
2262 'rowspan' => $cell->rowspan,
2263 'id' => $cell->id,
2264 'abbr' => $cell->abbr,
2265 'scope' => $cell->scope,
2267 $tagtype = 'td';
2268 if ($cell->header === true) {
2269 $tagtype = 'th';
2271 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
2274 $output .= html_writer::end_tag('tr') . "\n";
2276 $output .= html_writer::end_tag('tbody') . "\n";
2278 $output .= html_writer::end_tag('table') . "\n";
2280 return $output;
2284 * Renders form element label
2286 * By default, the label is suffixed with a label separator defined in the
2287 * current language pack (colon by default in the English lang pack).
2288 * Adding the colon can be explicitly disabled if needed. Label separators
2289 * are put outside the label tag itself so they are not read by
2290 * screenreaders (accessibility).
2292 * Parameter $for explicitly associates the label with a form control. When
2293 * set, the value of this attribute must be the same as the value of
2294 * the id attribute of the form control in the same document. When null,
2295 * the label being defined is associated with the control inside the label
2296 * element.
2298 * @param string $text content of the label tag
2299 * @param string|null $for id of the element this label is associated with, null for no association
2300 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
2301 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
2302 * @return string HTML of the label element
2304 public static function label($text, $for, $colonize = true, array $attributes=array()) {
2305 if (!is_null($for)) {
2306 $attributes = array_merge($attributes, array('for' => $for));
2308 $text = trim($text);
2309 $label = self::tag('label', $text, $attributes);
2311 // TODO MDL-12192 $colonize disabled for now yet
2312 // if (!empty($text) and $colonize) {
2313 // // the $text may end with the colon already, though it is bad string definition style
2314 // $colon = get_string('labelsep', 'langconfig');
2315 // if (!empty($colon)) {
2316 // $trimmed = trim($colon);
2317 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
2318 // //debugging('The label text should not end with colon or other label separator,
2319 // // please fix the string definition.', DEBUG_DEVELOPER);
2320 // } else {
2321 // $label .= $colon;
2322 // }
2323 // }
2324 // }
2326 return $label;
2330 * Combines a class parameter with other attributes. Aids in code reduction
2331 * because the class parameter is very frequently used.
2333 * If the class attribute is specified both in the attributes and in the
2334 * class parameter, the two values are combined with a space between.
2336 * @param string $class Optional CSS class (or classes as space-separated list)
2337 * @param array $attributes Optional other attributes as array
2338 * @return array Attributes (or null if still none)
2340 private static function add_class($class = '', array $attributes = null) {
2341 if ($class !== '') {
2342 $classattribute = array('class' => $class);
2343 if ($attributes) {
2344 if (array_key_exists('class', $attributes)) {
2345 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
2346 } else {
2347 $attributes = $classattribute + $attributes;
2349 } else {
2350 $attributes = $classattribute;
2353 return $attributes;
2357 * Creates a <div> tag. (Shortcut function.)
2359 * @param string $content HTML content of tag
2360 * @param string $class Optional CSS class (or classes as space-separated list)
2361 * @param array $attributes Optional other attributes as array
2362 * @return string HTML code for div
2364 public static function div($content, $class = '', array $attributes = null) {
2365 return self::tag('div', $content, self::add_class($class, $attributes));
2369 * Starts a <div> tag. (Shortcut function.)
2371 * @param string $class Optional CSS class (or classes as space-separated list)
2372 * @param array $attributes Optional other attributes as array
2373 * @return string HTML code for open div tag
2375 public static function start_div($class = '', array $attributes = null) {
2376 return self::start_tag('div', self::add_class($class, $attributes));
2380 * Ends a <div> tag. (Shortcut function.)
2382 * @return string HTML code for close div tag
2384 public static function end_div() {
2385 return self::end_tag('div');
2389 * Creates a <span> tag. (Shortcut function.)
2391 * @param string $content HTML content of tag
2392 * @param string $class Optional CSS class (or classes as space-separated list)
2393 * @param array $attributes Optional other attributes as array
2394 * @return string HTML code for span
2396 public static function span($content, $class = '', array $attributes = null) {
2397 return self::tag('span', $content, self::add_class($class, $attributes));
2401 * Starts a <span> tag. (Shortcut function.)
2403 * @param string $class Optional CSS class (or classes as space-separated list)
2404 * @param array $attributes Optional other attributes as array
2405 * @return string HTML code for open span tag
2407 public static function start_span($class = '', array $attributes = null) {
2408 return self::start_tag('span', self::add_class($class, $attributes));
2412 * Ends a <span> tag. (Shortcut function.)
2414 * @return string HTML code for close span tag
2416 public static function end_span() {
2417 return self::end_tag('span');
2422 * Simple javascript output class
2424 * @copyright 2010 Petr Skoda
2425 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2426 * @since Moodle 2.0
2427 * @package core
2428 * @category output
2430 class js_writer {
2433 * Returns javascript code calling the function
2435 * @param string $function function name, can be complex like Y.Event.purgeElement
2436 * @param array $arguments parameters
2437 * @param int $delay execution delay in seconds
2438 * @return string JS code fragment
2440 public static function function_call($function, array $arguments = null, $delay=0) {
2441 if ($arguments) {
2442 $arguments = array_map('json_encode', convert_to_array($arguments));
2443 $arguments = implode(', ', $arguments);
2444 } else {
2445 $arguments = '';
2447 $js = "$function($arguments);";
2449 if ($delay) {
2450 $delay = $delay * 1000; // in miliseconds
2451 $js = "setTimeout(function() { $js }, $delay);";
2453 return $js . "\n";
2457 * Special function which adds Y as first argument of function call.
2459 * @param string $function The function to call
2460 * @param array $extraarguments Any arguments to pass to it
2461 * @return string Some JS code
2463 public static function function_call_with_Y($function, array $extraarguments = null) {
2464 if ($extraarguments) {
2465 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
2466 $arguments = 'Y, ' . implode(', ', $extraarguments);
2467 } else {
2468 $arguments = 'Y';
2470 return "$function($arguments);\n";
2474 * Returns JavaScript code to initialise a new object
2476 * @param string $var If it is null then no var is assigned the new object.
2477 * @param string $class The class to initialise an object for.
2478 * @param array $arguments An array of args to pass to the init method.
2479 * @param array $requirements Any modules required for this class.
2480 * @param int $delay The delay before initialisation. 0 = no delay.
2481 * @return string Some JS code
2483 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
2484 if (is_array($arguments)) {
2485 $arguments = array_map('json_encode', convert_to_array($arguments));
2486 $arguments = implode(', ', $arguments);
2489 if ($var === null) {
2490 $js = "new $class(Y, $arguments);";
2491 } else if (strpos($var, '.')!==false) {
2492 $js = "$var = new $class(Y, $arguments);";
2493 } else {
2494 $js = "var $var = new $class(Y, $arguments);";
2497 if ($delay) {
2498 $delay = $delay * 1000; // in miliseconds
2499 $js = "setTimeout(function() { $js }, $delay);";
2502 if (count($requirements) > 0) {
2503 $requirements = implode("', '", $requirements);
2504 $js = "Y.use('$requirements', function(Y){ $js });";
2506 return $js."\n";
2510 * Returns code setting value to variable
2512 * @param string $name
2513 * @param mixed $value json serialised value
2514 * @param bool $usevar add var definition, ignored for nested properties
2515 * @return string JS code fragment
2517 public static function set_variable($name, $value, $usevar = true) {
2518 $output = '';
2520 if ($usevar) {
2521 if (strpos($name, '.')) {
2522 $output .= '';
2523 } else {
2524 $output .= 'var ';
2528 $output .= "$name = ".json_encode($value).";";
2530 return $output;
2534 * Writes event handler attaching code
2536 * @param array|string $selector standard YUI selector for elements, may be
2537 * array or string, element id is in the form "#idvalue"
2538 * @param string $event A valid DOM event (click, mousedown, change etc.)
2539 * @param string $function The name of the function to call
2540 * @param array $arguments An optional array of argument parameters to pass to the function
2541 * @return string JS code fragment
2543 public static function event_handler($selector, $event, $function, array $arguments = null) {
2544 $selector = json_encode($selector);
2545 $output = "Y.on('$event', $function, $selector, null";
2546 if (!empty($arguments)) {
2547 $output .= ', ' . json_encode($arguments);
2549 return $output . ");\n";
2554 * Holds all the information required to render a <table> by {@link core_renderer::table()}
2556 * Example of usage:
2557 * $t = new html_table();
2558 * ... // set various properties of the object $t as described below
2559 * echo html_writer::table($t);
2561 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
2562 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2563 * @since Moodle 2.0
2564 * @package core
2565 * @category output
2567 class html_table {
2570 * @var string Value to use for the id attribute of the table
2572 public $id = null;
2575 * @var array Attributes of HTML attributes for the <table> element
2577 public $attributes = array();
2580 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
2581 * For more control over the rendering of the headers, an array of html_table_cell objects
2582 * can be passed instead of an array of strings.
2584 * Example of usage:
2585 * $t->head = array('Student', 'Grade');
2587 public $head;
2590 * @var array An array that can be used to make a heading span multiple columns.
2591 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
2592 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
2594 * Example of usage:
2595 * $t->headspan = array(2,1);
2597 public $headspan;
2600 * @var array An array of column alignments.
2601 * The value is used as CSS 'text-align' property. Therefore, possible
2602 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
2603 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
2605 * Examples of usage:
2606 * $t->align = array(null, 'right');
2607 * or
2608 * $t->align[1] = 'right';
2610 public $align;
2613 * @var array The value is used as CSS 'size' property.
2615 * Examples of usage:
2616 * $t->size = array('50%', '50%');
2617 * or
2618 * $t->size[1] = '120px';
2620 public $size;
2623 * @var array An array of wrapping information.
2624 * The only possible value is 'nowrap' that sets the
2625 * CSS property 'white-space' to the value 'nowrap' in the given column.
2627 * Example of usage:
2628 * $t->wrap = array(null, 'nowrap');
2630 public $wrap;
2633 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2634 * $head specified, the string 'hr' (for horizontal ruler) can be used
2635 * instead of an array of cells data resulting in a divider rendered.
2637 * Example of usage with array of arrays:
2638 * $row1 = array('Harry Potter', '76 %');
2639 * $row2 = array('Hermione Granger', '100 %');
2640 * $t->data = array($row1, $row2);
2642 * Example with array of html_table_row objects: (used for more fine-grained control)
2643 * $cell1 = new html_table_cell();
2644 * $cell1->text = 'Harry Potter';
2645 * $cell1->colspan = 2;
2646 * $row1 = new html_table_row();
2647 * $row1->cells[] = $cell1;
2648 * $cell2 = new html_table_cell();
2649 * $cell2->text = 'Hermione Granger';
2650 * $cell3 = new html_table_cell();
2651 * $cell3->text = '100 %';
2652 * $row2 = new html_table_row();
2653 * $row2->cells = array($cell2, $cell3);
2654 * $t->data = array($row1, $row2);
2656 public $data = [];
2659 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2660 * @var string Width of the table, percentage of the page preferred.
2662 public $width = null;
2665 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2666 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2668 public $tablealign = null;
2671 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2672 * @var int Padding on each cell, in pixels
2674 public $cellpadding = null;
2677 * @var int Spacing between cells, in pixels
2678 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2680 public $cellspacing = null;
2683 * @var array Array of classes to add to particular rows, space-separated string.
2684 * Class 'lastrow' is added automatically for the last row in the table.
2686 * Example of usage:
2687 * $t->rowclasses[9] = 'tenth'
2689 public $rowclasses;
2692 * @var array An array of classes to add to every cell in a particular column,
2693 * space-separated string. Class 'cell' is added automatically by the renderer.
2694 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2695 * respectively. Class 'lastcol' is added automatically for all last cells
2696 * in a row.
2698 * Example of usage:
2699 * $t->colclasses = array(null, 'grade');
2701 public $colclasses;
2704 * @var string Description of the contents for screen readers.
2706 public $summary;
2709 * @var string Caption for the table, typically a title.
2711 * Example of usage:
2712 * $t->caption = "TV Guide";
2714 public $caption;
2717 * @var bool Whether to hide the table's caption from sighted users.
2719 * Example of usage:
2720 * $t->caption = "TV Guide";
2721 * $t->captionhide = true;
2723 public $captionhide = false;
2726 * Constructor
2728 public function __construct() {
2729 $this->attributes['class'] = '';
2734 * Component representing a table row.
2736 * @copyright 2009 Nicolas Connault
2737 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2738 * @since Moodle 2.0
2739 * @package core
2740 * @category output
2742 class html_table_row {
2745 * @var string Value to use for the id attribute of the row.
2747 public $id = null;
2750 * @var array Array of html_table_cell objects
2752 public $cells = array();
2755 * @var string Value to use for the style attribute of the table row
2757 public $style = null;
2760 * @var array Attributes of additional HTML attributes for the <tr> element
2762 public $attributes = array();
2765 * Constructor
2766 * @param array $cells
2768 public function __construct(array $cells=null) {
2769 $this->attributes['class'] = '';
2770 $cells = (array)$cells;
2771 foreach ($cells as $cell) {
2772 if ($cell instanceof html_table_cell) {
2773 $this->cells[] = $cell;
2774 } else {
2775 $this->cells[] = new html_table_cell($cell);
2782 * Component representing a table cell.
2784 * @copyright 2009 Nicolas Connault
2785 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2786 * @since Moodle 2.0
2787 * @package core
2788 * @category output
2790 class html_table_cell {
2793 * @var string Value to use for the id attribute of the cell.
2795 public $id = null;
2798 * @var string The contents of the cell.
2800 public $text;
2803 * @var string Abbreviated version of the contents of the cell.
2805 public $abbr = null;
2808 * @var int Number of columns this cell should span.
2810 public $colspan = null;
2813 * @var int Number of rows this cell should span.
2815 public $rowspan = null;
2818 * @var string Defines a way to associate header cells and data cells in a table.
2820 public $scope = null;
2823 * @var bool Whether or not this cell is a header cell.
2825 public $header = null;
2828 * @var string Value to use for the style attribute of the table cell
2830 public $style = null;
2833 * @var array Attributes of additional HTML attributes for the <td> element
2835 public $attributes = array();
2838 * Constructs a table cell
2840 * @param string $text
2842 public function __construct($text = null) {
2843 $this->text = $text;
2844 $this->attributes['class'] = '';
2849 * Component representing a paging bar.
2851 * @copyright 2009 Nicolas Connault
2852 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2853 * @since Moodle 2.0
2854 * @package core
2855 * @category output
2857 class paging_bar implements renderable, templatable {
2860 * @var int The maximum number of pagelinks to display.
2862 public $maxdisplay = 18;
2865 * @var int The total number of entries to be pages through..
2867 public $totalcount;
2870 * @var int The page you are currently viewing.
2872 public $page;
2875 * @var int The number of entries that should be shown per page.
2877 public $perpage;
2880 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2881 * an equals sign and the page number.
2882 * If this is a moodle_url object then the pagevar param will be replaced by
2883 * the page no, for each page.
2885 public $baseurl;
2888 * @var string This is the variable name that you use for the pagenumber in your
2889 * code (ie. 'tablepage', 'blogpage', etc)
2891 public $pagevar;
2894 * @var string A HTML link representing the "previous" page.
2896 public $previouslink = null;
2899 * @var string A HTML link representing the "next" page.
2901 public $nextlink = null;
2904 * @var string A HTML link representing the first page.
2906 public $firstlink = null;
2909 * @var string A HTML link representing the last page.
2911 public $lastlink = null;
2914 * @var array An array of strings. One of them is just a string: the current page
2916 public $pagelinks = array();
2919 * Constructor paging_bar with only the required params.
2921 * @param int $totalcount The total number of entries available to be paged through
2922 * @param int $page The page you are currently viewing
2923 * @param int $perpage The number of entries that should be shown per page
2924 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2925 * @param string $pagevar name of page parameter that holds the page number
2927 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2928 $this->totalcount = $totalcount;
2929 $this->page = $page;
2930 $this->perpage = $perpage;
2931 $this->baseurl = $baseurl;
2932 $this->pagevar = $pagevar;
2936 * Prepares the paging bar for output.
2938 * This method validates the arguments set up for the paging bar and then
2939 * produces fragments of HTML to assist display later on.
2941 * @param renderer_base $output
2942 * @param moodle_page $page
2943 * @param string $target
2944 * @throws coding_exception
2946 public function prepare(renderer_base $output, moodle_page $page, $target) {
2947 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2948 throw new coding_exception('paging_bar requires a totalcount value.');
2950 if (!isset($this->page) || is_null($this->page)) {
2951 throw new coding_exception('paging_bar requires a page value.');
2953 if (empty($this->perpage)) {
2954 throw new coding_exception('paging_bar requires a perpage value.');
2956 if (empty($this->baseurl)) {
2957 throw new coding_exception('paging_bar requires a baseurl value.');
2960 if ($this->totalcount > $this->perpage) {
2961 $pagenum = $this->page - 1;
2963 if ($this->page > 0) {
2964 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2967 if ($this->perpage > 0) {
2968 $lastpage = ceil($this->totalcount / $this->perpage);
2969 } else {
2970 $lastpage = 1;
2973 if ($this->page > round(($this->maxdisplay/3)*2)) {
2974 $currpage = $this->page - round($this->maxdisplay/3);
2976 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2977 } else {
2978 $currpage = 0;
2981 $displaycount = $displaypage = 0;
2983 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2984 $displaypage = $currpage + 1;
2986 if ($this->page == $currpage) {
2987 $this->pagelinks[] = html_writer::span($displaypage, 'current-page');
2988 } else {
2989 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2990 $this->pagelinks[] = $pagelink;
2993 $displaycount++;
2994 $currpage++;
2997 if ($currpage < $lastpage) {
2998 $lastpageactual = $lastpage - 1;
2999 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
3002 $pagenum = $this->page + 1;
3004 if ($pagenum != $lastpage) {
3005 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
3011 * Export for template.
3013 * @param renderer_base $output The renderer.
3014 * @return stdClass
3016 public function export_for_template(renderer_base $output) {
3017 $data = new stdClass();
3018 $data->previous = null;
3019 $data->next = null;
3020 $data->first = null;
3021 $data->last = null;
3022 $data->label = get_string('page');
3023 $data->pages = [];
3024 $data->haspages = $this->totalcount > $this->perpage;
3026 if (!$data->haspages) {
3027 return $data;
3030 if ($this->page > 0) {
3031 $data->previous = [
3032 'page' => $this->page - 1,
3033 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page - 1]))->out(false)
3037 $currpage = 0;
3038 if ($this->page > round(($this->maxdisplay / 3) * 2)) {
3039 $currpage = $this->page - round($this->maxdisplay / 3);
3040 $data->first = [
3041 'page' => 1,
3042 'url' => (new moodle_url($this->baseurl, [$this->pagevar => 0]))->out(false)
3046 $lastpage = 1;
3047 if ($this->perpage > 0) {
3048 $lastpage = ceil($this->totalcount / $this->perpage);
3051 $displaycount = 0;
3052 $displaypage = 0;
3053 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3054 $displaypage = $currpage + 1;
3056 $iscurrent = $this->page == $currpage;
3057 $link = new moodle_url($this->baseurl, [$this->pagevar => $currpage]);
3059 $data->pages[] = [
3060 'page' => $displaypage,
3061 'active' => $iscurrent,
3062 'url' => $iscurrent ? null : $link->out(false)
3065 $displaycount++;
3066 $currpage++;
3069 if ($currpage < $lastpage) {
3070 $data->last = [
3071 'page' => $lastpage,
3072 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $lastpage - 1]))->out(false)
3076 if ($this->page + 1 != $lastpage) {
3077 $data->next = [
3078 'page' => $this->page + 1,
3079 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page + 1]))->out(false)
3083 return $data;
3088 * Component representing initials bar.
3090 * @copyright 2017 Ilya Tregubov
3091 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3092 * @since Moodle 3.3
3093 * @package core
3094 * @category output
3096 class initials_bar implements renderable, templatable {
3099 * @var string Currently selected letter.
3101 public $current;
3104 * @var string Class name to add to this initial bar.
3106 public $class;
3109 * @var string The name to put in front of this initial bar.
3111 public $title;
3114 * @var string URL parameter name for this initial.
3116 public $urlvar;
3119 * @var string URL object.
3121 public $url;
3124 * @var array An array of letters in the alphabet.
3126 public $alpha;
3129 * Constructor initials_bar with only the required params.
3131 * @param string $current the currently selected letter.
3132 * @param string $class class name to add to this initial bar.
3133 * @param string $title the name to put in front of this initial bar.
3134 * @param string $urlvar URL parameter name for this initial.
3135 * @param string $url URL object.
3136 * @param array $alpha of letters in the alphabet.
3138 public function __construct($current, $class, $title, $urlvar, $url, $alpha = null) {
3139 $this->current = $current;
3140 $this->class = $class;
3141 $this->title = $title;
3142 $this->urlvar = $urlvar;
3143 $this->url = $url;
3144 $this->alpha = $alpha;
3148 * Export for template.
3150 * @param renderer_base $output The renderer.
3151 * @return stdClass
3153 public function export_for_template(renderer_base $output) {
3154 $data = new stdClass();
3156 if ($this->alpha == null) {
3157 $this->alpha = explode(',', get_string('alphabet', 'langconfig'));
3160 if ($this->current == 'all') {
3161 $this->current = '';
3164 // We want to find a letter grouping size which suits the language so
3165 // find the largest group size which is less than 15 chars.
3166 // The choice of 15 chars is the largest number of chars that reasonably
3167 // fits on the smallest supported screen size. By always using a max number
3168 // of groups which is a factor of 2, we always get nice wrapping, and the
3169 // last row is always the shortest.
3170 $groupsize = count($this->alpha);
3171 $groups = 1;
3172 while ($groupsize > 15) {
3173 $groups *= 2;
3174 $groupsize = ceil(count($this->alpha) / $groups);
3177 $groupsizelimit = 0;
3178 $groupnumber = 0;
3179 foreach ($this->alpha as $letter) {
3180 if ($groupsizelimit++ > 0 && $groupsizelimit % $groupsize == 1) {
3181 $groupnumber++;
3183 $groupletter = new stdClass();
3184 $groupletter->name = $letter;
3185 $groupletter->url = $this->url->out(false, array($this->urlvar => $letter));
3186 if ($letter == $this->current) {
3187 $groupletter->selected = $this->current;
3189 $data->group[$groupnumber]->letter[] = $groupletter;
3192 $data->class = $this->class;
3193 $data->title = $this->title;
3194 $data->url = $this->url->out(false, array($this->urlvar => ''));
3195 $data->current = $this->current;
3196 $data->all = get_string('all');
3198 return $data;
3203 * This class represents how a block appears on a page.
3205 * During output, each block instance is asked to return a block_contents object,
3206 * those are then passed to the $OUTPUT->block function for display.
3208 * contents should probably be generated using a moodle_block_..._renderer.
3210 * Other block-like things that need to appear on the page, for example the
3211 * add new block UI, are also represented as block_contents objects.
3213 * @copyright 2009 Tim Hunt
3214 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3215 * @since Moodle 2.0
3216 * @package core
3217 * @category output
3219 class block_contents {
3221 /** Used when the block cannot be collapsed **/
3222 const NOT_HIDEABLE = 0;
3224 /** Used when the block can be collapsed but currently is not **/
3225 const VISIBLE = 1;
3227 /** Used when the block has been collapsed **/
3228 const HIDDEN = 2;
3231 * @var int Used to set $skipid.
3233 protected static $idcounter = 1;
3236 * @var int All the blocks (or things that look like blocks) printed on
3237 * a page are given a unique number that can be used to construct id="" attributes.
3238 * This is set automatically be the {@link prepare()} method.
3239 * Do not try to set it manually.
3241 public $skipid;
3244 * @var int If this is the contents of a real block, this should be set
3245 * to the block_instance.id. Otherwise this should be set to 0.
3247 public $blockinstanceid = 0;
3250 * @var int If this is a real block instance, and there is a corresponding
3251 * block_position.id for the block on this page, this should be set to that id.
3252 * Otherwise it should be 0.
3254 public $blockpositionid = 0;
3257 * @var array An array of attribute => value pairs that are put on the outer div of this
3258 * block. {@link $id} and {@link $classes} attributes should be set separately.
3260 public $attributes;
3263 * @var string The title of this block. If this came from user input, it should already
3264 * have had format_string() processing done on it. This will be output inside
3265 * <h2> tags. Please do not cause invalid XHTML.
3267 public $title = '';
3270 * @var string The label to use when the block does not, or will not have a visible title.
3271 * You should never set this as well as title... it will just be ignored.
3273 public $arialabel = '';
3276 * @var string HTML for the content
3278 public $content = '';
3281 * @var array An alternative to $content, it you want a list of things with optional icons.
3283 public $footer = '';
3286 * @var string Any small print that should appear under the block to explain
3287 * to the teacher about the block, for example 'This is a sticky block that was
3288 * added in the system context.'
3290 public $annotation = '';
3293 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
3294 * the user can toggle whether this block is visible.
3296 public $collapsible = self::NOT_HIDEABLE;
3299 * Set this to true if the block is dockable.
3300 * @var bool
3302 public $dockable = false;
3305 * @var array A (possibly empty) array of editing controls. Each element of
3306 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
3307 * $icon is the icon name. Fed to $OUTPUT->image_url.
3309 public $controls = array();
3313 * Create new instance of block content
3314 * @param array $attributes
3316 public function __construct(array $attributes = null) {
3317 $this->skipid = self::$idcounter;
3318 self::$idcounter += 1;
3320 if ($attributes) {
3321 // standard block
3322 $this->attributes = $attributes;
3323 } else {
3324 // simple "fake" blocks used in some modules and "Add new block" block
3325 $this->attributes = array('class'=>'block');
3330 * Add html class to block
3332 * @param string $class
3334 public function add_class($class) {
3335 $this->attributes['class'] .= ' '.$class;
3341 * This class represents a target for where a block can go when it is being moved.
3343 * This needs to be rendered as a form with the given hidden from fields, and
3344 * clicking anywhere in the form should submit it. The form action should be
3345 * $PAGE->url.
3347 * @copyright 2009 Tim Hunt
3348 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3349 * @since Moodle 2.0
3350 * @package core
3351 * @category output
3353 class block_move_target {
3356 * @var moodle_url Move url
3358 public $url;
3361 * Constructor
3362 * @param moodle_url $url
3364 public function __construct(moodle_url $url) {
3365 $this->url = $url;
3370 * Custom menu item
3372 * This class is used to represent one item within a custom menu that may or may
3373 * not have children.
3375 * @copyright 2010 Sam Hemelryk
3376 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3377 * @since Moodle 2.0
3378 * @package core
3379 * @category output
3381 class custom_menu_item implements renderable, templatable {
3384 * @var string The text to show for the item
3386 protected $text;
3389 * @var moodle_url The link to give the icon if it has no children
3391 protected $url;
3394 * @var string A title to apply to the item. By default the text
3396 protected $title;
3399 * @var int A sort order for the item, not necessary if you order things in
3400 * the CFG var.
3402 protected $sort;
3405 * @var custom_menu_item A reference to the parent for this item or NULL if
3406 * it is a top level item
3408 protected $parent;
3411 * @var array A array in which to store children this item has.
3413 protected $children = array();
3416 * @var int A reference to the sort var of the last child that was added
3418 protected $lastsort = 0;
3421 * Constructs the new custom menu item
3423 * @param string $text
3424 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
3425 * @param string $title A title to apply to this item [Optional]
3426 * @param int $sort A sort or to use if we need to sort differently [Optional]
3427 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
3428 * belongs to, only if the child has a parent. [Optional]
3430 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
3431 $this->text = $text;
3432 $this->url = $url;
3433 $this->title = $title;
3434 $this->sort = (int)$sort;
3435 $this->parent = $parent;
3439 * Adds a custom menu item as a child of this node given its properties.
3441 * @param string $text
3442 * @param moodle_url $url
3443 * @param string $title
3444 * @param int $sort
3445 * @return custom_menu_item
3447 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
3448 $key = count($this->children);
3449 if (empty($sort)) {
3450 $sort = $this->lastsort + 1;
3452 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
3453 $this->lastsort = (int)$sort;
3454 return $this->children[$key];
3458 * Removes a custom menu item that is a child or descendant to the current menu.
3460 * Returns true if child was found and removed.
3462 * @param custom_menu_item $menuitem
3463 * @return bool
3465 public function remove_child(custom_menu_item $menuitem) {
3466 $removed = false;
3467 if (($key = array_search($menuitem, $this->children)) !== false) {
3468 unset($this->children[$key]);
3469 $this->children = array_values($this->children);
3470 $removed = true;
3471 } else {
3472 foreach ($this->children as $child) {
3473 if ($removed = $child->remove_child($menuitem)) {
3474 break;
3478 return $removed;
3482 * Returns the text for this item
3483 * @return string
3485 public function get_text() {
3486 return $this->text;
3490 * Returns the url for this item
3491 * @return moodle_url
3493 public function get_url() {
3494 return $this->url;
3498 * Returns the title for this item
3499 * @return string
3501 public function get_title() {
3502 return $this->title;
3506 * Sorts and returns the children for this item
3507 * @return array
3509 public function get_children() {
3510 $this->sort();
3511 return $this->children;
3515 * Gets the sort order for this child
3516 * @return int
3518 public function get_sort_order() {
3519 return $this->sort;
3523 * Gets the parent this child belong to
3524 * @return custom_menu_item
3526 public function get_parent() {
3527 return $this->parent;
3531 * Sorts the children this item has
3533 public function sort() {
3534 usort($this->children, array('custom_menu','sort_custom_menu_items'));
3538 * Returns true if this item has any children
3539 * @return bool
3541 public function has_children() {
3542 return (count($this->children) > 0);
3546 * Sets the text for the node
3547 * @param string $text
3549 public function set_text($text) {
3550 $this->text = (string)$text;
3554 * Sets the title for the node
3555 * @param string $title
3557 public function set_title($title) {
3558 $this->title = (string)$title;
3562 * Sets the url for the node
3563 * @param moodle_url $url
3565 public function set_url(moodle_url $url) {
3566 $this->url = $url;
3570 * Export this data so it can be used as the context for a mustache template.
3572 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
3573 * @return array
3575 public function export_for_template(renderer_base $output) {
3576 global $CFG;
3578 require_once($CFG->libdir . '/externallib.php');
3580 $syscontext = context_system::instance();
3582 $context = new stdClass();
3583 $context->text = external_format_string($this->text, $syscontext->id);
3584 $context->url = $this->url ? $this->url->out() : null;
3585 $context->title = external_format_string($this->title, $syscontext->id);
3586 $context->sort = $this->sort;
3587 $context->children = array();
3588 if (preg_match("/^#+$/", $this->text)) {
3589 $context->divider = true;
3591 $context->haschildren = !empty($this->children) && (count($this->children) > 0);
3592 foreach ($this->children as $child) {
3593 $child = $child->export_for_template($output);
3594 array_push($context->children, $child);
3597 return $context;
3602 * Custom menu class
3604 * This class is used to operate a custom menu that can be rendered for the page.
3605 * The custom menu is built using $CFG->custommenuitems and is a structured collection
3606 * of custom_menu_item nodes that can be rendered by the core renderer.
3608 * To configure the custom menu:
3609 * Settings: Administration > Appearance > Themes > Theme settings
3611 * @copyright 2010 Sam Hemelryk
3612 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3613 * @since Moodle 2.0
3614 * @package core
3615 * @category output
3617 class custom_menu extends custom_menu_item {
3620 * @var string The language we should render for, null disables multilang support.
3622 protected $currentlanguage = null;
3625 * Creates the custom menu
3627 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
3628 * @param string $currentlanguage the current language code, null disables multilang support
3630 public function __construct($definition = '', $currentlanguage = null) {
3631 $this->currentlanguage = $currentlanguage;
3632 parent::__construct('root'); // create virtual root element of the menu
3633 if (!empty($definition)) {
3634 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
3639 * Overrides the children of this custom menu. Useful when getting children
3640 * from $CFG->custommenuitems
3642 * @param array $children
3644 public function override_children(array $children) {
3645 $this->children = array();
3646 foreach ($children as $child) {
3647 if ($child instanceof custom_menu_item) {
3648 $this->children[] = $child;
3654 * Converts a string into a structured array of custom_menu_items which can
3655 * then be added to a custom menu.
3657 * Structure:
3658 * text|url|title|langs
3659 * The number of hyphens at the start determines the depth of the item. The
3660 * languages are optional, comma separated list of languages the line is for.
3662 * Example structure:
3663 * First level first item|http://www.moodle.com/
3664 * -Second level first item|http://www.moodle.com/partners/
3665 * -Second level second item|http://www.moodle.com/hq/
3666 * --Third level first item|http://www.moodle.com/jobs/
3667 * -Second level third item|http://www.moodle.com/development/
3668 * First level second item|http://www.moodle.com/feedback/
3669 * First level third item
3670 * English only|http://moodle.com|English only item|en
3671 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
3674 * @static
3675 * @param string $text the menu items definition
3676 * @param string $language the language code, null disables multilang support
3677 * @return array
3679 public static function convert_text_to_menu_nodes($text, $language = null) {
3680 $root = new custom_menu();
3681 $lastitem = $root;
3682 $lastdepth = 0;
3683 $hiddenitems = array();
3684 $lines = explode("\n", $text);
3685 foreach ($lines as $linenumber => $line) {
3686 $line = trim($line);
3687 if (strlen($line) == 0) {
3688 continue;
3690 // Parse item settings.
3691 $itemtext = null;
3692 $itemurl = null;
3693 $itemtitle = null;
3694 $itemvisible = true;
3695 $settings = explode('|', $line);
3696 foreach ($settings as $i => $setting) {
3697 $setting = trim($setting);
3698 if (!empty($setting)) {
3699 switch ($i) {
3700 case 0:
3701 $itemtext = ltrim($setting, '-');
3702 $itemtitle = $itemtext;
3703 break;
3704 case 1:
3705 try {
3706 $itemurl = new moodle_url($setting);
3707 } catch (moodle_exception $exception) {
3708 // We're not actually worried about this, we don't want to mess up the display
3709 // just for a wrongly entered URL.
3710 $itemurl = null;
3712 break;
3713 case 2:
3714 $itemtitle = $setting;
3715 break;
3716 case 3:
3717 if (!empty($language)) {
3718 $itemlanguages = array_map('trim', explode(',', $setting));
3719 $itemvisible &= in_array($language, $itemlanguages);
3721 break;
3725 // Get depth of new item.
3726 preg_match('/^(\-*)/', $line, $match);
3727 $itemdepth = strlen($match[1]) + 1;
3728 // Find parent item for new item.
3729 while (($lastdepth - $itemdepth) >= 0) {
3730 $lastitem = $lastitem->get_parent();
3731 $lastdepth--;
3733 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1);
3734 $lastdepth++;
3735 if (!$itemvisible) {
3736 $hiddenitems[] = $lastitem;
3739 foreach ($hiddenitems as $item) {
3740 $item->parent->remove_child($item);
3742 return $root->get_children();
3746 * Sorts two custom menu items
3748 * This function is designed to be used with the usort method
3749 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
3751 * @static
3752 * @param custom_menu_item $itema
3753 * @param custom_menu_item $itemb
3754 * @return int
3756 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
3757 $itema = $itema->get_sort_order();
3758 $itemb = $itemb->get_sort_order();
3759 if ($itema == $itemb) {
3760 return 0;
3762 return ($itema > $itemb) ? +1 : -1;
3767 * Stores one tab
3769 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3770 * @package core
3772 class tabobject implements renderable, templatable {
3773 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
3774 var $id;
3775 /** @var moodle_url|string link */
3776 var $link;
3777 /** @var string text on the tab */
3778 var $text;
3779 /** @var string title under the link, by defaul equals to text */
3780 var $title;
3781 /** @var bool whether to display a link under the tab name when it's selected */
3782 var $linkedwhenselected = false;
3783 /** @var bool whether the tab is inactive */
3784 var $inactive = false;
3785 /** @var bool indicates that this tab's child is selected */
3786 var $activated = false;
3787 /** @var bool indicates that this tab is selected */
3788 var $selected = false;
3789 /** @var array stores children tabobjects */
3790 var $subtree = array();
3791 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
3792 var $level = 1;
3795 * Constructor
3797 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
3798 * @param string|moodle_url $link
3799 * @param string $text text on the tab
3800 * @param string $title title under the link, by defaul equals to text
3801 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
3803 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
3804 $this->id = $id;
3805 $this->link = $link;
3806 $this->text = $text;
3807 $this->title = $title ? $title : $text;
3808 $this->linkedwhenselected = $linkedwhenselected;
3812 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
3814 * @param string $selected the id of the selected tab (whatever row it's on),
3815 * if null marks all tabs as unselected
3816 * @return bool whether this tab is selected or contains selected tab in its subtree
3818 protected function set_selected($selected) {
3819 if ((string)$selected === (string)$this->id) {
3820 $this->selected = true;
3821 // This tab is selected. No need to travel through subtree.
3822 return true;
3824 foreach ($this->subtree as $subitem) {
3825 if ($subitem->set_selected($selected)) {
3826 // This tab has child that is selected. Mark it as activated. No need to check other children.
3827 $this->activated = true;
3828 return true;
3831 return false;
3835 * Travels through tree and finds a tab with specified id
3837 * @param string $id
3838 * @return tabtree|null
3840 public function find($id) {
3841 if ((string)$this->id === (string)$id) {
3842 return $this;
3844 foreach ($this->subtree as $tab) {
3845 if ($obj = $tab->find($id)) {
3846 return $obj;
3849 return null;
3853 * Allows to mark each tab's level in the tree before rendering.
3855 * @param int $level
3857 protected function set_level($level) {
3858 $this->level = $level;
3859 foreach ($this->subtree as $tab) {
3860 $tab->set_level($level + 1);
3865 * Export for template.
3867 * @param renderer_base $output Renderer.
3868 * @return object
3870 public function export_for_template(renderer_base $output) {
3871 if ($this->inactive || ($this->selected && !$this->linkedwhenselected) || $this->activated) {
3872 $link = null;
3873 } else {
3874 $link = $this->link;
3876 $active = $this->activated || $this->selected;
3878 return (object) [
3879 'id' => $this->id,
3880 'link' => is_object($link) ? $link->out(false) : $link,
3881 'text' => $this->text,
3882 'title' => $this->title,
3883 'inactive' => !$active && $this->inactive,
3884 'active' => $active,
3885 'level' => $this->level,
3892 * Renderable for the main page header.
3894 * @package core
3895 * @category output
3896 * @since 2.9
3897 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
3898 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3900 class context_header implements renderable {
3903 * @var string $heading Main heading.
3905 public $heading;
3907 * @var int $headinglevel Main heading 'h' tag level.
3909 public $headinglevel;
3911 * @var string|null $imagedata HTML code for the picture in the page header.
3913 public $imagedata;
3915 * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
3916 * array elements - title => alternate text for the image, or if no image is available the button text.
3917 * url => Link for the button to head to. Should be a moodle_url.
3918 * image => location to the image, or name of the image in /pix/t/{image name}.
3919 * linkattributes => additional attributes for the <a href> element.
3920 * page => page object. Don't include if the image is an external image.
3922 public $additionalbuttons;
3925 * Constructor.
3927 * @param string $heading Main heading data.
3928 * @param int $headinglevel Main heading 'h' tag level.
3929 * @param string|null $imagedata HTML code for the picture in the page header.
3930 * @param string $additionalbuttons Buttons for the header e.g. Messaging button for the user header.
3932 public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null) {
3934 $this->heading = $heading;
3935 $this->headinglevel = $headinglevel;
3936 $this->imagedata = $imagedata;
3937 $this->additionalbuttons = $additionalbuttons;
3938 // If we have buttons then format them.
3939 if (isset($this->additionalbuttons)) {
3940 $this->format_button_images();
3945 * Adds an array element for a formatted image.
3947 protected function format_button_images() {
3949 foreach ($this->additionalbuttons as $buttontype => $button) {
3950 $page = $button['page'];
3951 // If no image is provided then just use the title.
3952 if (!isset($button['image'])) {
3953 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['title'];
3954 } else {
3955 // Check to see if this is an internal Moodle icon.
3956 $internalimage = $page->theme->resolve_image_location('t/' . $button['image'], 'moodle');
3957 if ($internalimage) {
3958 $this->additionalbuttons[$buttontype]['formattedimage'] = 't/' . $button['image'];
3959 } else {
3960 // Treat as an external image.
3961 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['image'];
3965 if (isset($button['linkattributes']['class'])) {
3966 $class = $button['linkattributes']['class'] . ' btn';
3967 } else {
3968 $class = 'btn';
3970 // Add the bootstrap 'btn' class for formatting.
3971 $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
3972 array('class' => $class));
3978 * Stores tabs list
3980 * Example how to print a single line tabs:
3981 * $rows = array(
3982 * new tabobject(...),
3983 * new tabobject(...)
3984 * );
3985 * echo $OUTPUT->tabtree($rows, $selectedid);
3987 * Multiple row tabs may not look good on some devices but if you want to use them
3988 * you can specify ->subtree for the active tabobject.
3990 * @copyright 2013 Marina Glancy
3991 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3992 * @since Moodle 2.5
3993 * @package core
3994 * @category output
3996 class tabtree extends tabobject {
3998 * Constuctor
4000 * It is highly recommended to call constructor when list of tabs is already
4001 * populated, this way you ensure that selected and inactive tabs are located
4002 * and attribute level is set correctly.
4004 * @param array $tabs array of tabs, each of them may have it's own ->subtree
4005 * @param string|null $selected which tab to mark as selected, all parent tabs will
4006 * automatically be marked as activated
4007 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4008 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
4010 public function __construct($tabs, $selected = null, $inactive = null) {
4011 $this->subtree = $tabs;
4012 if ($selected !== null) {
4013 $this->set_selected($selected);
4015 if ($inactive !== null) {
4016 if (is_array($inactive)) {
4017 foreach ($inactive as $id) {
4018 if ($tab = $this->find($id)) {
4019 $tab->inactive = true;
4022 } else if ($tab = $this->find($inactive)) {
4023 $tab->inactive = true;
4026 $this->set_level(0);
4030 * Export for template.
4032 * @param renderer_base $output Renderer.
4033 * @return object
4035 public function export_for_template(renderer_base $output) {
4036 $tabs = [];
4037 $secondrow = false;
4039 foreach ($this->subtree as $tab) {
4040 $tabs[] = $tab->export_for_template($output);
4041 if (!empty($tab->subtree) && ($tab->level == 0 || $tab->selected || $tab->activated)) {
4042 $secondrow = new tabtree($tab->subtree);
4046 return (object) [
4047 'tabs' => $tabs,
4048 'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false
4054 * An action menu.
4056 * This action menu component takes a series of primary and secondary actions.
4057 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
4058 * down menu.
4060 * @package core
4061 * @category output
4062 * @copyright 2013 Sam Hemelryk
4063 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4065 class action_menu implements renderable, templatable {
4068 * Top right alignment.
4070 const TL = 1;
4073 * Top right alignment.
4075 const TR = 2;
4078 * Top right alignment.
4080 const BL = 3;
4083 * Top right alignment.
4085 const BR = 4;
4088 * The instance number. This is unique to this instance of the action menu.
4089 * @var int
4091 protected $instance = 0;
4094 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
4095 * @var array
4097 protected $primaryactions = array();
4100 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
4101 * @var array
4103 protected $secondaryactions = array();
4106 * An array of attributes added to the container of the action menu.
4107 * Initialised with defaults during construction.
4108 * @var array
4110 public $attributes = array();
4112 * An array of attributes added to the container of the primary actions.
4113 * Initialised with defaults during construction.
4114 * @var array
4116 public $attributesprimary = array();
4118 * An array of attributes added to the container of the secondary actions.
4119 * Initialised with defaults during construction.
4120 * @var array
4122 public $attributessecondary = array();
4125 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
4126 * @var array
4128 public $actiontext = null;
4131 * An icon to use for the toggling the secondary menu (dropdown).
4132 * @var actionicon
4134 public $actionicon;
4137 * Any text to use for the toggling the secondary menu (dropdown).
4138 * @var menutrigger
4140 public $menutrigger = '';
4143 * Any extra classes for toggling to the secondary menu.
4144 * @var triggerextraclasses
4146 public $triggerextraclasses = '';
4149 * Place the action menu before all other actions.
4150 * @var prioritise
4152 public $prioritise = false;
4155 * Constructs the action menu with the given items.
4157 * @param array $actions An array of actions.
4159 public function __construct(array $actions = array()) {
4160 static $initialised = 0;
4161 $this->instance = $initialised;
4162 $initialised++;
4164 $this->attributes = array(
4165 'id' => 'action-menu-'.$this->instance,
4166 'class' => 'moodle-actionmenu',
4167 'data-enhance' => 'moodle-core-actionmenu'
4169 $this->attributesprimary = array(
4170 'id' => 'action-menu-'.$this->instance.'-menubar',
4171 'class' => 'menubar',
4172 'role' => 'menubar'
4174 $this->attributessecondary = array(
4175 'id' => 'action-menu-'.$this->instance.'-menu',
4176 'class' => 'menu',
4177 'data-rel' => 'menu-content',
4178 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
4179 'role' => 'menu'
4181 $this->set_alignment(self::TR, self::BR);
4182 foreach ($actions as $action) {
4183 $this->add($action);
4188 * Sets the menu trigger text.
4190 * @param string $trigger The text
4191 * @param string $extraclasses Extra classes to style the secondary menu toggle.
4192 * @return null
4194 public function set_menu_trigger($trigger, $extraclasses = '') {
4195 $this->menutrigger = $trigger;
4196 $this->triggerextraclasses = $extraclasses;
4200 * Return true if there is at least one visible link in the menu.
4202 * @return bool
4204 public function is_empty() {
4205 return !count($this->primaryactions) && !count($this->secondaryactions);
4209 * Initialises JS required fore the action menu.
4210 * The JS is only required once as it manages all action menu's on the page.
4212 * @param moodle_page $page
4214 public function initialise_js(moodle_page $page) {
4215 static $initialised = false;
4216 if (!$initialised) {
4217 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
4218 $initialised = true;
4223 * Adds an action to this action menu.
4225 * @param action_menu_link|pix_icon|string $action
4227 public function add($action) {
4228 if ($action instanceof action_link) {
4229 if ($action->primary) {
4230 $this->add_primary_action($action);
4231 } else {
4232 $this->add_secondary_action($action);
4234 } else if ($action instanceof pix_icon) {
4235 $this->add_primary_action($action);
4236 } else {
4237 $this->add_secondary_action($action);
4242 * Adds a primary action to the action menu.
4244 * @param action_menu_link|action_link|pix_icon|string $action
4246 public function add_primary_action($action) {
4247 if ($action instanceof action_link || $action instanceof pix_icon) {
4248 $action->attributes['role'] = 'menuitem';
4249 if ($action instanceof action_menu_link) {
4250 $action->actionmenu = $this;
4253 $this->primaryactions[] = $action;
4257 * Adds a secondary action to the action menu.
4259 * @param action_link|pix_icon|string $action
4261 public function add_secondary_action($action) {
4262 if ($action instanceof action_link || $action instanceof pix_icon) {
4263 $action->attributes['role'] = 'menuitem';
4264 if ($action instanceof action_menu_link) {
4265 $action->actionmenu = $this;
4268 $this->secondaryactions[] = $action;
4272 * Returns the primary actions ready to be rendered.
4274 * @param core_renderer $output The renderer to use for getting icons.
4275 * @return array
4277 public function get_primary_actions(core_renderer $output = null) {
4278 global $OUTPUT;
4279 if ($output === null) {
4280 $output = $OUTPUT;
4282 $pixicon = $this->actionicon;
4283 $linkclasses = array('toggle-display');
4285 $title = '';
4286 if (!empty($this->menutrigger)) {
4287 $pixicon = '<b class="caret"></b>';
4288 $linkclasses[] = 'textmenu';
4289 } else {
4290 $title = new lang_string('actions', 'moodle');
4291 $this->actionicon = new pix_icon(
4292 't/edit_menu',
4294 'moodle',
4295 array('class' => 'iconsmall actionmenu', 'title' => '')
4297 $pixicon = $this->actionicon;
4299 if ($pixicon instanceof renderable) {
4300 $pixicon = $output->render($pixicon);
4301 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
4302 $title = $pixicon->attributes['alt'];
4305 $string = '';
4306 if ($this->actiontext) {
4307 $string = $this->actiontext;
4309 $actions = $this->primaryactions;
4310 $attributes = array(
4311 'class' => implode(' ', $linkclasses),
4312 'title' => $title,
4313 'id' => 'action-menu-toggle-'.$this->instance,
4314 'role' => 'menuitem'
4316 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
4317 if ($this->prioritise) {
4318 array_unshift($actions, $link);
4319 } else {
4320 $actions[] = $link;
4322 return $actions;
4326 * Returns the secondary actions ready to be rendered.
4327 * @return array
4329 public function get_secondary_actions() {
4330 return $this->secondaryactions;
4334 * Sets the selector that should be used to find the owning node of this menu.
4335 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
4337 public function set_owner_selector($selector) {
4338 $this->attributes['data-owner'] = $selector;
4342 * Sets the alignment of the dialogue in relation to button used to toggle it.
4344 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4345 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4347 public function set_alignment($dialogue, $button) {
4348 if (isset($this->attributessecondary['data-align'])) {
4349 // We've already got one set, lets remove the old class so as to avoid troubles.
4350 $class = $this->attributessecondary['class'];
4351 $search = 'align-'.$this->attributessecondary['data-align'];
4352 $this->attributessecondary['class'] = str_replace($search, '', $class);
4354 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
4355 $this->attributessecondary['data-align'] = $align;
4356 $this->attributessecondary['class'] .= ' align-'.$align;
4360 * Returns a string to describe the alignment.
4362 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4363 * @return string
4365 protected function get_align_string($align) {
4366 switch ($align) {
4367 case self::TL :
4368 return 'tl';
4369 case self::TR :
4370 return 'tr';
4371 case self::BL :
4372 return 'bl';
4373 case self::BR :
4374 return 'br';
4375 default :
4376 return 'tl';
4381 * Sets a constraint for the dialogue.
4383 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
4384 * element the constraint identifies.
4386 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
4388 public function set_constraint($ancestorselector) {
4389 $this->attributessecondary['data-constraint'] = $ancestorselector;
4393 * If you call this method the action menu will be displayed but will not be enhanced.
4395 * By not displaying the menu enhanced all items will be displayed in a single row.
4397 * @deprecated since Moodle 3.2
4399 public function do_not_enhance() {
4400 debugging('The method action_menu::do_not_enhance() is deprecated, use a list of action_icon instead.', DEBUG_DEVELOPER);
4404 * Returns true if this action menu will be enhanced.
4406 * @return bool
4408 public function will_be_enhanced() {
4409 return isset($this->attributes['data-enhance']);
4413 * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
4415 * This property can be useful when the action menu is displayed within a parent element that is either floated
4416 * or relatively positioned.
4417 * In that situation the width of the menu is determined by the width of the parent element which may not be large
4418 * enough for the menu items without them wrapping.
4419 * This disables the wrapping so that the menu takes on the width of the longest item.
4421 * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
4423 public function set_nowrap_on_items($value = true) {
4424 $class = 'nowrap-items';
4425 if (!empty($this->attributes['class'])) {
4426 $pos = strpos($this->attributes['class'], $class);
4427 if ($value === true && $pos === false) {
4428 // The value is true and the class has not been set yet. Add it.
4429 $this->attributes['class'] .= ' '.$class;
4430 } else if ($value === false && $pos !== false) {
4431 // The value is false and the class has been set. Remove it.
4432 $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class));
4434 } else if ($value) {
4435 // The value is true and the class has not been set yet. Add it.
4436 $this->attributes['class'] = $class;
4441 * Export for template.
4443 * @param renderer_base $output The renderer.
4444 * @return stdClass
4446 public function export_for_template(renderer_base $output) {
4447 $data = new stdClass();
4448 $attributes = $this->attributes;
4449 $attributesprimary = $this->attributesprimary;
4450 $attributessecondary = $this->attributessecondary;
4452 $data->instance = $this->instance;
4454 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
4455 unset($attributes['class']);
4457 $data->attributes = array_map(function($key, $value) {
4458 return [ 'name' => $key, 'value' => $value ];
4459 }, array_keys($attributes), $attributes);
4461 $primary = new stdClass();
4462 $primary->title = '';
4463 $primary->prioritise = $this->prioritise;
4465 $primary->classes = isset($attributesprimary['class']) ? $attributesprimary['class'] : '';
4466 unset($attributesprimary['class']);
4467 $primary->attributes = array_map(function($key, $value) {
4468 return [ 'name' => $key, 'value' => $value ];
4469 }, array_keys($attributesprimary), $attributesprimary);
4471 $actionicon = $this->actionicon;
4472 if (!empty($this->menutrigger)) {
4473 $primary->menutrigger = $this->menutrigger;
4474 $primary->triggerextraclasses = $this->triggerextraclasses;
4475 } else {
4476 $primary->title = get_string('actions');
4477 $actionicon = new pix_icon('t/edit_menu', '', 'moodle', ['class' => 'iconsmall actionmenu', 'title' => '']);
4480 if ($actionicon instanceof pix_icon) {
4481 $primary->icon = $actionicon->export_for_pix();
4482 if (!empty($actionicon->attributes['alt'])) {
4483 $primary->title = $actionicon->attributes['alt'];
4485 } else {
4486 $primary->iconraw = $actionicon ? $output->render($actionicon) : '';
4489 $primary->actiontext = $this->actiontext ? (string) $this->actiontext : '';
4490 $primary->items = array_map(function($item) use ($output) {
4491 $data = (object) [];
4492 if ($item instanceof action_menu_link) {
4493 $data->actionmenulink = $item->export_for_template($output);
4494 } else if ($item instanceof action_menu_filler) {
4495 $data->actionmenufiller = $item->export_for_template($output);
4496 } else if ($item instanceof action_link) {
4497 $data->actionlink = $item->export_for_template($output);
4498 } else if ($item instanceof pix_icon) {
4499 $data->pixicon = $item->export_for_template($output);
4500 } else {
4501 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4503 return $data;
4504 }, $this->primaryactions);
4506 $secondary = new stdClass();
4507 $secondary->classes = isset($attributessecondary['class']) ? $attributessecondary['class'] : '';
4508 unset($attributessecondary['class']);
4509 $secondary->attributes = array_map(function($key, $value) {
4510 return [ 'name' => $key, 'value' => $value ];
4511 }, array_keys($attributessecondary), $attributessecondary);
4512 $secondary->items = array_map(function($item) use ($output) {
4513 $data = (object) [];
4514 if ($item instanceof action_menu_link) {
4515 $data->actionmenulink = $item->export_for_template($output);
4516 } else if ($item instanceof action_menu_filler) {
4517 $data->actionmenufiller = $item->export_for_template($output);
4518 } else if ($item instanceof action_link) {
4519 $data->actionlink = $item->export_for_template($output);
4520 } else if ($item instanceof pix_icon) {
4521 $data->pixicon = $item->export_for_template($output);
4522 } else {
4523 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4525 return $data;
4526 }, $this->secondaryactions);
4528 $data->primary = $primary;
4529 $data->secondary = $secondary;
4531 return $data;
4537 * An action menu filler
4539 * @package core
4540 * @category output
4541 * @copyright 2013 Andrew Nicols
4542 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4544 class action_menu_filler extends action_link implements renderable {
4547 * True if this is a primary action. False if not.
4548 * @var bool
4550 public $primary = true;
4553 * Constructs the object.
4555 public function __construct() {
4560 * An action menu action
4562 * @package core
4563 * @category output
4564 * @copyright 2013 Sam Hemelryk
4565 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4567 class action_menu_link extends action_link implements renderable {
4570 * True if this is a primary action. False if not.
4571 * @var bool
4573 public $primary = true;
4576 * The action menu this link has been added to.
4577 * @var action_menu
4579 public $actionmenu = null;
4582 * Constructs the object.
4584 * @param moodle_url $url The URL for the action.
4585 * @param pix_icon $icon The icon to represent the action.
4586 * @param string $text The text to represent the action.
4587 * @param bool $primary Whether this is a primary action or not.
4588 * @param array $attributes Any attribtues associated with the action.
4590 public function __construct(moodle_url $url, pix_icon $icon = null, $text, $primary = true, array $attributes = array()) {
4591 parent::__construct($url, $text, null, $attributes, $icon);
4592 $this->primary = (bool)$primary;
4593 $this->add_class('menu-action');
4594 $this->attributes['role'] = 'menuitem';
4598 * Export for template.
4600 * @param renderer_base $output The renderer.
4601 * @return stdClass
4603 public function export_for_template(renderer_base $output) {
4604 static $instance = 1;
4606 $data = parent::export_for_template($output);
4607 $data->instance = $instance++;
4609 // Ignore what the parent did with the attributes, except for ID and class.
4610 $data->attributes = [];
4611 $attributes = $this->attributes;
4612 unset($attributes['id']);
4613 unset($attributes['class']);
4615 // Handle text being a renderable.
4616 if ($this->text instanceof renderable) {
4617 $data->text = $this->render($this->text);
4620 $data->showtext = (!$this->icon || $this->primary === false);
4622 $data->icon = null;
4623 if ($this->icon) {
4624 $icon = $this->icon;
4625 if ($this->primary || !$this->actionmenu->will_be_enhanced()) {
4626 $attributes['title'] = $data->text;
4628 $data->icon = $icon ? $icon->export_for_pix() : null;
4631 $data->disabled = !empty($attributes['disabled']);
4632 unset($attributes['disabled']);
4634 $data->attributes = array_map(function($key, $value) {
4635 return [
4636 'name' => $key,
4637 'value' => $value
4639 }, array_keys($attributes), $attributes);
4641 return $data;
4646 * A primary action menu action
4648 * @package core
4649 * @category output
4650 * @copyright 2013 Sam Hemelryk
4651 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4653 class action_menu_link_primary extends action_menu_link {
4655 * Constructs the object.
4657 * @param moodle_url $url
4658 * @param pix_icon $icon
4659 * @param string $text
4660 * @param array $attributes
4662 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
4663 parent::__construct($url, $icon, $text, true, $attributes);
4668 * A secondary action menu action
4670 * @package core
4671 * @category output
4672 * @copyright 2013 Sam Hemelryk
4673 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4675 class action_menu_link_secondary extends action_menu_link {
4677 * Constructs the object.
4679 * @param moodle_url $url
4680 * @param pix_icon $icon
4681 * @param string $text
4682 * @param array $attributes
4684 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
4685 parent::__construct($url, $icon, $text, false, $attributes);
4690 * Represents a set of preferences groups.
4692 * @package core
4693 * @category output
4694 * @copyright 2015 Frédéric Massart - FMCorz.net
4695 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4697 class preferences_groups implements renderable {
4700 * Array of preferences_group.
4701 * @var array
4703 public $groups;
4706 * Constructor.
4707 * @param array $groups of preferences_group
4709 public function __construct($groups) {
4710 $this->groups = $groups;
4716 * Represents a group of preferences page link.
4718 * @package core
4719 * @category output
4720 * @copyright 2015 Frédéric Massart - FMCorz.net
4721 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4723 class preferences_group implements renderable {
4726 * Title of the group.
4727 * @var string
4729 public $title;
4732 * Array of navigation_node.
4733 * @var array
4735 public $nodes;
4738 * Constructor.
4739 * @param string $title The title.
4740 * @param array $nodes of navigation_node.
4742 public function __construct($title, $nodes) {
4743 $this->title = $title;
4744 $this->nodes = $nodes;
4749 * Progress bar class.
4751 * Manages the display of a progress bar.
4753 * To use this class.
4754 * - construct
4755 * - call create (or use the 3rd param to the constructor)
4756 * - call update or update_full() or update() repeatedly
4758 * @copyright 2008 jamiesensei
4759 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4760 * @package core
4761 * @category output
4763 class progress_bar implements renderable, templatable {
4764 /** @var string html id */
4765 private $html_id;
4766 /** @var int total width */
4767 private $width;
4768 /** @var int last percentage printed */
4769 private $percent = 0;
4770 /** @var int time when last printed */
4771 private $lastupdate = 0;
4772 /** @var int when did we start printing this */
4773 private $time_start = 0;
4776 * Constructor
4778 * Prints JS code if $autostart true.
4780 * @param string $htmlid The container ID.
4781 * @param int $width The suggested width.
4782 * @param bool $autostart Whether to start the progress bar right away.
4784 public function __construct($htmlid = '', $width = 500, $autostart = false) {
4785 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
4786 debugging('progress_bar used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', DEBUG_DEVELOPER);
4789 if (!empty($htmlid)) {
4790 $this->html_id = $htmlid;
4791 } else {
4792 $this->html_id = 'pbar_'.uniqid();
4795 $this->width = $width;
4797 if ($autostart) {
4798 $this->create();
4803 * Create a new progress bar, this function will output html.
4805 * @return void Echo's output
4807 public function create() {
4808 global $OUTPUT;
4810 $this->time_start = microtime(true);
4811 if (CLI_SCRIPT) {
4812 return; // Temporary solution for cli scripts.
4815 flush();
4816 echo $OUTPUT->render($this);
4817 flush();
4821 * Update the progress bar.
4823 * @param int $percent From 1-100.
4824 * @param string $msg The message.
4825 * @return void Echo's output
4826 * @throws coding_exception
4828 private function _update($percent, $msg) {
4829 if (empty($this->time_start)) {
4830 throw new coding_exception('You must call create() (or use the $autostart ' .
4831 'argument to the constructor) before you try updating the progress bar.');
4834 if (CLI_SCRIPT) {
4835 return; // Temporary solution for cli scripts.
4838 $estimate = $this->estimate($percent);
4840 if ($estimate === null) {
4841 // Always do the first and last updates.
4842 } else if ($estimate == 0) {
4843 // Always do the last updates.
4844 } else if ($this->lastupdate + 20 < time()) {
4845 // We must update otherwise browser would time out.
4846 } else if (round($this->percent, 2) === round($percent, 2)) {
4847 // No significant change, no need to update anything.
4848 return;
4851 $estimatemsg = null;
4852 if (is_numeric($estimate)) {
4853 $estimatemsg = get_string('secondsleft', 'moodle', round($estimate, 2));
4856 $this->percent = round($percent, 2);
4857 $this->lastupdate = microtime(true);
4859 echo html_writer::script(js_writer::function_call('updateProgressBar',
4860 array($this->html_id, $this->percent, $msg, $estimatemsg)));
4861 flush();
4865 * Estimate how much time it is going to take.
4867 * @param int $pt From 1-100.
4868 * @return mixed Null (unknown), or int.
4870 private function estimate($pt) {
4871 if ($this->lastupdate == 0) {
4872 return null;
4874 if ($pt < 0.00001) {
4875 return null; // We do not know yet how long it will take.
4877 if ($pt > 99.99999) {
4878 return 0; // Nearly done, right?
4880 $consumed = microtime(true) - $this->time_start;
4881 if ($consumed < 0.001) {
4882 return null;
4885 return (100 - $pt) * ($consumed / $pt);
4889 * Update progress bar according percent.
4891 * @param int $percent From 1-100.
4892 * @param string $msg The message needed to be shown.
4894 public function update_full($percent, $msg) {
4895 $percent = max(min($percent, 100), 0);
4896 $this->_update($percent, $msg);
4900 * Update progress bar according the number of tasks.
4902 * @param int $cur Current task number.
4903 * @param int $total Total task number.
4904 * @param string $msg The message needed to be shown.
4906 public function update($cur, $total, $msg) {
4907 $percent = ($cur / $total) * 100;
4908 $this->update_full($percent, $msg);
4912 * Restart the progress bar.
4914 public function restart() {
4915 $this->percent = 0;
4916 $this->lastupdate = 0;
4917 $this->time_start = 0;
4921 * Export for template.
4923 * @param renderer_base $output The renderer.
4924 * @return array
4926 public function export_for_template(renderer_base $output) {
4927 return [
4928 'id' => $this->html_id,
4929 'width' => $this->width,