MDL-51177 core: Ignore built files in stylelint
[moodle.git] / lib / outputcomponents.php
blobd4850dab21b347de8f3d5320334112940d6fc30d
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 * @var bool Include user authentication token.
212 public $includetoken = false;
215 * User picture constructor.
217 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
218 * It is recommended to add also contextid of the user for performance reasons.
220 public function __construct(stdClass $user) {
221 global $DB;
223 if (empty($user->id)) {
224 throw new coding_exception('User id is required when printing user avatar image.');
227 // only touch the DB if we are missing data and complain loudly...
228 $needrec = false;
229 foreach (self::$fields as $field) {
230 if (!array_key_exists($field, $user)) {
231 $needrec = true;
232 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
233 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
234 break;
238 if ($needrec) {
239 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
240 } else {
241 $this->user = clone($user);
246 * Returns a list of required user fields, useful when fetching required user info from db.
248 * In some cases we have to fetch the user data together with some other information,
249 * the idalias is useful there because the id would otherwise override the main
250 * id of the result record. Please note it has to be converted back to id before rendering.
252 * @param string $tableprefix name of database table prefix in query
253 * @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)
254 * @param string $idalias alias of id field
255 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
256 * @return string
258 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
259 if (!$tableprefix and !$extrafields and !$idalias) {
260 return implode(',', self::$fields);
262 if ($tableprefix) {
263 $tableprefix .= '.';
265 foreach (self::$fields as $field) {
266 if ($field === 'id' and $idalias and $idalias !== 'id') {
267 $fields[$field] = "$tableprefix$field AS $idalias";
268 } else {
269 if ($fieldprefix and $field !== 'id') {
270 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
271 } else {
272 $fields[$field] = "$tableprefix$field";
276 // add extra fields if not already there
277 if ($extrafields) {
278 foreach ($extrafields as $e) {
279 if ($e === 'id' or isset($fields[$e])) {
280 continue;
282 if ($fieldprefix) {
283 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
284 } else {
285 $fields[$e] = "$tableprefix$e";
289 return implode(',', $fields);
293 * Extract the aliased user fields from a given record
295 * Given a record that was previously obtained using {@link self::fields()} with aliases,
296 * this method extracts user related unaliased fields.
298 * @param stdClass $record containing user picture fields
299 * @param array $extrafields extra fields included in the $record
300 * @param string $idalias alias of the id field
301 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
302 * @return stdClass object with unaliased user fields
304 public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
306 if (empty($idalias)) {
307 $idalias = 'id';
310 $return = new stdClass();
312 foreach (self::$fields as $field) {
313 if ($field === 'id') {
314 if (property_exists($record, $idalias)) {
315 $return->id = $record->{$idalias};
317 } else {
318 if (property_exists($record, $fieldprefix.$field)) {
319 $return->{$field} = $record->{$fieldprefix.$field};
323 // add extra fields if not already there
324 if ($extrafields) {
325 foreach ($extrafields as $e) {
326 if ($e === 'id' or property_exists($return, $e)) {
327 continue;
329 $return->{$e} = $record->{$fieldprefix.$e};
333 return $return;
337 * Works out the URL for the users picture.
339 * This method is recommended as it avoids costly redirects of user pictures
340 * if requests are made for non-existent files etc.
342 * @param moodle_page $page
343 * @param renderer_base $renderer
344 * @return moodle_url
346 public function get_url(moodle_page $page, renderer_base $renderer = null) {
347 global $CFG;
349 if (is_null($renderer)) {
350 $renderer = $page->get_renderer('core');
353 // Sort out the filename and size. Size is only required for the gravatar
354 // implementation presently.
355 if (empty($this->size)) {
356 $filename = 'f2';
357 $size = 35;
358 } else if ($this->size === true or $this->size == 1) {
359 $filename = 'f1';
360 $size = 100;
361 } else if ($this->size > 100) {
362 $filename = 'f3';
363 $size = (int)$this->size;
364 } else if ($this->size >= 50) {
365 $filename = 'f1';
366 $size = (int)$this->size;
367 } else {
368 $filename = 'f2';
369 $size = (int)$this->size;
372 $defaulturl = $renderer->image_url('u/'.$filename); // default image
374 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
375 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
376 // Protect images if login required and not logged in;
377 // also if login is required for profile images and is not logged in or guest
378 // do not use require_login() because it is expensive and not suitable here anyway.
379 return $defaulturl;
382 // First try to detect deleted users - but do not read from database for performance reasons!
383 if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
384 // All deleted users should have email replaced by md5 hash,
385 // all active users are expected to have valid email.
386 return $defaulturl;
389 // Did the user upload a picture?
390 if ($this->user->picture > 0) {
391 if (!empty($this->user->contextid)) {
392 $contextid = $this->user->contextid;
393 } else {
394 $context = context_user::instance($this->user->id, IGNORE_MISSING);
395 if (!$context) {
396 // This must be an incorrectly deleted user, all other users have context.
397 return $defaulturl;
399 $contextid = $context->id;
402 $path = '/';
403 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
404 // We append the theme name to the file path if we have it so that
405 // in the circumstance that the profile picture is not available
406 // when the user actually requests it they still get the profile
407 // picture for the correct theme.
408 $path .= $page->theme->name.'/';
410 // Set the image URL to the URL for the uploaded file and return.
411 $url = moodle_url::make_pluginfile_url(
412 $contextid, 'user', 'icon', null, $path, $filename, false, $this->includetoken);
413 $url->param('rev', $this->user->picture);
414 return $url;
417 if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
418 // Normalise the size variable to acceptable bounds
419 if ($size < 1 || $size > 512) {
420 $size = 35;
422 // Hash the users email address
423 $md5 = md5(strtolower(trim($this->user->email)));
424 // Build a gravatar URL with what we know.
426 // Find the best default image URL we can (MDL-35669)
427 if (empty($CFG->gravatardefaulturl)) {
428 $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
429 if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
430 $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
431 } else {
432 $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
434 } else {
435 $gravatardefault = $CFG->gravatardefaulturl;
438 // If the currently requested page is https then we'll return an
439 // https gravatar page.
440 if (is_https()) {
441 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
442 } else {
443 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
447 return $defaulturl;
452 * Data structure representing a help icon.
454 * @copyright 2010 Petr Skoda (info@skodak.org)
455 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
456 * @since Moodle 2.0
457 * @package core
458 * @category output
460 class help_icon implements renderable, templatable {
463 * @var string lang pack identifier (without the "_help" suffix),
464 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
465 * must exist.
467 public $identifier;
470 * @var string Component name, the same as in get_string()
472 public $component;
475 * @var string Extra descriptive text next to the icon
477 public $linktext = null;
480 * Constructor
482 * @param string $identifier string for help page title,
483 * string with _help suffix is used for the actual help text.
484 * string with _link suffix is used to create a link to further info (if it exists)
485 * @param string $component
487 public function __construct($identifier, $component) {
488 $this->identifier = $identifier;
489 $this->component = $component;
493 * Verifies that both help strings exists, shows debug warnings if not
495 public function diag_strings() {
496 $sm = get_string_manager();
497 if (!$sm->string_exists($this->identifier, $this->component)) {
498 debugging("Help title string does not exist: [$this->identifier, $this->component]");
500 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
501 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
506 * Export this data so it can be used as the context for a mustache template.
508 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
509 * @return array
511 public function export_for_template(renderer_base $output) {
512 global $CFG;
514 $title = get_string($this->identifier, $this->component);
516 if (empty($this->linktext)) {
517 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
518 } else {
519 $alt = get_string('helpwiththis');
522 $data = get_formatted_help_string($this->identifier, $this->component, false);
524 $data->alt = $alt;
525 $data->icon = (new pix_icon('help', $alt, 'core', ['class' => 'iconhelp']))->export_for_template($output);
526 $data->linktext = $this->linktext;
527 $data->title = get_string('helpprefix2', '', trim($title, ". \t"));
528 $data->url = (new moodle_url('/help.php', [
529 'component' => $this->component,
530 'identifier' => $this->identifier,
531 'lang' => current_language()
532 ]))->out(false);
534 $data->ltr = !right_to_left();
535 return $data;
541 * Data structure representing an icon font.
543 * @copyright 2016 Damyon Wiese
544 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
545 * @package core
546 * @category output
548 class pix_icon_font implements templatable {
551 * @var pix_icon $pixicon The original icon.
553 private $pixicon = null;
556 * @var string $key The mapped key.
558 private $key;
561 * @var bool $mapped The icon could not be mapped.
563 private $mapped;
566 * Constructor
568 * @param pix_icon $pixicon The original icon
570 public function __construct(pix_icon $pixicon) {
571 global $PAGE;
573 $this->pixicon = $pixicon;
574 $this->mapped = false;
575 $iconsystem = \core\output\icon_system::instance();
577 $this->key = $iconsystem->remap_icon_name($pixicon->pix, $pixicon->component);
578 if (!empty($this->key)) {
579 $this->mapped = true;
584 * Return true if this pix_icon was successfully mapped to an icon font.
586 * @return bool
588 public function is_mapped() {
589 return $this->mapped;
593 * Export this data so it can be used as the context for a mustache template.
595 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
596 * @return array
598 public function export_for_template(renderer_base $output) {
600 $pixdata = $this->pixicon->export_for_template($output);
602 $title = isset($this->pixicon->attributes['title']) ? $this->pixicon->attributes['title'] : '';
603 $alt = isset($this->pixicon->attributes['alt']) ? $this->pixicon->attributes['alt'] : '';
604 if (empty($title)) {
605 $title = $alt;
607 $data = array(
608 'extraclasses' => $pixdata['extraclasses'],
609 'title' => $title,
610 'alt' => $alt,
611 'key' => $this->key
614 return $data;
619 * Data structure representing an icon subtype.
621 * @copyright 2016 Damyon Wiese
622 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
623 * @package core
624 * @category output
626 class pix_icon_fontawesome extends pix_icon_font {
631 * Data structure representing an icon.
633 * @copyright 2010 Petr Skoda
634 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
635 * @since Moodle 2.0
636 * @package core
637 * @category output
639 class pix_icon implements renderable, templatable {
642 * @var string The icon name
644 var $pix;
647 * @var string The component the icon belongs to.
649 var $component;
652 * @var array An array of attributes to use on the icon
654 var $attributes = array();
657 * Constructor
659 * @param string $pix short icon name
660 * @param string $alt The alt text to use for the icon
661 * @param string $component component name
662 * @param array $attributes html attributes
664 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
665 global $PAGE;
667 $this->pix = $pix;
668 $this->component = $component;
669 $this->attributes = (array)$attributes;
671 if (empty($this->attributes['class'])) {
672 $this->attributes['class'] = '';
675 // Set an additional class for big icons so that they can be styled properly.
676 if (substr($pix, 0, 2) === 'b/') {
677 $this->attributes['class'] .= ' iconsize-big';
680 // If the alt is empty, don't place it in the attributes, otherwise it will override parent alt text.
681 if (!is_null($alt)) {
682 $this->attributes['alt'] = $alt;
684 // If there is no title, set it to the attribute.
685 if (!isset($this->attributes['title'])) {
686 $this->attributes['title'] = $this->attributes['alt'];
688 } else {
689 unset($this->attributes['alt']);
692 if (empty($this->attributes['title'])) {
693 // Remove the title attribute if empty, we probably want to use the parent node's title
694 // and some browsers might overwrite it with an empty title.
695 unset($this->attributes['title']);
700 * Export this data so it can be used as the context for a mustache template.
702 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
703 * @return array
705 public function export_for_template(renderer_base $output) {
706 $attributes = $this->attributes;
707 $extraclasses = '';
709 foreach ($attributes as $key => $item) {
710 if ($key == 'class') {
711 $extraclasses = $item;
712 unset($attributes[$key]);
713 break;
717 $attributes['src'] = $output->image_url($this->pix, $this->component)->out(false);
718 $templatecontext = array();
719 foreach ($attributes as $name => $value) {
720 $templatecontext[] = array('name' => $name, 'value' => $value);
722 $title = isset($attributes['title']) ? $attributes['title'] : '';
723 if (empty($title)) {
724 $title = isset($attributes['alt']) ? $attributes['alt'] : '';
726 $data = array(
727 'attributes' => $templatecontext,
728 'extraclasses' => $extraclasses
731 return $data;
735 * Much simpler version of export that will produce the data required to render this pix with the
736 * pix helper in a mustache tag.
738 * @return array
740 public function export_for_pix() {
741 $title = isset($this->attributes['title']) ? $this->attributes['title'] : '';
742 if (empty($title)) {
743 $title = isset($this->attributes['alt']) ? $this->attributes['alt'] : '';
745 return [
746 'key' => $this->pix,
747 'component' => $this->component,
748 'title' => $title
754 * Data structure representing an activity icon.
756 * The difference is that activity icons will always render with the standard icon system (no font icons).
758 * @copyright 2017 Damyon Wiese
759 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
760 * @package core
762 class image_icon extends pix_icon {
766 * Data structure representing an emoticon image
768 * @copyright 2010 David Mudrak
769 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
770 * @since Moodle 2.0
771 * @package core
772 * @category output
774 class pix_emoticon extends pix_icon implements renderable {
777 * Constructor
778 * @param string $pix short icon name
779 * @param string $alt alternative text
780 * @param string $component emoticon image provider
781 * @param array $attributes explicit HTML attributes
783 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
784 if (empty($attributes['class'])) {
785 $attributes['class'] = 'emoticon';
787 parent::__construct($pix, $alt, $component, $attributes);
792 * Data structure representing a simple form with only one button.
794 * @copyright 2009 Petr Skoda
795 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
796 * @since Moodle 2.0
797 * @package core
798 * @category output
800 class single_button implements renderable {
803 * @var moodle_url Target url
805 public $url;
808 * @var string Button label
810 public $label;
813 * @var string Form submit method post or get
815 public $method = 'post';
818 * @var string Wrapping div class
820 public $class = 'singlebutton';
823 * @var bool True if button is primary button. Used for styling.
825 public $primary = false;
828 * @var bool True if button disabled, false if normal
830 public $disabled = false;
833 * @var string Button tooltip
835 public $tooltip = null;
838 * @var string Form id
840 public $formid;
843 * @var array List of attached actions
845 public $actions = array();
848 * @var array $params URL Params
850 public $params;
853 * @var string Action id
855 public $actionid;
858 * Constructor
859 * @param moodle_url $url
860 * @param string $label button text
861 * @param string $method get or post submit method
863 public function __construct(moodle_url $url, $label, $method='post', $primary=false) {
864 $this->url = clone($url);
865 $this->label = $label;
866 $this->method = $method;
867 $this->primary = $primary;
871 * Shortcut for adding a JS confirm dialog when the button is clicked.
872 * The message must be a yes/no question.
874 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
876 public function add_confirm_action($confirmmessage) {
877 $this->add_action(new confirm_action($confirmmessage));
881 * Add action to the button.
882 * @param component_action $action
884 public function add_action(component_action $action) {
885 $this->actions[] = $action;
889 * Export data.
891 * @param renderer_base $output Renderer.
892 * @return stdClass
894 public function export_for_template(renderer_base $output) {
895 $url = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
897 $data = new stdClass();
898 $data->id = html_writer::random_id('single_button');
899 $data->formid = $this->formid;
900 $data->method = $this->method;
901 $data->url = $url === '' ? '#' : $url;
902 $data->label = $this->label;
903 $data->classes = $this->class;
904 $data->disabled = $this->disabled;
905 $data->tooltip = $this->tooltip;
906 $data->primary = $this->primary;
908 // Form parameters.
909 $params = $this->url->params();
910 if ($this->method === 'post') {
911 $params['sesskey'] = sesskey();
913 $data->params = array_map(function($key) use ($params) {
914 return ['name' => $key, 'value' => $params[$key]];
915 }, array_keys($params));
917 // Button actions.
918 $actions = $this->actions;
919 $data->actions = array_map(function($action) use ($output) {
920 return $action->export_for_template($output);
921 }, $actions);
922 $data->hasactions = !empty($data->actions);
924 return $data;
930 * Simple form with just one select field that gets submitted automatically.
932 * If JS not enabled small go button is printed too.
934 * @copyright 2009 Petr Skoda
935 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
936 * @since Moodle 2.0
937 * @package core
938 * @category output
940 class single_select implements renderable, templatable {
943 * @var moodle_url Target url - includes hidden fields
945 var $url;
948 * @var string Name of the select element.
950 var $name;
953 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
954 * it is also possible to specify optgroup as complex label array ex.:
955 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
956 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
958 var $options;
961 * @var string Selected option
963 var $selected;
966 * @var array Nothing selected
968 var $nothing;
971 * @var array Extra select field attributes
973 var $attributes = array();
976 * @var string Button label
978 var $label = '';
981 * @var array Button label's attributes
983 var $labelattributes = array();
986 * @var string Form submit method post or get
988 var $method = 'get';
991 * @var string Wrapping div class
993 var $class = 'singleselect';
996 * @var bool True if button disabled, false if normal
998 var $disabled = false;
1001 * @var string Button tooltip
1003 var $tooltip = null;
1006 * @var string Form id
1008 var $formid = null;
1011 * @var array List of attached actions
1013 var $helpicon = null;
1016 * Constructor
1017 * @param moodle_url $url form action target, includes hidden fields
1018 * @param string $name name of selection field - the changing parameter in url
1019 * @param array $options list of options
1020 * @param string $selected selected element
1021 * @param array $nothing
1022 * @param string $formid
1024 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1025 $this->url = $url;
1026 $this->name = $name;
1027 $this->options = $options;
1028 $this->selected = $selected;
1029 $this->nothing = $nothing;
1030 $this->formid = $formid;
1034 * Shortcut for adding a JS confirm dialog when the button is clicked.
1035 * The message must be a yes/no question.
1037 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
1039 public function add_confirm_action($confirmmessage) {
1040 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
1044 * Add action to the button.
1046 * @param component_action $action
1048 public function add_action(component_action $action) {
1049 $this->actions[] = $action;
1053 * Adds help icon.
1055 * @deprecated since Moodle 2.0
1057 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1058 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1062 * Adds help icon.
1064 * @param string $identifier The keyword that defines a help page
1065 * @param string $component
1067 public function set_help_icon($identifier, $component = 'moodle') {
1068 $this->helpicon = new help_icon($identifier, $component);
1072 * Sets select's label
1074 * @param string $label
1075 * @param array $attributes (optional)
1077 public function set_label($label, $attributes = array()) {
1078 $this->label = $label;
1079 $this->labelattributes = $attributes;
1084 * Export data.
1086 * @param renderer_base $output Renderer.
1087 * @return stdClass
1089 public function export_for_template(renderer_base $output) {
1090 $attributes = $this->attributes;
1092 $data = new stdClass();
1093 $data->name = $this->name;
1094 $data->method = $this->method;
1095 $data->action = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
1096 $data->classes = $this->class;
1097 $data->label = $this->label;
1098 $data->disabled = $this->disabled;
1099 $data->title = $this->tooltip;
1100 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('single_select_f');
1101 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('single_select');
1102 unset($attributes['id']);
1104 // Form parameters.
1105 $params = $this->url->params();
1106 if ($this->method === 'post') {
1107 $params['sesskey'] = sesskey();
1109 $data->params = array_map(function($key) use ($params) {
1110 return ['name' => $key, 'value' => $params[$key]];
1111 }, array_keys($params));
1113 // Select options.
1114 $hasnothing = false;
1115 if (is_string($this->nothing) && $this->nothing !== '') {
1116 $nothing = ['' => $this->nothing];
1117 $hasnothing = true;
1118 $nothingkey = '';
1119 } else if (is_array($this->nothing)) {
1120 $nothingvalue = reset($this->nothing);
1121 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1122 $nothing = [key($this->nothing) => get_string('choosedots')];
1123 } else {
1124 $nothing = $this->nothing;
1126 $hasnothing = true;
1127 $nothingkey = key($this->nothing);
1129 if ($hasnothing) {
1130 $options = $nothing + $this->options;
1131 } else {
1132 $options = $this->options;
1135 foreach ($options as $value => $name) {
1136 if (is_array($options[$value])) {
1137 foreach ($options[$value] as $optgroupname => $optgroupvalues) {
1138 $sublist = [];
1139 foreach ($optgroupvalues as $optvalue => $optname) {
1140 $option = [
1141 'value' => $optvalue,
1142 'name' => $optname,
1143 'selected' => strval($this->selected) === strval($optvalue),
1146 if ($hasnothing && $nothingkey === $optvalue) {
1147 $option['ignore'] = 'data-ignore';
1150 $sublist[] = $option;
1152 $data->options[] = [
1153 'name' => $optgroupname,
1154 'optgroup' => true,
1155 'options' => $sublist
1158 } else {
1159 $option = [
1160 'value' => $value,
1161 'name' => $options[$value],
1162 'selected' => strval($this->selected) === strval($value),
1163 'optgroup' => false
1166 if ($hasnothing && $nothingkey === $value) {
1167 $option['ignore'] = 'data-ignore';
1170 $data->options[] = $option;
1174 // Label attributes.
1175 $data->labelattributes = [];
1176 foreach ($this->labelattributes as $key => $value) {
1177 $data->labelattributes = ['name' => $key, 'value' => $value];
1180 // Help icon.
1181 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1183 return $data;
1188 * Simple URL selection widget description.
1190 * @copyright 2009 Petr Skoda
1191 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1192 * @since Moodle 2.0
1193 * @package core
1194 * @category output
1196 class url_select implements renderable, templatable {
1198 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
1199 * it is also possible to specify optgroup as complex label array ex.:
1200 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1201 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1203 var $urls;
1206 * @var string Selected option
1208 var $selected;
1211 * @var array Nothing selected
1213 var $nothing;
1216 * @var array Extra select field attributes
1218 var $attributes = array();
1221 * @var string Button label
1223 var $label = '';
1226 * @var array Button label's attributes
1228 var $labelattributes = array();
1231 * @var string Wrapping div class
1233 var $class = 'urlselect';
1236 * @var bool True if button disabled, false if normal
1238 var $disabled = false;
1241 * @var string Button tooltip
1243 var $tooltip = null;
1246 * @var string Form id
1248 var $formid = null;
1251 * @var array List of attached actions
1253 var $helpicon = null;
1256 * @var string If set, makes button visible with given name for button
1258 var $showbutton = null;
1261 * Constructor
1262 * @param array $urls list of options
1263 * @param string $selected selected element
1264 * @param array $nothing
1265 * @param string $formid
1266 * @param string $showbutton Set to text of button if it should be visible
1267 * or null if it should be hidden (hidden version always has text 'go')
1269 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
1270 $this->urls = $urls;
1271 $this->selected = $selected;
1272 $this->nothing = $nothing;
1273 $this->formid = $formid;
1274 $this->showbutton = $showbutton;
1278 * Adds help icon.
1280 * @deprecated since Moodle 2.0
1282 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1283 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1287 * Adds help icon.
1289 * @param string $identifier The keyword that defines a help page
1290 * @param string $component
1292 public function set_help_icon($identifier, $component = 'moodle') {
1293 $this->helpicon = new help_icon($identifier, $component);
1297 * Sets select's label
1299 * @param string $label
1300 * @param array $attributes (optional)
1302 public function set_label($label, $attributes = array()) {
1303 $this->label = $label;
1304 $this->labelattributes = $attributes;
1308 * Clean a URL.
1310 * @param string $value The URL.
1311 * @return The cleaned URL.
1313 protected function clean_url($value) {
1314 global $CFG;
1316 if (empty($value)) {
1317 // Nothing.
1319 } else if (strpos($value, $CFG->wwwroot . '/') === 0) {
1320 $value = str_replace($CFG->wwwroot, '', $value);
1322 } else if (strpos($value, '/') !== 0) {
1323 debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER);
1326 return $value;
1330 * Flatten the options for Mustache.
1332 * This also cleans the URLs.
1334 * @param array $options The options.
1335 * @param array $nothing The nothing option.
1336 * @return array
1338 protected function flatten_options($options, $nothing) {
1339 $flattened = [];
1341 foreach ($options as $value => $option) {
1342 if (is_array($option)) {
1343 foreach ($option as $groupname => $optoptions) {
1344 if (!isset($flattened[$groupname])) {
1345 $flattened[$groupname] = [
1346 'name' => $groupname,
1347 'isgroup' => true,
1348 'options' => []
1351 foreach ($optoptions as $optvalue => $optoption) {
1352 $cleanedvalue = $this->clean_url($optvalue);
1353 $flattened[$groupname]['options'][$cleanedvalue] = [
1354 'name' => $optoption,
1355 'value' => $cleanedvalue,
1356 'selected' => $this->selected == $optvalue,
1361 } else {
1362 $cleanedvalue = $this->clean_url($value);
1363 $flattened[$cleanedvalue] = [
1364 'name' => $option,
1365 'value' => $cleanedvalue,
1366 'selected' => $this->selected == $value,
1371 if (!empty($nothing)) {
1372 $value = key($nothing);
1373 $name = reset($nothing);
1374 $flattened = [
1375 $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value]
1376 ] + $flattened;
1379 // Make non-associative array.
1380 foreach ($flattened as $key => $value) {
1381 if (!empty($value['options'])) {
1382 $flattened[$key]['options'] = array_values($value['options']);
1385 $flattened = array_values($flattened);
1387 return $flattened;
1391 * Export for template.
1393 * @param renderer_base $output Renderer.
1394 * @return stdClass
1396 public function export_for_template(renderer_base $output) {
1397 $attributes = $this->attributes;
1399 $data = new stdClass();
1400 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('url_select_f');
1401 $data->classes = $this->class;
1402 $data->label = $this->label;
1403 $data->disabled = $this->disabled;
1404 $data->title = $this->tooltip;
1405 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('url_select');
1406 $data->sesskey = sesskey();
1407 $data->action = (new moodle_url('/course/jumpto.php'))->out(false);
1409 // Remove attributes passed as property directly.
1410 unset($attributes['class']);
1411 unset($attributes['id']);
1412 unset($attributes['name']);
1413 unset($attributes['title']);
1415 $data->showbutton = $this->showbutton;
1417 // Select options.
1418 $nothing = false;
1419 if (is_string($this->nothing) && $this->nothing !== '') {
1420 $nothing = ['' => $this->nothing];
1421 } else if (is_array($this->nothing)) {
1422 $nothingvalue = reset($this->nothing);
1423 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1424 $nothing = [key($this->nothing) => get_string('choosedots')];
1425 } else {
1426 $nothing = $this->nothing;
1429 $data->options = $this->flatten_options($this->urls, $nothing);
1431 // Label attributes.
1432 $data->labelattributes = [];
1433 foreach ($this->labelattributes as $key => $value) {
1434 $data->labelattributes[] = ['name' => $key, 'value' => $value];
1437 // Help icon.
1438 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1440 // Finally all the remaining attributes.
1441 $data->attributes = [];
1442 foreach ($this->attributes as $key => $value) {
1443 $data->attributes = ['name' => $key, 'value' => $value];
1446 return $data;
1451 * Data structure describing html link with special action attached.
1453 * @copyright 2010 Petr Skoda
1454 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1455 * @since Moodle 2.0
1456 * @package core
1457 * @category output
1459 class action_link implements renderable {
1462 * @var moodle_url Href url
1464 public $url;
1467 * @var string Link text HTML fragment
1469 public $text;
1472 * @var array HTML attributes
1474 public $attributes;
1477 * @var array List of actions attached to link
1479 public $actions;
1482 * @var pix_icon Optional pix icon to render with the link
1484 public $icon;
1487 * Constructor
1488 * @param moodle_url $url
1489 * @param string $text HTML fragment
1490 * @param component_action $action
1491 * @param array $attributes associative array of html link attributes + disabled
1492 * @param pix_icon $icon optional pix_icon to render with the link text
1494 public function __construct(moodle_url $url,
1495 $text,
1496 component_action $action=null,
1497 array $attributes=null,
1498 pix_icon $icon=null) {
1499 $this->url = clone($url);
1500 $this->text = $text;
1501 $this->attributes = (array)$attributes;
1502 if ($action) {
1503 $this->add_action($action);
1505 $this->icon = $icon;
1509 * Add action to the link.
1511 * @param component_action $action
1513 public function add_action(component_action $action) {
1514 $this->actions[] = $action;
1518 * Adds a CSS class to this action link object
1519 * @param string $class
1521 public function add_class($class) {
1522 if (empty($this->attributes['class'])) {
1523 $this->attributes['class'] = $class;
1524 } else {
1525 $this->attributes['class'] .= ' ' . $class;
1530 * Returns true if the specified class has been added to this link.
1531 * @param string $class
1532 * @return bool
1534 public function has_class($class) {
1535 return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
1539 * Return the rendered HTML for the icon. Useful for rendering action links in a template.
1540 * @return string
1542 public function get_icon_html() {
1543 global $OUTPUT;
1544 if (!$this->icon) {
1545 return '';
1547 return $OUTPUT->render($this->icon);
1551 * Export for template.
1553 * @param renderer_base $output The renderer.
1554 * @return stdClass
1556 public function export_for_template(renderer_base $output) {
1557 $data = new stdClass();
1558 $attributes = $this->attributes;
1560 if (empty($attributes['id'])) {
1561 $attributes['id'] = html_writer::random_id('action_link');
1563 $data->id = $attributes['id'];
1564 unset($attributes['id']);
1566 $data->disabled = !empty($attributes['disabled']);
1567 unset($attributes['disabled']);
1569 $data->text = $this->text instanceof renderable ? $output->render($this->text) : (string) $this->text;
1570 $data->url = $this->url ? $this->url->out(false) : '';
1571 $data->icon = $this->icon ? $this->icon->export_for_pix() : null;
1572 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
1573 unset($attributes['class']);
1575 $data->attributes = array_map(function($key, $value) {
1576 return [
1577 'name' => $key,
1578 'value' => $value
1580 }, array_keys($attributes), $attributes);
1582 $data->actions = array_map(function($action) use ($output) {
1583 return $action->export_for_template($output);
1584 }, !empty($this->actions) ? $this->actions : []);
1585 $data->hasactions = !empty($this->actions);
1587 return $data;
1592 * Simple html output class
1594 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1595 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1596 * @since Moodle 2.0
1597 * @package core
1598 * @category output
1600 class html_writer {
1603 * Outputs a tag with attributes and contents
1605 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1606 * @param string $contents What goes between the opening and closing tags
1607 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1608 * @return string HTML fragment
1610 public static function tag($tagname, $contents, array $attributes = null) {
1611 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1615 * Outputs an opening tag with attributes
1617 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1618 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1619 * @return string HTML fragment
1621 public static function start_tag($tagname, array $attributes = null) {
1622 return '<' . $tagname . self::attributes($attributes) . '>';
1626 * Outputs a closing tag
1628 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1629 * @return string HTML fragment
1631 public static function end_tag($tagname) {
1632 return '</' . $tagname . '>';
1636 * Outputs an empty tag with attributes
1638 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1639 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1640 * @return string HTML fragment
1642 public static function empty_tag($tagname, array $attributes = null) {
1643 return '<' . $tagname . self::attributes($attributes) . ' />';
1647 * Outputs a tag, but only if the contents are not empty
1649 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1650 * @param string $contents What goes between the opening and closing tags
1651 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1652 * @return string HTML fragment
1654 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1655 if ($contents === '' || is_null($contents)) {
1656 return '';
1658 return self::tag($tagname, $contents, $attributes);
1662 * Outputs a HTML attribute and value
1664 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1665 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1666 * @return string HTML fragment
1668 public static function attribute($name, $value) {
1669 if ($value instanceof moodle_url) {
1670 return ' ' . $name . '="' . $value->out() . '"';
1673 // special case, we do not want these in output
1674 if ($value === null) {
1675 return '';
1678 // no sloppy trimming here!
1679 return ' ' . $name . '="' . s($value) . '"';
1683 * Outputs a list of HTML attributes and values
1685 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1686 * The values will be escaped with {@link s()}
1687 * @return string HTML fragment
1689 public static function attributes(array $attributes = null) {
1690 $attributes = (array)$attributes;
1691 $output = '';
1692 foreach ($attributes as $name => $value) {
1693 $output .= self::attribute($name, $value);
1695 return $output;
1699 * Generates a simple image tag with attributes.
1701 * @param string $src The source of image
1702 * @param string $alt The alternate text for image
1703 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1704 * @return string HTML fragment
1706 public static function img($src, $alt, array $attributes = null) {
1707 $attributes = (array)$attributes;
1708 $attributes['src'] = $src;
1709 $attributes['alt'] = $alt;
1711 return self::empty_tag('img', $attributes);
1715 * Generates random html element id.
1717 * @staticvar int $counter
1718 * @staticvar type $uniq
1719 * @param string $base A string fragment that will be included in the random ID.
1720 * @return string A unique ID
1722 public static function random_id($base='random') {
1723 static $counter = 0;
1724 static $uniq;
1726 if (!isset($uniq)) {
1727 $uniq = uniqid();
1730 $counter++;
1731 return $base.$uniq.$counter;
1735 * Generates a simple html link
1737 * @param string|moodle_url $url The URL
1738 * @param string $text The text
1739 * @param array $attributes HTML attributes
1740 * @return string HTML fragment
1742 public static function link($url, $text, array $attributes = null) {
1743 $attributes = (array)$attributes;
1744 $attributes['href'] = $url;
1745 return self::tag('a', $text, $attributes);
1749 * Generates a simple checkbox with optional label
1751 * @param string $name The name of the checkbox
1752 * @param string $value The value of the checkbox
1753 * @param bool $checked Whether the checkbox is checked
1754 * @param string $label The label for the checkbox
1755 * @param array $attributes Any attributes to apply to the checkbox
1756 * @return string html fragment
1758 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1759 $attributes = (array)$attributes;
1760 $output = '';
1762 if ($label !== '' and !is_null($label)) {
1763 if (empty($attributes['id'])) {
1764 $attributes['id'] = self::random_id('checkbox_');
1767 $attributes['type'] = 'checkbox';
1768 $attributes['value'] = $value;
1769 $attributes['name'] = $name;
1770 $attributes['checked'] = $checked ? 'checked' : null;
1772 $output .= self::empty_tag('input', $attributes);
1774 if ($label !== '' and !is_null($label)) {
1775 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1778 return $output;
1782 * Generates a simple select yes/no form field
1784 * @param string $name name of select element
1785 * @param bool $selected
1786 * @param array $attributes - html select element attributes
1787 * @return string HTML fragment
1789 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1790 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1791 return self::select($options, $name, $selected, null, $attributes);
1795 * Generates a simple select form field
1797 * @param array $options associative array value=>label ex.:
1798 * array(1=>'One, 2=>Two)
1799 * it is also possible to specify optgroup as complex label array ex.:
1800 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1801 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1802 * @param string $name name of select element
1803 * @param string|array $selected value or array of values depending on multiple attribute
1804 * @param array|bool $nothing add nothing selected option, or false of not added
1805 * @param array $attributes html select element attributes
1806 * @return string HTML fragment
1808 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1809 $attributes = (array)$attributes;
1810 if (is_array($nothing)) {
1811 foreach ($nothing as $k=>$v) {
1812 if ($v === 'choose' or $v === 'choosedots') {
1813 $nothing[$k] = get_string('choosedots');
1816 $options = $nothing + $options; // keep keys, do not override
1818 } else if (is_string($nothing) and $nothing !== '') {
1819 // BC
1820 $options = array(''=>$nothing) + $options;
1823 // we may accept more values if multiple attribute specified
1824 $selected = (array)$selected;
1825 foreach ($selected as $k=>$v) {
1826 $selected[$k] = (string)$v;
1829 if (!isset($attributes['id'])) {
1830 $id = 'menu'.$name;
1831 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1832 $id = str_replace('[', '', $id);
1833 $id = str_replace(']', '', $id);
1834 $attributes['id'] = $id;
1837 if (!isset($attributes['class'])) {
1838 $class = 'menu'.$name;
1839 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1840 $class = str_replace('[', '', $class);
1841 $class = str_replace(']', '', $class);
1842 $attributes['class'] = $class;
1844 $attributes['class'] = 'select custom-select ' . $attributes['class']; // Add 'select' selector always.
1846 $attributes['name'] = $name;
1848 if (!empty($attributes['disabled'])) {
1849 $attributes['disabled'] = 'disabled';
1850 } else {
1851 unset($attributes['disabled']);
1854 $output = '';
1855 foreach ($options as $value=>$label) {
1856 if (is_array($label)) {
1857 // ignore key, it just has to be unique
1858 $output .= self::select_optgroup(key($label), current($label), $selected);
1859 } else {
1860 $output .= self::select_option($label, $value, $selected);
1863 return self::tag('select', $output, $attributes);
1867 * Returns HTML to display a select box option.
1869 * @param string $label The label to display as the option.
1870 * @param string|int $value The value the option represents
1871 * @param array $selected An array of selected options
1872 * @return string HTML fragment
1874 private static function select_option($label, $value, array $selected) {
1875 $attributes = array();
1876 $value = (string)$value;
1877 if (in_array($value, $selected, true)) {
1878 $attributes['selected'] = 'selected';
1880 $attributes['value'] = $value;
1881 return self::tag('option', $label, $attributes);
1885 * Returns HTML to display a select box option group.
1887 * @param string $groupname The label to use for the group
1888 * @param array $options The options in the group
1889 * @param array $selected An array of selected values.
1890 * @return string HTML fragment.
1892 private static function select_optgroup($groupname, $options, array $selected) {
1893 if (empty($options)) {
1894 return '';
1896 $attributes = array('label'=>$groupname);
1897 $output = '';
1898 foreach ($options as $value=>$label) {
1899 $output .= self::select_option($label, $value, $selected);
1901 return self::tag('optgroup', $output, $attributes);
1905 * This is a shortcut for making an hour selector menu.
1907 * @param string $type The type of selector (years, months, days, hours, minutes)
1908 * @param string $name fieldname
1909 * @param int $currenttime A default timestamp in GMT
1910 * @param int $step minute spacing
1911 * @param array $attributes - html select element attributes
1912 * @return HTML fragment
1914 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1915 global $OUTPUT;
1917 if (!$currenttime) {
1918 $currenttime = time();
1920 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1921 $currentdate = $calendartype->timestamp_to_date_array($currenttime);
1922 $userdatetype = $type;
1923 $timeunits = array();
1925 switch ($type) {
1926 case 'years':
1927 $timeunits = $calendartype->get_years();
1928 $userdatetype = 'year';
1929 break;
1930 case 'months':
1931 $timeunits = $calendartype->get_months();
1932 $userdatetype = 'month';
1933 $currentdate['month'] = (int)$currentdate['mon'];
1934 break;
1935 case 'days':
1936 $timeunits = $calendartype->get_days();
1937 $userdatetype = 'mday';
1938 break;
1939 case 'hours':
1940 for ($i=0; $i<=23; $i++) {
1941 $timeunits[$i] = sprintf("%02d",$i);
1943 break;
1944 case 'minutes':
1945 if ($step != 1) {
1946 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1949 for ($i=0; $i<=59; $i+=$step) {
1950 $timeunits[$i] = sprintf("%02d",$i);
1952 break;
1953 default:
1954 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1957 $attributes = (array) $attributes;
1958 $data = (object) [
1959 'name' => $name,
1960 'id' => !empty($attributes['id']) ? $attributes['id'] : self::random_id('ts_'),
1961 'label' => get_string(substr($type, 0, -1), 'form'),
1962 'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) {
1963 return [
1964 'name' => $timeunits[$value],
1965 'value' => $value,
1966 'selected' => $currentdate[$userdatetype] == $value
1968 }, array_keys($timeunits)),
1971 unset($attributes['id']);
1972 unset($attributes['name']);
1973 $data->attributes = array_map(function($name) use ($attributes) {
1974 return [
1975 'name' => $name,
1976 'value' => $attributes[$name]
1978 }, array_keys($attributes));
1980 return $OUTPUT->render_from_template('core/select_time', $data);
1984 * Shortcut for quick making of lists
1986 * Note: 'list' is a reserved keyword ;-)
1988 * @param array $items
1989 * @param array $attributes
1990 * @param string $tag ul or ol
1991 * @return string
1993 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1994 $output = html_writer::start_tag($tag, $attributes)."\n";
1995 foreach ($items as $item) {
1996 $output .= html_writer::tag('li', $item)."\n";
1998 $output .= html_writer::end_tag($tag);
1999 return $output;
2003 * Returns hidden input fields created from url parameters.
2005 * @param moodle_url $url
2006 * @param array $exclude list of excluded parameters
2007 * @return string HTML fragment
2009 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
2010 $exclude = (array)$exclude;
2011 $params = $url->params();
2012 foreach ($exclude as $key) {
2013 unset($params[$key]);
2016 $output = '';
2017 foreach ($params as $key => $value) {
2018 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
2019 $output .= self::empty_tag('input', $attributes)."\n";
2021 return $output;
2025 * Generate a script tag containing the the specified code.
2027 * @param string $jscode the JavaScript code
2028 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
2029 * @return string HTML, the code wrapped in <script> tags.
2031 public static function script($jscode, $url=null) {
2032 if ($jscode) {
2033 $attributes = array('type'=>'text/javascript');
2034 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
2036 } else if ($url) {
2037 $attributes = array('type'=>'text/javascript', 'src'=>$url);
2038 return self::tag('script', '', $attributes) . "\n";
2040 } else {
2041 return '';
2046 * Renders HTML table
2048 * This method may modify the passed instance by adding some default properties if they are not set yet.
2049 * If this is not what you want, you should make a full clone of your data before passing them to this
2050 * method. In most cases this is not an issue at all so we do not clone by default for performance
2051 * and memory consumption reasons.
2053 * @param html_table $table data to be rendered
2054 * @return string HTML code
2056 public static function table(html_table $table) {
2057 // prepare table data and populate missing properties with reasonable defaults
2058 if (!empty($table->align)) {
2059 foreach ($table->align as $key => $aa) {
2060 if ($aa) {
2061 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
2062 } else {
2063 $table->align[$key] = null;
2067 if (!empty($table->size)) {
2068 foreach ($table->size as $key => $ss) {
2069 if ($ss) {
2070 $table->size[$key] = 'width:'. $ss .';';
2071 } else {
2072 $table->size[$key] = null;
2076 if (!empty($table->wrap)) {
2077 foreach ($table->wrap as $key => $ww) {
2078 if ($ww) {
2079 $table->wrap[$key] = 'white-space:nowrap;';
2080 } else {
2081 $table->wrap[$key] = '';
2085 if (!empty($table->head)) {
2086 foreach ($table->head as $key => $val) {
2087 if (!isset($table->align[$key])) {
2088 $table->align[$key] = null;
2090 if (!isset($table->size[$key])) {
2091 $table->size[$key] = null;
2093 if (!isset($table->wrap[$key])) {
2094 $table->wrap[$key] = null;
2099 if (empty($table->attributes['class'])) {
2100 $table->attributes['class'] = 'generaltable';
2102 if (!empty($table->tablealign)) {
2103 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
2106 // explicitly assigned properties override those defined via $table->attributes
2107 $table->attributes['class'] = trim($table->attributes['class']);
2108 $attributes = array_merge($table->attributes, array(
2109 'id' => $table->id,
2110 'width' => $table->width,
2111 'summary' => $table->summary,
2112 'cellpadding' => $table->cellpadding,
2113 'cellspacing' => $table->cellspacing,
2115 $output = html_writer::start_tag('table', $attributes) . "\n";
2117 $countcols = 0;
2119 // Output a caption if present.
2120 if (!empty($table->caption)) {
2121 $captionattributes = array();
2122 if ($table->captionhide) {
2123 $captionattributes['class'] = 'accesshide';
2125 $output .= html_writer::tag(
2126 'caption',
2127 $table->caption,
2128 $captionattributes
2132 if (!empty($table->head)) {
2133 $countcols = count($table->head);
2135 $output .= html_writer::start_tag('thead', array()) . "\n";
2136 $output .= html_writer::start_tag('tr', array()) . "\n";
2137 $keys = array_keys($table->head);
2138 $lastkey = end($keys);
2140 foreach ($table->head as $key => $heading) {
2141 // Convert plain string headings into html_table_cell objects
2142 if (!($heading instanceof html_table_cell)) {
2143 $headingtext = $heading;
2144 $heading = new html_table_cell();
2145 $heading->text = $headingtext;
2146 $heading->header = true;
2149 if ($heading->header !== false) {
2150 $heading->header = true;
2153 if ($heading->header && empty($heading->scope)) {
2154 $heading->scope = 'col';
2157 $heading->attributes['class'] .= ' header c' . $key;
2158 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
2159 $heading->colspan = $table->headspan[$key];
2160 $countcols += $table->headspan[$key] - 1;
2163 if ($key == $lastkey) {
2164 $heading->attributes['class'] .= ' lastcol';
2166 if (isset($table->colclasses[$key])) {
2167 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
2169 $heading->attributes['class'] = trim($heading->attributes['class']);
2170 $attributes = array_merge($heading->attributes, array(
2171 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
2172 'scope' => $heading->scope,
2173 'colspan' => $heading->colspan,
2176 $tagtype = 'td';
2177 if ($heading->header === true) {
2178 $tagtype = 'th';
2180 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
2182 $output .= html_writer::end_tag('tr') . "\n";
2183 $output .= html_writer::end_tag('thead') . "\n";
2185 if (empty($table->data)) {
2186 // For valid XHTML strict every table must contain either a valid tr
2187 // or a valid tbody... both of which must contain a valid td
2188 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
2189 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
2190 $output .= html_writer::end_tag('tbody');
2194 if (!empty($table->data)) {
2195 $keys = array_keys($table->data);
2196 $lastrowkey = end($keys);
2197 $output .= html_writer::start_tag('tbody', array());
2199 foreach ($table->data as $key => $row) {
2200 if (($row === 'hr') && ($countcols)) {
2201 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
2202 } else {
2203 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
2204 if (!($row instanceof html_table_row)) {
2205 $newrow = new html_table_row();
2207 foreach ($row as $cell) {
2208 if (!($cell instanceof html_table_cell)) {
2209 $cell = new html_table_cell($cell);
2211 $newrow->cells[] = $cell;
2213 $row = $newrow;
2216 if (isset($table->rowclasses[$key])) {
2217 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
2220 if ($key == $lastrowkey) {
2221 $row->attributes['class'] .= ' lastrow';
2224 // Explicitly assigned properties should override those defined in the attributes.
2225 $row->attributes['class'] = trim($row->attributes['class']);
2226 $trattributes = array_merge($row->attributes, array(
2227 'id' => $row->id,
2228 'style' => $row->style,
2230 $output .= html_writer::start_tag('tr', $trattributes) . "\n";
2231 $keys2 = array_keys($row->cells);
2232 $lastkey = end($keys2);
2234 $gotlastkey = false; //flag for sanity checking
2235 foreach ($row->cells as $key => $cell) {
2236 if ($gotlastkey) {
2237 //This should never happen. Why do we have a cell after the last cell?
2238 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
2241 if (!($cell instanceof html_table_cell)) {
2242 $mycell = new html_table_cell();
2243 $mycell->text = $cell;
2244 $cell = $mycell;
2247 if (($cell->header === true) && empty($cell->scope)) {
2248 $cell->scope = 'row';
2251 if (isset($table->colclasses[$key])) {
2252 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
2255 $cell->attributes['class'] .= ' cell c' . $key;
2256 if ($key == $lastkey) {
2257 $cell->attributes['class'] .= ' lastcol';
2258 $gotlastkey = true;
2260 $tdstyle = '';
2261 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
2262 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
2263 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
2264 $cell->attributes['class'] = trim($cell->attributes['class']);
2265 $tdattributes = array_merge($cell->attributes, array(
2266 'style' => $tdstyle . $cell->style,
2267 'colspan' => $cell->colspan,
2268 'rowspan' => $cell->rowspan,
2269 'id' => $cell->id,
2270 'abbr' => $cell->abbr,
2271 'scope' => $cell->scope,
2273 $tagtype = 'td';
2274 if ($cell->header === true) {
2275 $tagtype = 'th';
2277 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
2280 $output .= html_writer::end_tag('tr') . "\n";
2282 $output .= html_writer::end_tag('tbody') . "\n";
2284 $output .= html_writer::end_tag('table') . "\n";
2286 return $output;
2290 * Renders form element label
2292 * By default, the label is suffixed with a label separator defined in the
2293 * current language pack (colon by default in the English lang pack).
2294 * Adding the colon can be explicitly disabled if needed. Label separators
2295 * are put outside the label tag itself so they are not read by
2296 * screenreaders (accessibility).
2298 * Parameter $for explicitly associates the label with a form control. When
2299 * set, the value of this attribute must be the same as the value of
2300 * the id attribute of the form control in the same document. When null,
2301 * the label being defined is associated with the control inside the label
2302 * element.
2304 * @param string $text content of the label tag
2305 * @param string|null $for id of the element this label is associated with, null for no association
2306 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
2307 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
2308 * @return string HTML of the label element
2310 public static function label($text, $for, $colonize = true, array $attributes=array()) {
2311 if (!is_null($for)) {
2312 $attributes = array_merge($attributes, array('for' => $for));
2314 $text = trim($text);
2315 $label = self::tag('label', $text, $attributes);
2317 // TODO MDL-12192 $colonize disabled for now yet
2318 // if (!empty($text) and $colonize) {
2319 // // the $text may end with the colon already, though it is bad string definition style
2320 // $colon = get_string('labelsep', 'langconfig');
2321 // if (!empty($colon)) {
2322 // $trimmed = trim($colon);
2323 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
2324 // //debugging('The label text should not end with colon or other label separator,
2325 // // please fix the string definition.', DEBUG_DEVELOPER);
2326 // } else {
2327 // $label .= $colon;
2328 // }
2329 // }
2330 // }
2332 return $label;
2336 * Combines a class parameter with other attributes. Aids in code reduction
2337 * because the class parameter is very frequently used.
2339 * If the class attribute is specified both in the attributes and in the
2340 * class parameter, the two values are combined with a space between.
2342 * @param string $class Optional CSS class (or classes as space-separated list)
2343 * @param array $attributes Optional other attributes as array
2344 * @return array Attributes (or null if still none)
2346 private static function add_class($class = '', array $attributes = null) {
2347 if ($class !== '') {
2348 $classattribute = array('class' => $class);
2349 if ($attributes) {
2350 if (array_key_exists('class', $attributes)) {
2351 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
2352 } else {
2353 $attributes = $classattribute + $attributes;
2355 } else {
2356 $attributes = $classattribute;
2359 return $attributes;
2363 * Creates a <div> tag. (Shortcut function.)
2365 * @param string $content HTML content of tag
2366 * @param string $class Optional CSS class (or classes as space-separated list)
2367 * @param array $attributes Optional other attributes as array
2368 * @return string HTML code for div
2370 public static function div($content, $class = '', array $attributes = null) {
2371 return self::tag('div', $content, self::add_class($class, $attributes));
2375 * Starts a <div> tag. (Shortcut function.)
2377 * @param string $class Optional CSS class (or classes as space-separated list)
2378 * @param array $attributes Optional other attributes as array
2379 * @return string HTML code for open div tag
2381 public static function start_div($class = '', array $attributes = null) {
2382 return self::start_tag('div', self::add_class($class, $attributes));
2386 * Ends a <div> tag. (Shortcut function.)
2388 * @return string HTML code for close div tag
2390 public static function end_div() {
2391 return self::end_tag('div');
2395 * Creates a <span> tag. (Shortcut function.)
2397 * @param string $content HTML content of tag
2398 * @param string $class Optional CSS class (or classes as space-separated list)
2399 * @param array $attributes Optional other attributes as array
2400 * @return string HTML code for span
2402 public static function span($content, $class = '', array $attributes = null) {
2403 return self::tag('span', $content, self::add_class($class, $attributes));
2407 * Starts a <span> tag. (Shortcut function.)
2409 * @param string $class Optional CSS class (or classes as space-separated list)
2410 * @param array $attributes Optional other attributes as array
2411 * @return string HTML code for open span tag
2413 public static function start_span($class = '', array $attributes = null) {
2414 return self::start_tag('span', self::add_class($class, $attributes));
2418 * Ends a <span> tag. (Shortcut function.)
2420 * @return string HTML code for close span tag
2422 public static function end_span() {
2423 return self::end_tag('span');
2428 * Simple javascript output class
2430 * @copyright 2010 Petr Skoda
2431 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2432 * @since Moodle 2.0
2433 * @package core
2434 * @category output
2436 class js_writer {
2439 * Returns javascript code calling the function
2441 * @param string $function function name, can be complex like Y.Event.purgeElement
2442 * @param array $arguments parameters
2443 * @param int $delay execution delay in seconds
2444 * @return string JS code fragment
2446 public static function function_call($function, array $arguments = null, $delay=0) {
2447 if ($arguments) {
2448 $arguments = array_map('json_encode', convert_to_array($arguments));
2449 $arguments = implode(', ', $arguments);
2450 } else {
2451 $arguments = '';
2453 $js = "$function($arguments);";
2455 if ($delay) {
2456 $delay = $delay * 1000; // in miliseconds
2457 $js = "setTimeout(function() { $js }, $delay);";
2459 return $js . "\n";
2463 * Special function which adds Y as first argument of function call.
2465 * @param string $function The function to call
2466 * @param array $extraarguments Any arguments to pass to it
2467 * @return string Some JS code
2469 public static function function_call_with_Y($function, array $extraarguments = null) {
2470 if ($extraarguments) {
2471 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
2472 $arguments = 'Y, ' . implode(', ', $extraarguments);
2473 } else {
2474 $arguments = 'Y';
2476 return "$function($arguments);\n";
2480 * Returns JavaScript code to initialise a new object
2482 * @param string $var If it is null then no var is assigned the new object.
2483 * @param string $class The class to initialise an object for.
2484 * @param array $arguments An array of args to pass to the init method.
2485 * @param array $requirements Any modules required for this class.
2486 * @param int $delay The delay before initialisation. 0 = no delay.
2487 * @return string Some JS code
2489 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
2490 if (is_array($arguments)) {
2491 $arguments = array_map('json_encode', convert_to_array($arguments));
2492 $arguments = implode(', ', $arguments);
2495 if ($var === null) {
2496 $js = "new $class(Y, $arguments);";
2497 } else if (strpos($var, '.')!==false) {
2498 $js = "$var = new $class(Y, $arguments);";
2499 } else {
2500 $js = "var $var = new $class(Y, $arguments);";
2503 if ($delay) {
2504 $delay = $delay * 1000; // in miliseconds
2505 $js = "setTimeout(function() { $js }, $delay);";
2508 if (count($requirements) > 0) {
2509 $requirements = implode("', '", $requirements);
2510 $js = "Y.use('$requirements', function(Y){ $js });";
2512 return $js."\n";
2516 * Returns code setting value to variable
2518 * @param string $name
2519 * @param mixed $value json serialised value
2520 * @param bool $usevar add var definition, ignored for nested properties
2521 * @return string JS code fragment
2523 public static function set_variable($name, $value, $usevar = true) {
2524 $output = '';
2526 if ($usevar) {
2527 if (strpos($name, '.')) {
2528 $output .= '';
2529 } else {
2530 $output .= 'var ';
2534 $output .= "$name = ".json_encode($value).";";
2536 return $output;
2540 * Writes event handler attaching code
2542 * @param array|string $selector standard YUI selector for elements, may be
2543 * array or string, element id is in the form "#idvalue"
2544 * @param string $event A valid DOM event (click, mousedown, change etc.)
2545 * @param string $function The name of the function to call
2546 * @param array $arguments An optional array of argument parameters to pass to the function
2547 * @return string JS code fragment
2549 public static function event_handler($selector, $event, $function, array $arguments = null) {
2550 $selector = json_encode($selector);
2551 $output = "Y.on('$event', $function, $selector, null";
2552 if (!empty($arguments)) {
2553 $output .= ', ' . json_encode($arguments);
2555 return $output . ");\n";
2560 * Holds all the information required to render a <table> by {@link core_renderer::table()}
2562 * Example of usage:
2563 * $t = new html_table();
2564 * ... // set various properties of the object $t as described below
2565 * echo html_writer::table($t);
2567 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
2568 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2569 * @since Moodle 2.0
2570 * @package core
2571 * @category output
2573 class html_table {
2576 * @var string Value to use for the id attribute of the table
2578 public $id = null;
2581 * @var array Attributes of HTML attributes for the <table> element
2583 public $attributes = array();
2586 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
2587 * For more control over the rendering of the headers, an array of html_table_cell objects
2588 * can be passed instead of an array of strings.
2590 * Example of usage:
2591 * $t->head = array('Student', 'Grade');
2593 public $head;
2596 * @var array An array that can be used to make a heading span multiple columns.
2597 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
2598 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
2600 * Example of usage:
2601 * $t->headspan = array(2,1);
2603 public $headspan;
2606 * @var array An array of column alignments.
2607 * The value is used as CSS 'text-align' property. Therefore, possible
2608 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
2609 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
2611 * Examples of usage:
2612 * $t->align = array(null, 'right');
2613 * or
2614 * $t->align[1] = 'right';
2616 public $align;
2619 * @var array The value is used as CSS 'size' property.
2621 * Examples of usage:
2622 * $t->size = array('50%', '50%');
2623 * or
2624 * $t->size[1] = '120px';
2626 public $size;
2629 * @var array An array of wrapping information.
2630 * The only possible value is 'nowrap' that sets the
2631 * CSS property 'white-space' to the value 'nowrap' in the given column.
2633 * Example of usage:
2634 * $t->wrap = array(null, 'nowrap');
2636 public $wrap;
2639 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2640 * $head specified, the string 'hr' (for horizontal ruler) can be used
2641 * instead of an array of cells data resulting in a divider rendered.
2643 * Example of usage with array of arrays:
2644 * $row1 = array('Harry Potter', '76 %');
2645 * $row2 = array('Hermione Granger', '100 %');
2646 * $t->data = array($row1, $row2);
2648 * Example with array of html_table_row objects: (used for more fine-grained control)
2649 * $cell1 = new html_table_cell();
2650 * $cell1->text = 'Harry Potter';
2651 * $cell1->colspan = 2;
2652 * $row1 = new html_table_row();
2653 * $row1->cells[] = $cell1;
2654 * $cell2 = new html_table_cell();
2655 * $cell2->text = 'Hermione Granger';
2656 * $cell3 = new html_table_cell();
2657 * $cell3->text = '100 %';
2658 * $row2 = new html_table_row();
2659 * $row2->cells = array($cell2, $cell3);
2660 * $t->data = array($row1, $row2);
2662 public $data = [];
2665 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2666 * @var string Width of the table, percentage of the page preferred.
2668 public $width = null;
2671 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2672 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2674 public $tablealign = null;
2677 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2678 * @var int Padding on each cell, in pixels
2680 public $cellpadding = null;
2683 * @var int Spacing between cells, in pixels
2684 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2686 public $cellspacing = null;
2689 * @var array Array of classes to add to particular rows, space-separated string.
2690 * Class 'lastrow' is added automatically for the last row in the table.
2692 * Example of usage:
2693 * $t->rowclasses[9] = 'tenth'
2695 public $rowclasses;
2698 * @var array An array of classes to add to every cell in a particular column,
2699 * space-separated string. Class 'cell' is added automatically by the renderer.
2700 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2701 * respectively. Class 'lastcol' is added automatically for all last cells
2702 * in a row.
2704 * Example of usage:
2705 * $t->colclasses = array(null, 'grade');
2707 public $colclasses;
2710 * @var string Description of the contents for screen readers.
2712 public $summary;
2715 * @var string Caption for the table, typically a title.
2717 * Example of usage:
2718 * $t->caption = "TV Guide";
2720 public $caption;
2723 * @var bool Whether to hide the table's caption from sighted users.
2725 * Example of usage:
2726 * $t->caption = "TV Guide";
2727 * $t->captionhide = true;
2729 public $captionhide = false;
2732 * Constructor
2734 public function __construct() {
2735 $this->attributes['class'] = '';
2740 * Component representing a table row.
2742 * @copyright 2009 Nicolas Connault
2743 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2744 * @since Moodle 2.0
2745 * @package core
2746 * @category output
2748 class html_table_row {
2751 * @var string Value to use for the id attribute of the row.
2753 public $id = null;
2756 * @var array Array of html_table_cell objects
2758 public $cells = array();
2761 * @var string Value to use for the style attribute of the table row
2763 public $style = null;
2766 * @var array Attributes of additional HTML attributes for the <tr> element
2768 public $attributes = array();
2771 * Constructor
2772 * @param array $cells
2774 public function __construct(array $cells=null) {
2775 $this->attributes['class'] = '';
2776 $cells = (array)$cells;
2777 foreach ($cells as $cell) {
2778 if ($cell instanceof html_table_cell) {
2779 $this->cells[] = $cell;
2780 } else {
2781 $this->cells[] = new html_table_cell($cell);
2788 * Component representing a table cell.
2790 * @copyright 2009 Nicolas Connault
2791 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2792 * @since Moodle 2.0
2793 * @package core
2794 * @category output
2796 class html_table_cell {
2799 * @var string Value to use for the id attribute of the cell.
2801 public $id = null;
2804 * @var string The contents of the cell.
2806 public $text;
2809 * @var string Abbreviated version of the contents of the cell.
2811 public $abbr = null;
2814 * @var int Number of columns this cell should span.
2816 public $colspan = null;
2819 * @var int Number of rows this cell should span.
2821 public $rowspan = null;
2824 * @var string Defines a way to associate header cells and data cells in a table.
2826 public $scope = null;
2829 * @var bool Whether or not this cell is a header cell.
2831 public $header = null;
2834 * @var string Value to use for the style attribute of the table cell
2836 public $style = null;
2839 * @var array Attributes of additional HTML attributes for the <td> element
2841 public $attributes = array();
2844 * Constructs a table cell
2846 * @param string $text
2848 public function __construct($text = null) {
2849 $this->text = $text;
2850 $this->attributes['class'] = '';
2855 * Component representing a paging bar.
2857 * @copyright 2009 Nicolas Connault
2858 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2859 * @since Moodle 2.0
2860 * @package core
2861 * @category output
2863 class paging_bar implements renderable, templatable {
2866 * @var int The maximum number of pagelinks to display.
2868 public $maxdisplay = 18;
2871 * @var int The total number of entries to be pages through..
2873 public $totalcount;
2876 * @var int The page you are currently viewing.
2878 public $page;
2881 * @var int The number of entries that should be shown per page.
2883 public $perpage;
2886 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2887 * an equals sign and the page number.
2888 * If this is a moodle_url object then the pagevar param will be replaced by
2889 * the page no, for each page.
2891 public $baseurl;
2894 * @var string This is the variable name that you use for the pagenumber in your
2895 * code (ie. 'tablepage', 'blogpage', etc)
2897 public $pagevar;
2900 * @var string A HTML link representing the "previous" page.
2902 public $previouslink = null;
2905 * @var string A HTML link representing the "next" page.
2907 public $nextlink = null;
2910 * @var string A HTML link representing the first page.
2912 public $firstlink = null;
2915 * @var string A HTML link representing the last page.
2917 public $lastlink = null;
2920 * @var array An array of strings. One of them is just a string: the current page
2922 public $pagelinks = array();
2925 * Constructor paging_bar with only the required params.
2927 * @param int $totalcount The total number of entries available to be paged through
2928 * @param int $page The page you are currently viewing
2929 * @param int $perpage The number of entries that should be shown per page
2930 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2931 * @param string $pagevar name of page parameter that holds the page number
2933 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2934 $this->totalcount = $totalcount;
2935 $this->page = $page;
2936 $this->perpage = $perpage;
2937 $this->baseurl = $baseurl;
2938 $this->pagevar = $pagevar;
2942 * Prepares the paging bar for output.
2944 * This method validates the arguments set up for the paging bar and then
2945 * produces fragments of HTML to assist display later on.
2947 * @param renderer_base $output
2948 * @param moodle_page $page
2949 * @param string $target
2950 * @throws coding_exception
2952 public function prepare(renderer_base $output, moodle_page $page, $target) {
2953 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2954 throw new coding_exception('paging_bar requires a totalcount value.');
2956 if (!isset($this->page) || is_null($this->page)) {
2957 throw new coding_exception('paging_bar requires a page value.');
2959 if (empty($this->perpage)) {
2960 throw new coding_exception('paging_bar requires a perpage value.');
2962 if (empty($this->baseurl)) {
2963 throw new coding_exception('paging_bar requires a baseurl value.');
2966 if ($this->totalcount > $this->perpage) {
2967 $pagenum = $this->page - 1;
2969 if ($this->page > 0) {
2970 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2973 if ($this->perpage > 0) {
2974 $lastpage = ceil($this->totalcount / $this->perpage);
2975 } else {
2976 $lastpage = 1;
2979 if ($this->page > round(($this->maxdisplay/3)*2)) {
2980 $currpage = $this->page - round($this->maxdisplay/3);
2982 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2983 } else {
2984 $currpage = 0;
2987 $displaycount = $displaypage = 0;
2989 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2990 $displaypage = $currpage + 1;
2992 if ($this->page == $currpage) {
2993 $this->pagelinks[] = html_writer::span($displaypage, 'current-page');
2994 } else {
2995 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2996 $this->pagelinks[] = $pagelink;
2999 $displaycount++;
3000 $currpage++;
3003 if ($currpage < $lastpage) {
3004 $lastpageactual = $lastpage - 1;
3005 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
3008 $pagenum = $this->page + 1;
3010 if ($pagenum != $lastpage) {
3011 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
3017 * Export for template.
3019 * @param renderer_base $output The renderer.
3020 * @return stdClass
3022 public function export_for_template(renderer_base $output) {
3023 $data = new stdClass();
3024 $data->previous = null;
3025 $data->next = null;
3026 $data->first = null;
3027 $data->last = null;
3028 $data->label = get_string('page');
3029 $data->pages = [];
3030 $data->haspages = $this->totalcount > $this->perpage;
3032 if (!$data->haspages) {
3033 return $data;
3036 if ($this->page > 0) {
3037 $data->previous = [
3038 'page' => $this->page - 1,
3039 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page - 1]))->out(false)
3043 $currpage = 0;
3044 if ($this->page > round(($this->maxdisplay / 3) * 2)) {
3045 $currpage = $this->page - round($this->maxdisplay / 3);
3046 $data->first = [
3047 'page' => 1,
3048 'url' => (new moodle_url($this->baseurl, [$this->pagevar => 0]))->out(false)
3052 $lastpage = 1;
3053 if ($this->perpage > 0) {
3054 $lastpage = ceil($this->totalcount / $this->perpage);
3057 $displaycount = 0;
3058 $displaypage = 0;
3059 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
3060 $displaypage = $currpage + 1;
3062 $iscurrent = $this->page == $currpage;
3063 $link = new moodle_url($this->baseurl, [$this->pagevar => $currpage]);
3065 $data->pages[] = [
3066 'page' => $displaypage,
3067 'active' => $iscurrent,
3068 'url' => $iscurrent ? null : $link->out(false)
3071 $displaycount++;
3072 $currpage++;
3075 if ($currpage < $lastpage) {
3076 $data->last = [
3077 'page' => $lastpage,
3078 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $lastpage - 1]))->out(false)
3082 if ($this->page + 1 != $lastpage) {
3083 $data->next = [
3084 'page' => $this->page + 1,
3085 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page + 1]))->out(false)
3089 return $data;
3094 * Component representing initials bar.
3096 * @copyright 2017 Ilya Tregubov
3097 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3098 * @since Moodle 3.3
3099 * @package core
3100 * @category output
3102 class initials_bar implements renderable, templatable {
3105 * @var string Currently selected letter.
3107 public $current;
3110 * @var string Class name to add to this initial bar.
3112 public $class;
3115 * @var string The name to put in front of this initial bar.
3117 public $title;
3120 * @var string URL parameter name for this initial.
3122 public $urlvar;
3125 * @var string URL object.
3127 public $url;
3130 * @var array An array of letters in the alphabet.
3132 public $alpha;
3135 * Constructor initials_bar with only the required params.
3137 * @param string $current the currently selected letter.
3138 * @param string $class class name to add to this initial bar.
3139 * @param string $title the name to put in front of this initial bar.
3140 * @param string $urlvar URL parameter name for this initial.
3141 * @param string $url URL object.
3142 * @param array $alpha of letters in the alphabet.
3144 public function __construct($current, $class, $title, $urlvar, $url, $alpha = null) {
3145 $this->current = $current;
3146 $this->class = $class;
3147 $this->title = $title;
3148 $this->urlvar = $urlvar;
3149 $this->url = $url;
3150 $this->alpha = $alpha;
3154 * Export for template.
3156 * @param renderer_base $output The renderer.
3157 * @return stdClass
3159 public function export_for_template(renderer_base $output) {
3160 $data = new stdClass();
3162 if ($this->alpha == null) {
3163 $this->alpha = explode(',', get_string('alphabet', 'langconfig'));
3166 if ($this->current == 'all') {
3167 $this->current = '';
3170 // We want to find a letter grouping size which suits the language so
3171 // find the largest group size which is less than 15 chars.
3172 // The choice of 15 chars is the largest number of chars that reasonably
3173 // fits on the smallest supported screen size. By always using a max number
3174 // of groups which is a factor of 2, we always get nice wrapping, and the
3175 // last row is always the shortest.
3176 $groupsize = count($this->alpha);
3177 $groups = 1;
3178 while ($groupsize > 15) {
3179 $groups *= 2;
3180 $groupsize = ceil(count($this->alpha) / $groups);
3183 $groupsizelimit = 0;
3184 $groupnumber = 0;
3185 foreach ($this->alpha as $letter) {
3186 if ($groupsizelimit++ > 0 && $groupsizelimit % $groupsize == 1) {
3187 $groupnumber++;
3189 $groupletter = new stdClass();
3190 $groupletter->name = $letter;
3191 $groupletter->url = $this->url->out(false, array($this->urlvar => $letter));
3192 if ($letter == $this->current) {
3193 $groupletter->selected = $this->current;
3195 $data->group[$groupnumber]->letter[] = $groupletter;
3198 $data->class = $this->class;
3199 $data->title = $this->title;
3200 $data->url = $this->url->out(false, array($this->urlvar => ''));
3201 $data->current = $this->current;
3202 $data->all = get_string('all');
3204 return $data;
3209 * This class represents how a block appears on a page.
3211 * During output, each block instance is asked to return a block_contents object,
3212 * those are then passed to the $OUTPUT->block function for display.
3214 * contents should probably be generated using a moodle_block_..._renderer.
3216 * Other block-like things that need to appear on the page, for example the
3217 * add new block UI, are also represented as block_contents objects.
3219 * @copyright 2009 Tim Hunt
3220 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3221 * @since Moodle 2.0
3222 * @package core
3223 * @category output
3225 class block_contents {
3227 /** Used when the block cannot be collapsed **/
3228 const NOT_HIDEABLE = 0;
3230 /** Used when the block can be collapsed but currently is not **/
3231 const VISIBLE = 1;
3233 /** Used when the block has been collapsed **/
3234 const HIDDEN = 2;
3237 * @var int Used to set $skipid.
3239 protected static $idcounter = 1;
3242 * @var int All the blocks (or things that look like blocks) printed on
3243 * a page are given a unique number that can be used to construct id="" attributes.
3244 * This is set automatically be the {@link prepare()} method.
3245 * Do not try to set it manually.
3247 public $skipid;
3250 * @var int If this is the contents of a real block, this should be set
3251 * to the block_instance.id. Otherwise this should be set to 0.
3253 public $blockinstanceid = 0;
3256 * @var int If this is a real block instance, and there is a corresponding
3257 * block_position.id for the block on this page, this should be set to that id.
3258 * Otherwise it should be 0.
3260 public $blockpositionid = 0;
3263 * @var array An array of attribute => value pairs that are put on the outer div of this
3264 * block. {@link $id} and {@link $classes} attributes should be set separately.
3266 public $attributes;
3269 * @var string The title of this block. If this came from user input, it should already
3270 * have had format_string() processing done on it. This will be output inside
3271 * <h2> tags. Please do not cause invalid XHTML.
3273 public $title = '';
3276 * @var string The label to use when the block does not, or will not have a visible title.
3277 * You should never set this as well as title... it will just be ignored.
3279 public $arialabel = '';
3282 * @var string HTML for the content
3284 public $content = '';
3287 * @var array An alternative to $content, it you want a list of things with optional icons.
3289 public $footer = '';
3292 * @var string Any small print that should appear under the block to explain
3293 * to the teacher about the block, for example 'This is a sticky block that was
3294 * added in the system context.'
3296 public $annotation = '';
3299 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
3300 * the user can toggle whether this block is visible.
3302 public $collapsible = self::NOT_HIDEABLE;
3305 * Set this to true if the block is dockable.
3306 * @var bool
3308 public $dockable = false;
3311 * @var array A (possibly empty) array of editing controls. Each element of
3312 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
3313 * $icon is the icon name. Fed to $OUTPUT->image_url.
3315 public $controls = array();
3319 * Create new instance of block content
3320 * @param array $attributes
3322 public function __construct(array $attributes = null) {
3323 $this->skipid = self::$idcounter;
3324 self::$idcounter += 1;
3326 if ($attributes) {
3327 // standard block
3328 $this->attributes = $attributes;
3329 } else {
3330 // simple "fake" blocks used in some modules and "Add new block" block
3331 $this->attributes = array('class'=>'block');
3336 * Add html class to block
3338 * @param string $class
3340 public function add_class($class) {
3341 $this->attributes['class'] .= ' '.$class;
3347 * This class represents a target for where a block can go when it is being moved.
3349 * This needs to be rendered as a form with the given hidden from fields, and
3350 * clicking anywhere in the form should submit it. The form action should be
3351 * $PAGE->url.
3353 * @copyright 2009 Tim Hunt
3354 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3355 * @since Moodle 2.0
3356 * @package core
3357 * @category output
3359 class block_move_target {
3362 * @var moodle_url Move url
3364 public $url;
3367 * Constructor
3368 * @param moodle_url $url
3370 public function __construct(moodle_url $url) {
3371 $this->url = $url;
3376 * Custom menu item
3378 * This class is used to represent one item within a custom menu that may or may
3379 * not have children.
3381 * @copyright 2010 Sam Hemelryk
3382 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3383 * @since Moodle 2.0
3384 * @package core
3385 * @category output
3387 class custom_menu_item implements renderable, templatable {
3390 * @var string The text to show for the item
3392 protected $text;
3395 * @var moodle_url The link to give the icon if it has no children
3397 protected $url;
3400 * @var string A title to apply to the item. By default the text
3402 protected $title;
3405 * @var int A sort order for the item, not necessary if you order things in
3406 * the CFG var.
3408 protected $sort;
3411 * @var custom_menu_item A reference to the parent for this item or NULL if
3412 * it is a top level item
3414 protected $parent;
3417 * @var array A array in which to store children this item has.
3419 protected $children = array();
3422 * @var int A reference to the sort var of the last child that was added
3424 protected $lastsort = 0;
3427 * Constructs the new custom menu item
3429 * @param string $text
3430 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
3431 * @param string $title A title to apply to this item [Optional]
3432 * @param int $sort A sort or to use if we need to sort differently [Optional]
3433 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
3434 * belongs to, only if the child has a parent. [Optional]
3436 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
3437 $this->text = $text;
3438 $this->url = $url;
3439 $this->title = $title;
3440 $this->sort = (int)$sort;
3441 $this->parent = $parent;
3445 * Adds a custom menu item as a child of this node given its properties.
3447 * @param string $text
3448 * @param moodle_url $url
3449 * @param string $title
3450 * @param int $sort
3451 * @return custom_menu_item
3453 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
3454 $key = count($this->children);
3455 if (empty($sort)) {
3456 $sort = $this->lastsort + 1;
3458 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
3459 $this->lastsort = (int)$sort;
3460 return $this->children[$key];
3464 * Removes a custom menu item that is a child or descendant to the current menu.
3466 * Returns true if child was found and removed.
3468 * @param custom_menu_item $menuitem
3469 * @return bool
3471 public function remove_child(custom_menu_item $menuitem) {
3472 $removed = false;
3473 if (($key = array_search($menuitem, $this->children)) !== false) {
3474 unset($this->children[$key]);
3475 $this->children = array_values($this->children);
3476 $removed = true;
3477 } else {
3478 foreach ($this->children as $child) {
3479 if ($removed = $child->remove_child($menuitem)) {
3480 break;
3484 return $removed;
3488 * Returns the text for this item
3489 * @return string
3491 public function get_text() {
3492 return $this->text;
3496 * Returns the url for this item
3497 * @return moodle_url
3499 public function get_url() {
3500 return $this->url;
3504 * Returns the title for this item
3505 * @return string
3507 public function get_title() {
3508 return $this->title;
3512 * Sorts and returns the children for this item
3513 * @return array
3515 public function get_children() {
3516 $this->sort();
3517 return $this->children;
3521 * Gets the sort order for this child
3522 * @return int
3524 public function get_sort_order() {
3525 return $this->sort;
3529 * Gets the parent this child belong to
3530 * @return custom_menu_item
3532 public function get_parent() {
3533 return $this->parent;
3537 * Sorts the children this item has
3539 public function sort() {
3540 usort($this->children, array('custom_menu','sort_custom_menu_items'));
3544 * Returns true if this item has any children
3545 * @return bool
3547 public function has_children() {
3548 return (count($this->children) > 0);
3552 * Sets the text for the node
3553 * @param string $text
3555 public function set_text($text) {
3556 $this->text = (string)$text;
3560 * Sets the title for the node
3561 * @param string $title
3563 public function set_title($title) {
3564 $this->title = (string)$title;
3568 * Sets the url for the node
3569 * @param moodle_url $url
3571 public function set_url(moodle_url $url) {
3572 $this->url = $url;
3576 * Export this data so it can be used as the context for a mustache template.
3578 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
3579 * @return array
3581 public function export_for_template(renderer_base $output) {
3582 global $CFG;
3584 require_once($CFG->libdir . '/externallib.php');
3586 $syscontext = context_system::instance();
3588 $context = new stdClass();
3589 $context->text = external_format_string($this->text, $syscontext->id);
3590 $context->url = $this->url ? $this->url->out() : null;
3591 $context->title = external_format_string($this->title, $syscontext->id);
3592 $context->sort = $this->sort;
3593 $context->children = array();
3594 if (preg_match("/^#+$/", $this->text)) {
3595 $context->divider = true;
3597 $context->haschildren = !empty($this->children) && (count($this->children) > 0);
3598 foreach ($this->children as $child) {
3599 $child = $child->export_for_template($output);
3600 array_push($context->children, $child);
3603 return $context;
3608 * Custom menu class
3610 * This class is used to operate a custom menu that can be rendered for the page.
3611 * The custom menu is built using $CFG->custommenuitems and is a structured collection
3612 * of custom_menu_item nodes that can be rendered by the core renderer.
3614 * To configure the custom menu:
3615 * Settings: Administration > Appearance > Themes > Theme settings
3617 * @copyright 2010 Sam Hemelryk
3618 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3619 * @since Moodle 2.0
3620 * @package core
3621 * @category output
3623 class custom_menu extends custom_menu_item {
3626 * @var string The language we should render for, null disables multilang support.
3628 protected $currentlanguage = null;
3631 * Creates the custom menu
3633 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
3634 * @param string $currentlanguage the current language code, null disables multilang support
3636 public function __construct($definition = '', $currentlanguage = null) {
3637 $this->currentlanguage = $currentlanguage;
3638 parent::__construct('root'); // create virtual root element of the menu
3639 if (!empty($definition)) {
3640 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
3645 * Overrides the children of this custom menu. Useful when getting children
3646 * from $CFG->custommenuitems
3648 * @param array $children
3650 public function override_children(array $children) {
3651 $this->children = array();
3652 foreach ($children as $child) {
3653 if ($child instanceof custom_menu_item) {
3654 $this->children[] = $child;
3660 * Converts a string into a structured array of custom_menu_items which can
3661 * then be added to a custom menu.
3663 * Structure:
3664 * text|url|title|langs
3665 * The number of hyphens at the start determines the depth of the item. The
3666 * languages are optional, comma separated list of languages the line is for.
3668 * Example structure:
3669 * First level first item|http://www.moodle.com/
3670 * -Second level first item|http://www.moodle.com/partners/
3671 * -Second level second item|http://www.moodle.com/hq/
3672 * --Third level first item|http://www.moodle.com/jobs/
3673 * -Second level third item|http://www.moodle.com/development/
3674 * First level second item|http://www.moodle.com/feedback/
3675 * First level third item
3676 * English only|http://moodle.com|English only item|en
3677 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
3680 * @static
3681 * @param string $text the menu items definition
3682 * @param string $language the language code, null disables multilang support
3683 * @return array
3685 public static function convert_text_to_menu_nodes($text, $language = null) {
3686 $root = new custom_menu();
3687 $lastitem = $root;
3688 $lastdepth = 0;
3689 $hiddenitems = array();
3690 $lines = explode("\n", $text);
3691 foreach ($lines as $linenumber => $line) {
3692 $line = trim($line);
3693 if (strlen($line) == 0) {
3694 continue;
3696 // Parse item settings.
3697 $itemtext = null;
3698 $itemurl = null;
3699 $itemtitle = null;
3700 $itemvisible = true;
3701 $settings = explode('|', $line);
3702 foreach ($settings as $i => $setting) {
3703 $setting = trim($setting);
3704 if (!empty($setting)) {
3705 switch ($i) {
3706 case 0:
3707 $itemtext = ltrim($setting, '-');
3708 $itemtitle = $itemtext;
3709 break;
3710 case 1:
3711 try {
3712 $itemurl = new moodle_url($setting);
3713 } catch (moodle_exception $exception) {
3714 // We're not actually worried about this, we don't want to mess up the display
3715 // just for a wrongly entered URL.
3716 $itemurl = null;
3718 break;
3719 case 2:
3720 $itemtitle = $setting;
3721 break;
3722 case 3:
3723 if (!empty($language)) {
3724 $itemlanguages = array_map('trim', explode(',', $setting));
3725 $itemvisible &= in_array($language, $itemlanguages);
3727 break;
3731 // Get depth of new item.
3732 preg_match('/^(\-*)/', $line, $match);
3733 $itemdepth = strlen($match[1]) + 1;
3734 // Find parent item for new item.
3735 while (($lastdepth - $itemdepth) >= 0) {
3736 $lastitem = $lastitem->get_parent();
3737 $lastdepth--;
3739 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1);
3740 $lastdepth++;
3741 if (!$itemvisible) {
3742 $hiddenitems[] = $lastitem;
3745 foreach ($hiddenitems as $item) {
3746 $item->parent->remove_child($item);
3748 return $root->get_children();
3752 * Sorts two custom menu items
3754 * This function is designed to be used with the usort method
3755 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
3757 * @static
3758 * @param custom_menu_item $itema
3759 * @param custom_menu_item $itemb
3760 * @return int
3762 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
3763 $itema = $itema->get_sort_order();
3764 $itemb = $itemb->get_sort_order();
3765 if ($itema == $itemb) {
3766 return 0;
3768 return ($itema > $itemb) ? +1 : -1;
3773 * Stores one tab
3775 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3776 * @package core
3778 class tabobject implements renderable, templatable {
3779 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
3780 var $id;
3781 /** @var moodle_url|string link */
3782 var $link;
3783 /** @var string text on the tab */
3784 var $text;
3785 /** @var string title under the link, by defaul equals to text */
3786 var $title;
3787 /** @var bool whether to display a link under the tab name when it's selected */
3788 var $linkedwhenselected = false;
3789 /** @var bool whether the tab is inactive */
3790 var $inactive = false;
3791 /** @var bool indicates that this tab's child is selected */
3792 var $activated = false;
3793 /** @var bool indicates that this tab is selected */
3794 var $selected = false;
3795 /** @var array stores children tabobjects */
3796 var $subtree = array();
3797 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
3798 var $level = 1;
3801 * Constructor
3803 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
3804 * @param string|moodle_url $link
3805 * @param string $text text on the tab
3806 * @param string $title title under the link, by defaul equals to text
3807 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
3809 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
3810 $this->id = $id;
3811 $this->link = $link;
3812 $this->text = $text;
3813 $this->title = $title ? $title : $text;
3814 $this->linkedwhenselected = $linkedwhenselected;
3818 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
3820 * @param string $selected the id of the selected tab (whatever row it's on),
3821 * if null marks all tabs as unselected
3822 * @return bool whether this tab is selected or contains selected tab in its subtree
3824 protected function set_selected($selected) {
3825 if ((string)$selected === (string)$this->id) {
3826 $this->selected = true;
3827 // This tab is selected. No need to travel through subtree.
3828 return true;
3830 foreach ($this->subtree as $subitem) {
3831 if ($subitem->set_selected($selected)) {
3832 // This tab has child that is selected. Mark it as activated. No need to check other children.
3833 $this->activated = true;
3834 return true;
3837 return false;
3841 * Travels through tree and finds a tab with specified id
3843 * @param string $id
3844 * @return tabtree|null
3846 public function find($id) {
3847 if ((string)$this->id === (string)$id) {
3848 return $this;
3850 foreach ($this->subtree as $tab) {
3851 if ($obj = $tab->find($id)) {
3852 return $obj;
3855 return null;
3859 * Allows to mark each tab's level in the tree before rendering.
3861 * @param int $level
3863 protected function set_level($level) {
3864 $this->level = $level;
3865 foreach ($this->subtree as $tab) {
3866 $tab->set_level($level + 1);
3871 * Export for template.
3873 * @param renderer_base $output Renderer.
3874 * @return object
3876 public function export_for_template(renderer_base $output) {
3877 if ($this->inactive || ($this->selected && !$this->linkedwhenselected) || $this->activated) {
3878 $link = null;
3879 } else {
3880 $link = $this->link;
3882 $active = $this->activated || $this->selected;
3884 return (object) [
3885 'id' => $this->id,
3886 'link' => is_object($link) ? $link->out(false) : $link,
3887 'text' => $this->text,
3888 'title' => $this->title,
3889 'inactive' => !$active && $this->inactive,
3890 'active' => $active,
3891 'level' => $this->level,
3898 * Renderable for the main page header.
3900 * @package core
3901 * @category output
3902 * @since 2.9
3903 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
3904 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3906 class context_header implements renderable {
3909 * @var string $heading Main heading.
3911 public $heading;
3913 * @var int $headinglevel Main heading 'h' tag level.
3915 public $headinglevel;
3917 * @var string|null $imagedata HTML code for the picture in the page header.
3919 public $imagedata;
3921 * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
3922 * array elements - title => alternate text for the image, or if no image is available the button text.
3923 * url => Link for the button to head to. Should be a moodle_url.
3924 * image => location to the image, or name of the image in /pix/t/{image name}.
3925 * linkattributes => additional attributes for the <a href> element.
3926 * page => page object. Don't include if the image is an external image.
3928 public $additionalbuttons;
3931 * Constructor.
3933 * @param string $heading Main heading data.
3934 * @param int $headinglevel Main heading 'h' tag level.
3935 * @param string|null $imagedata HTML code for the picture in the page header.
3936 * @param string $additionalbuttons Buttons for the header e.g. Messaging button for the user header.
3938 public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null) {
3940 $this->heading = $heading;
3941 $this->headinglevel = $headinglevel;
3942 $this->imagedata = $imagedata;
3943 $this->additionalbuttons = $additionalbuttons;
3944 // If we have buttons then format them.
3945 if (isset($this->additionalbuttons)) {
3946 $this->format_button_images();
3951 * Adds an array element for a formatted image.
3953 protected function format_button_images() {
3955 foreach ($this->additionalbuttons as $buttontype => $button) {
3956 $page = $button['page'];
3957 // If no image is provided then just use the title.
3958 if (!isset($button['image'])) {
3959 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['title'];
3960 } else {
3961 // Check to see if this is an internal Moodle icon.
3962 $internalimage = $page->theme->resolve_image_location('t/' . $button['image'], 'moodle');
3963 if ($internalimage) {
3964 $this->additionalbuttons[$buttontype]['formattedimage'] = 't/' . $button['image'];
3965 } else {
3966 // Treat as an external image.
3967 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['image'];
3971 if (isset($button['linkattributes']['class'])) {
3972 $class = $button['linkattributes']['class'] . ' btn';
3973 } else {
3974 $class = 'btn';
3976 // Add the bootstrap 'btn' class for formatting.
3977 $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
3978 array('class' => $class));
3984 * Stores tabs list
3986 * Example how to print a single line tabs:
3987 * $rows = array(
3988 * new tabobject(...),
3989 * new tabobject(...)
3990 * );
3991 * echo $OUTPUT->tabtree($rows, $selectedid);
3993 * Multiple row tabs may not look good on some devices but if you want to use them
3994 * you can specify ->subtree for the active tabobject.
3996 * @copyright 2013 Marina Glancy
3997 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3998 * @since Moodle 2.5
3999 * @package core
4000 * @category output
4002 class tabtree extends tabobject {
4004 * Constuctor
4006 * It is highly recommended to call constructor when list of tabs is already
4007 * populated, this way you ensure that selected and inactive tabs are located
4008 * and attribute level is set correctly.
4010 * @param array $tabs array of tabs, each of them may have it's own ->subtree
4011 * @param string|null $selected which tab to mark as selected, all parent tabs will
4012 * automatically be marked as activated
4013 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4014 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
4016 public function __construct($tabs, $selected = null, $inactive = null) {
4017 $this->subtree = $tabs;
4018 if ($selected !== null) {
4019 $this->set_selected($selected);
4021 if ($inactive !== null) {
4022 if (is_array($inactive)) {
4023 foreach ($inactive as $id) {
4024 if ($tab = $this->find($id)) {
4025 $tab->inactive = true;
4028 } else if ($tab = $this->find($inactive)) {
4029 $tab->inactive = true;
4032 $this->set_level(0);
4036 * Export for template.
4038 * @param renderer_base $output Renderer.
4039 * @return object
4041 public function export_for_template(renderer_base $output) {
4042 $tabs = [];
4043 $secondrow = false;
4045 foreach ($this->subtree as $tab) {
4046 $tabs[] = $tab->export_for_template($output);
4047 if (!empty($tab->subtree) && ($tab->level == 0 || $tab->selected || $tab->activated)) {
4048 $secondrow = new tabtree($tab->subtree);
4052 return (object) [
4053 'tabs' => $tabs,
4054 'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false
4060 * An action menu.
4062 * This action menu component takes a series of primary and secondary actions.
4063 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
4064 * down menu.
4066 * @package core
4067 * @category output
4068 * @copyright 2013 Sam Hemelryk
4069 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4071 class action_menu implements renderable, templatable {
4074 * Top right alignment.
4076 const TL = 1;
4079 * Top right alignment.
4081 const TR = 2;
4084 * Top right alignment.
4086 const BL = 3;
4089 * Top right alignment.
4091 const BR = 4;
4094 * The instance number. This is unique to this instance of the action menu.
4095 * @var int
4097 protected $instance = 0;
4100 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
4101 * @var array
4103 protected $primaryactions = array();
4106 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
4107 * @var array
4109 protected $secondaryactions = array();
4112 * An array of attributes added to the container of the action menu.
4113 * Initialised with defaults during construction.
4114 * @var array
4116 public $attributes = array();
4118 * An array of attributes added to the container of the primary actions.
4119 * Initialised with defaults during construction.
4120 * @var array
4122 public $attributesprimary = array();
4124 * An array of attributes added to the container of the secondary actions.
4125 * Initialised with defaults during construction.
4126 * @var array
4128 public $attributessecondary = array();
4131 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
4132 * @var array
4134 public $actiontext = null;
4137 * An icon to use for the toggling the secondary menu (dropdown).
4138 * @var actionicon
4140 public $actionicon;
4143 * Any text to use for the toggling the secondary menu (dropdown).
4144 * @var menutrigger
4146 public $menutrigger = '';
4149 * Any extra classes for toggling to the secondary menu.
4150 * @var triggerextraclasses
4152 public $triggerextraclasses = '';
4155 * Place the action menu before all other actions.
4156 * @var prioritise
4158 public $prioritise = false;
4161 * Constructs the action menu with the given items.
4163 * @param array $actions An array of actions.
4165 public function __construct(array $actions = array()) {
4166 static $initialised = 0;
4167 $this->instance = $initialised;
4168 $initialised++;
4170 $this->attributes = array(
4171 'id' => 'action-menu-'.$this->instance,
4172 'class' => 'moodle-actionmenu',
4173 'data-enhance' => 'moodle-core-actionmenu'
4175 $this->attributesprimary = array(
4176 'id' => 'action-menu-'.$this->instance.'-menubar',
4177 'class' => 'menubar',
4178 'role' => 'menubar'
4180 $this->attributessecondary = array(
4181 'id' => 'action-menu-'.$this->instance.'-menu',
4182 'class' => 'menu',
4183 'data-rel' => 'menu-content',
4184 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
4185 'role' => 'menu'
4187 $this->set_alignment(self::TR, self::BR);
4188 foreach ($actions as $action) {
4189 $this->add($action);
4194 * Sets the menu trigger text.
4196 * @param string $trigger The text
4197 * @param string $extraclasses Extra classes to style the secondary menu toggle.
4198 * @return null
4200 public function set_menu_trigger($trigger, $extraclasses = '') {
4201 $this->menutrigger = $trigger;
4202 $this->triggerextraclasses = $extraclasses;
4206 * Return true if there is at least one visible link in the menu.
4208 * @return bool
4210 public function is_empty() {
4211 return !count($this->primaryactions) && !count($this->secondaryactions);
4215 * Initialises JS required fore the action menu.
4216 * The JS is only required once as it manages all action menu's on the page.
4218 * @param moodle_page $page
4220 public function initialise_js(moodle_page $page) {
4221 static $initialised = false;
4222 if (!$initialised) {
4223 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
4224 $initialised = true;
4229 * Adds an action to this action menu.
4231 * @param action_menu_link|pix_icon|string $action
4233 public function add($action) {
4234 if ($action instanceof action_link) {
4235 if ($action->primary) {
4236 $this->add_primary_action($action);
4237 } else {
4238 $this->add_secondary_action($action);
4240 } else if ($action instanceof pix_icon) {
4241 $this->add_primary_action($action);
4242 } else {
4243 $this->add_secondary_action($action);
4248 * Adds a primary action to the action menu.
4250 * @param action_menu_link|action_link|pix_icon|string $action
4252 public function add_primary_action($action) {
4253 if ($action instanceof action_link || $action instanceof pix_icon) {
4254 $action->attributes['role'] = 'menuitem';
4255 if ($action instanceof action_menu_link) {
4256 $action->actionmenu = $this;
4259 $this->primaryactions[] = $action;
4263 * Adds a secondary action to the action menu.
4265 * @param action_link|pix_icon|string $action
4267 public function add_secondary_action($action) {
4268 if ($action instanceof action_link || $action instanceof pix_icon) {
4269 $action->attributes['role'] = 'menuitem';
4270 if ($action instanceof action_menu_link) {
4271 $action->actionmenu = $this;
4274 $this->secondaryactions[] = $action;
4278 * Returns the primary actions ready to be rendered.
4280 * @param core_renderer $output The renderer to use for getting icons.
4281 * @return array
4283 public function get_primary_actions(core_renderer $output = null) {
4284 global $OUTPUT;
4285 if ($output === null) {
4286 $output = $OUTPUT;
4288 $pixicon = $this->actionicon;
4289 $linkclasses = array('toggle-display');
4291 $title = '';
4292 if (!empty($this->menutrigger)) {
4293 $pixicon = '<b class="caret"></b>';
4294 $linkclasses[] = 'textmenu';
4295 } else {
4296 $title = new lang_string('actions', 'moodle');
4297 $this->actionicon = new pix_icon(
4298 't/edit_menu',
4300 'moodle',
4301 array('class' => 'iconsmall actionmenu', 'title' => '')
4303 $pixicon = $this->actionicon;
4305 if ($pixicon instanceof renderable) {
4306 $pixicon = $output->render($pixicon);
4307 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
4308 $title = $pixicon->attributes['alt'];
4311 $string = '';
4312 if ($this->actiontext) {
4313 $string = $this->actiontext;
4315 $actions = $this->primaryactions;
4316 $attributes = array(
4317 'class' => implode(' ', $linkclasses),
4318 'title' => $title,
4319 'id' => 'action-menu-toggle-'.$this->instance,
4320 'role' => 'menuitem'
4322 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
4323 if ($this->prioritise) {
4324 array_unshift($actions, $link);
4325 } else {
4326 $actions[] = $link;
4328 return $actions;
4332 * Returns the secondary actions ready to be rendered.
4333 * @return array
4335 public function get_secondary_actions() {
4336 return $this->secondaryactions;
4340 * Sets the selector that should be used to find the owning node of this menu.
4341 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
4343 public function set_owner_selector($selector) {
4344 $this->attributes['data-owner'] = $selector;
4348 * Sets the alignment of the dialogue in relation to button used to toggle it.
4350 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4351 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4353 public function set_alignment($dialogue, $button) {
4354 if (isset($this->attributessecondary['data-align'])) {
4355 // We've already got one set, lets remove the old class so as to avoid troubles.
4356 $class = $this->attributessecondary['class'];
4357 $search = 'align-'.$this->attributessecondary['data-align'];
4358 $this->attributessecondary['class'] = str_replace($search, '', $class);
4360 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
4361 $this->attributessecondary['data-align'] = $align;
4362 $this->attributessecondary['class'] .= ' align-'.$align;
4366 * Returns a string to describe the alignment.
4368 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4369 * @return string
4371 protected function get_align_string($align) {
4372 switch ($align) {
4373 case self::TL :
4374 return 'tl';
4375 case self::TR :
4376 return 'tr';
4377 case self::BL :
4378 return 'bl';
4379 case self::BR :
4380 return 'br';
4381 default :
4382 return 'tl';
4387 * Sets a constraint for the dialogue.
4389 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
4390 * element the constraint identifies.
4392 * This is required whenever the action menu is displayed inside any CSS element with the .no-overflow class
4393 * (flexible_table and any of it's child classes are a likely candidate).
4395 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
4397 public function set_constraint($ancestorselector) {
4398 $this->attributessecondary['data-constraint'] = $ancestorselector;
4402 * If you call this method the action menu will be displayed but will not be enhanced.
4404 * By not displaying the menu enhanced all items will be displayed in a single row.
4406 * @deprecated since Moodle 3.2
4408 public function do_not_enhance() {
4409 debugging('The method action_menu::do_not_enhance() is deprecated, use a list of action_icon instead.', DEBUG_DEVELOPER);
4413 * Returns true if this action menu will be enhanced.
4415 * @return bool
4417 public function will_be_enhanced() {
4418 return isset($this->attributes['data-enhance']);
4422 * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
4424 * This property can be useful when the action menu is displayed within a parent element that is either floated
4425 * or relatively positioned.
4426 * In that situation the width of the menu is determined by the width of the parent element which may not be large
4427 * enough for the menu items without them wrapping.
4428 * This disables the wrapping so that the menu takes on the width of the longest item.
4430 * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
4432 public function set_nowrap_on_items($value = true) {
4433 $class = 'nowrap-items';
4434 if (!empty($this->attributes['class'])) {
4435 $pos = strpos($this->attributes['class'], $class);
4436 if ($value === true && $pos === false) {
4437 // The value is true and the class has not been set yet. Add it.
4438 $this->attributes['class'] .= ' '.$class;
4439 } else if ($value === false && $pos !== false) {
4440 // The value is false and the class has been set. Remove it.
4441 $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class));
4443 } else if ($value) {
4444 // The value is true and the class has not been set yet. Add it.
4445 $this->attributes['class'] = $class;
4450 * Export for template.
4452 * @param renderer_base $output The renderer.
4453 * @return stdClass
4455 public function export_for_template(renderer_base $output) {
4456 $data = new stdClass();
4457 $attributes = $this->attributes;
4458 $attributesprimary = $this->attributesprimary;
4459 $attributessecondary = $this->attributessecondary;
4461 $data->instance = $this->instance;
4463 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
4464 unset($attributes['class']);
4466 $data->attributes = array_map(function($key, $value) {
4467 return [ 'name' => $key, 'value' => $value ];
4468 }, array_keys($attributes), $attributes);
4470 $primary = new stdClass();
4471 $primary->title = '';
4472 $primary->prioritise = $this->prioritise;
4474 $primary->classes = isset($attributesprimary['class']) ? $attributesprimary['class'] : '';
4475 unset($attributesprimary['class']);
4476 $primary->attributes = array_map(function($key, $value) {
4477 return [ 'name' => $key, 'value' => $value ];
4478 }, array_keys($attributesprimary), $attributesprimary);
4480 $actionicon = $this->actionicon;
4481 if (!empty($this->menutrigger)) {
4482 $primary->menutrigger = $this->menutrigger;
4483 $primary->triggerextraclasses = $this->triggerextraclasses;
4484 } else {
4485 $primary->title = get_string('actions');
4486 $actionicon = new pix_icon('t/edit_menu', '', 'moodle', ['class' => 'iconsmall actionmenu', 'title' => '']);
4489 if ($actionicon instanceof pix_icon) {
4490 $primary->icon = $actionicon->export_for_pix();
4491 if (!empty($actionicon->attributes['alt'])) {
4492 $primary->title = $actionicon->attributes['alt'];
4494 } else {
4495 $primary->iconraw = $actionicon ? $output->render($actionicon) : '';
4498 $primary->actiontext = $this->actiontext ? (string) $this->actiontext : '';
4499 $primary->items = array_map(function($item) use ($output) {
4500 $data = (object) [];
4501 if ($item instanceof action_menu_link) {
4502 $data->actionmenulink = $item->export_for_template($output);
4503 } else if ($item instanceof action_menu_filler) {
4504 $data->actionmenufiller = $item->export_for_template($output);
4505 } else if ($item instanceof action_link) {
4506 $data->actionlink = $item->export_for_template($output);
4507 } else if ($item instanceof pix_icon) {
4508 $data->pixicon = $item->export_for_template($output);
4509 } else {
4510 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4512 return $data;
4513 }, $this->primaryactions);
4515 $secondary = new stdClass();
4516 $secondary->classes = isset($attributessecondary['class']) ? $attributessecondary['class'] : '';
4517 unset($attributessecondary['class']);
4518 $secondary->attributes = array_map(function($key, $value) {
4519 return [ 'name' => $key, 'value' => $value ];
4520 }, array_keys($attributessecondary), $attributessecondary);
4521 $secondary->items = array_map(function($item) use ($output) {
4522 $data = (object) [];
4523 if ($item instanceof action_menu_link) {
4524 $data->actionmenulink = $item->export_for_template($output);
4525 } else if ($item instanceof action_menu_filler) {
4526 $data->actionmenufiller = $item->export_for_template($output);
4527 } else if ($item instanceof action_link) {
4528 $data->actionlink = $item->export_for_template($output);
4529 } else if ($item instanceof pix_icon) {
4530 $data->pixicon = $item->export_for_template($output);
4531 } else {
4532 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4534 return $data;
4535 }, $this->secondaryactions);
4537 $data->primary = $primary;
4538 $data->secondary = $secondary;
4540 return $data;
4546 * An action menu filler
4548 * @package core
4549 * @category output
4550 * @copyright 2013 Andrew Nicols
4551 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4553 class action_menu_filler extends action_link implements renderable {
4556 * True if this is a primary action. False if not.
4557 * @var bool
4559 public $primary = true;
4562 * Constructs the object.
4564 public function __construct() {
4569 * An action menu action
4571 * @package core
4572 * @category output
4573 * @copyright 2013 Sam Hemelryk
4574 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4576 class action_menu_link extends action_link implements renderable {
4579 * True if this is a primary action. False if not.
4580 * @var bool
4582 public $primary = true;
4585 * The action menu this link has been added to.
4586 * @var action_menu
4588 public $actionmenu = null;
4591 * Constructs the object.
4593 * @param moodle_url $url The URL for the action.
4594 * @param pix_icon $icon The icon to represent the action.
4595 * @param string $text The text to represent the action.
4596 * @param bool $primary Whether this is a primary action or not.
4597 * @param array $attributes Any attribtues associated with the action.
4599 public function __construct(moodle_url $url, pix_icon $icon = null, $text, $primary = true, array $attributes = array()) {
4600 parent::__construct($url, $text, null, $attributes, $icon);
4601 $this->primary = (bool)$primary;
4602 $this->add_class('menu-action');
4603 $this->attributes['role'] = 'menuitem';
4607 * Export for template.
4609 * @param renderer_base $output The renderer.
4610 * @return stdClass
4612 public function export_for_template(renderer_base $output) {
4613 static $instance = 1;
4615 $data = parent::export_for_template($output);
4616 $data->instance = $instance++;
4618 // Ignore what the parent did with the attributes, except for ID and class.
4619 $data->attributes = [];
4620 $attributes = $this->attributes;
4621 unset($attributes['id']);
4622 unset($attributes['class']);
4624 // Handle text being a renderable.
4625 if ($this->text instanceof renderable) {
4626 $data->text = $this->render($this->text);
4629 $data->showtext = (!$this->icon || $this->primary === false);
4631 $data->icon = null;
4632 if ($this->icon) {
4633 $icon = $this->icon;
4634 if ($this->primary || !$this->actionmenu->will_be_enhanced()) {
4635 $attributes['title'] = $data->text;
4637 $data->icon = $icon ? $icon->export_for_pix() : null;
4640 $data->disabled = !empty($attributes['disabled']);
4641 unset($attributes['disabled']);
4643 $data->attributes = array_map(function($key, $value) {
4644 return [
4645 'name' => $key,
4646 'value' => $value
4648 }, array_keys($attributes), $attributes);
4650 return $data;
4655 * A primary action menu action
4657 * @package core
4658 * @category output
4659 * @copyright 2013 Sam Hemelryk
4660 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4662 class action_menu_link_primary extends action_menu_link {
4664 * Constructs the object.
4666 * @param moodle_url $url
4667 * @param pix_icon $icon
4668 * @param string $text
4669 * @param array $attributes
4671 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
4672 parent::__construct($url, $icon, $text, true, $attributes);
4677 * A secondary action menu action
4679 * @package core
4680 * @category output
4681 * @copyright 2013 Sam Hemelryk
4682 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4684 class action_menu_link_secondary extends action_menu_link {
4686 * Constructs the object.
4688 * @param moodle_url $url
4689 * @param pix_icon $icon
4690 * @param string $text
4691 * @param array $attributes
4693 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
4694 parent::__construct($url, $icon, $text, false, $attributes);
4699 * Represents a set of preferences groups.
4701 * @package core
4702 * @category output
4703 * @copyright 2015 Frédéric Massart - FMCorz.net
4704 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4706 class preferences_groups implements renderable {
4709 * Array of preferences_group.
4710 * @var array
4712 public $groups;
4715 * Constructor.
4716 * @param array $groups of preferences_group
4718 public function __construct($groups) {
4719 $this->groups = $groups;
4725 * Represents a group of preferences page link.
4727 * @package core
4728 * @category output
4729 * @copyright 2015 Frédéric Massart - FMCorz.net
4730 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4732 class preferences_group implements renderable {
4735 * Title of the group.
4736 * @var string
4738 public $title;
4741 * Array of navigation_node.
4742 * @var array
4744 public $nodes;
4747 * Constructor.
4748 * @param string $title The title.
4749 * @param array $nodes of navigation_node.
4751 public function __construct($title, $nodes) {
4752 $this->title = $title;
4753 $this->nodes = $nodes;
4758 * Progress bar class.
4760 * Manages the display of a progress bar.
4762 * To use this class.
4763 * - construct
4764 * - call create (or use the 3rd param to the constructor)
4765 * - call update or update_full() or update() repeatedly
4767 * @copyright 2008 jamiesensei
4768 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4769 * @package core
4770 * @category output
4772 class progress_bar implements renderable, templatable {
4773 /** @var string html id */
4774 private $html_id;
4775 /** @var int total width */
4776 private $width;
4777 /** @var int last percentage printed */
4778 private $percent = 0;
4779 /** @var int time when last printed */
4780 private $lastupdate = 0;
4781 /** @var int when did we start printing this */
4782 private $time_start = 0;
4785 * Constructor
4787 * Prints JS code if $autostart true.
4789 * @param string $htmlid The container ID.
4790 * @param int $width The suggested width.
4791 * @param bool $autostart Whether to start the progress bar right away.
4793 public function __construct($htmlid = '', $width = 500, $autostart = false) {
4794 if (!CLI_SCRIPT && !NO_OUTPUT_BUFFERING) {
4795 debugging('progress_bar used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', DEBUG_DEVELOPER);
4798 if (!empty($htmlid)) {
4799 $this->html_id = $htmlid;
4800 } else {
4801 $this->html_id = 'pbar_'.uniqid();
4804 $this->width = $width;
4806 if ($autostart) {
4807 $this->create();
4812 * Create a new progress bar, this function will output html.
4814 * @return void Echo's output
4816 public function create() {
4817 global $OUTPUT;
4819 $this->time_start = microtime(true);
4820 if (CLI_SCRIPT) {
4821 return; // Temporary solution for cli scripts.
4824 flush();
4825 echo $OUTPUT->render($this);
4826 flush();
4830 * Update the progress bar.
4832 * @param int $percent From 1-100.
4833 * @param string $msg The message.
4834 * @return void Echo's output
4835 * @throws coding_exception
4837 private function _update($percent, $msg) {
4838 if (empty($this->time_start)) {
4839 throw new coding_exception('You must call create() (or use the $autostart ' .
4840 'argument to the constructor) before you try updating the progress bar.');
4843 if (CLI_SCRIPT) {
4844 return; // Temporary solution for cli scripts.
4847 $estimate = $this->estimate($percent);
4849 if ($estimate === null) {
4850 // Always do the first and last updates.
4851 } else if ($estimate == 0) {
4852 // Always do the last updates.
4853 } else if ($this->lastupdate + 20 < time()) {
4854 // We must update otherwise browser would time out.
4855 } else if (round($this->percent, 2) === round($percent, 2)) {
4856 // No significant change, no need to update anything.
4857 return;
4860 $estimatemsg = null;
4861 if (is_numeric($estimate)) {
4862 $estimatemsg = get_string('secondsleft', 'moodle', round($estimate, 2));
4865 $this->percent = round($percent, 2);
4866 $this->lastupdate = microtime(true);
4868 echo html_writer::script(js_writer::function_call('updateProgressBar',
4869 array($this->html_id, $this->percent, $msg, $estimatemsg)));
4870 flush();
4874 * Estimate how much time it is going to take.
4876 * @param int $pt From 1-100.
4877 * @return mixed Null (unknown), or int.
4879 private function estimate($pt) {
4880 if ($this->lastupdate == 0) {
4881 return null;
4883 if ($pt < 0.00001) {
4884 return null; // We do not know yet how long it will take.
4886 if ($pt > 99.99999) {
4887 return 0; // Nearly done, right?
4889 $consumed = microtime(true) - $this->time_start;
4890 if ($consumed < 0.001) {
4891 return null;
4894 return (100 - $pt) * ($consumed / $pt);
4898 * Update progress bar according percent.
4900 * @param int $percent From 1-100.
4901 * @param string $msg The message needed to be shown.
4903 public function update_full($percent, $msg) {
4904 $percent = max(min($percent, 100), 0);
4905 $this->_update($percent, $msg);
4909 * Update progress bar according the number of tasks.
4911 * @param int $cur Current task number.
4912 * @param int $total Total task number.
4913 * @param string $msg The message needed to be shown.
4915 public function update($cur, $total, $msg) {
4916 $percent = ($cur / $total) * 100;
4917 $this->update_full($percent, $msg);
4921 * Restart the progress bar.
4923 public function restart() {
4924 $this->percent = 0;
4925 $this->lastupdate = 0;
4926 $this->time_start = 0;
4930 * Export for template.
4932 * @param renderer_base $output The renderer.
4933 * @return array
4935 public function export_for_template(renderer_base $output) {
4936 return [
4937 'id' => $this->html_id,
4938 'width' => $this->width,