Merge branch 'MDL-47162' of https://github.com/stronk7/moodle
[moodle.git] / lib / outputcomponents.php
blob157bb158d09fdd2bdd828c9529d90edce9a4f8e4
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 * User picture constructor.
207 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
208 * It is recommended to add also contextid of the user for performance reasons.
210 public function __construct(stdClass $user) {
211 global $DB;
213 if (empty($user->id)) {
214 throw new coding_exception('User id is required when printing user avatar image.');
217 // only touch the DB if we are missing data and complain loudly...
218 $needrec = false;
219 foreach (self::$fields as $field) {
220 if (!array_key_exists($field, $user)) {
221 $needrec = true;
222 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
223 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER);
224 break;
228 if ($needrec) {
229 $this->user = $DB->get_record('user', array('id'=>$user->id), self::fields(), MUST_EXIST);
230 } else {
231 $this->user = clone($user);
236 * Returns a list of required user fields, useful when fetching required user info from db.
238 * In some cases we have to fetch the user data together with some other information,
239 * the idalias is useful there because the id would otherwise override the main
240 * id of the result record. Please note it has to be converted back to id before rendering.
242 * @param string $tableprefix name of database table prefix in query
243 * @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)
244 * @param string $idalias alias of id field
245 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
246 * @return string
248 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
249 if (!$tableprefix and !$extrafields and !$idalias) {
250 return implode(',', self::$fields);
252 if ($tableprefix) {
253 $tableprefix .= '.';
255 foreach (self::$fields as $field) {
256 if ($field === 'id' and $idalias and $idalias !== 'id') {
257 $fields[$field] = "$tableprefix$field AS $idalias";
258 } else {
259 if ($fieldprefix and $field !== 'id') {
260 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
261 } else {
262 $fields[$field] = "$tableprefix$field";
266 // add extra fields if not already there
267 if ($extrafields) {
268 foreach ($extrafields as $e) {
269 if ($e === 'id' or isset($fields[$e])) {
270 continue;
272 if ($fieldprefix) {
273 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
274 } else {
275 $fields[$e] = "$tableprefix$e";
279 return implode(',', $fields);
283 * Extract the aliased user fields from a given record
285 * Given a record that was previously obtained using {@link self::fields()} with aliases,
286 * this method extracts user related unaliased fields.
288 * @param stdClass $record containing user picture fields
289 * @param array $extrafields extra fields included in the $record
290 * @param string $idalias alias of the id field
291 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
292 * @return stdClass object with unaliased user fields
294 public static function unalias(stdClass $record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
296 if (empty($idalias)) {
297 $idalias = 'id';
300 $return = new stdClass();
302 foreach (self::$fields as $field) {
303 if ($field === 'id') {
304 if (property_exists($record, $idalias)) {
305 $return->id = $record->{$idalias};
307 } else {
308 if (property_exists($record, $fieldprefix.$field)) {
309 $return->{$field} = $record->{$fieldprefix.$field};
313 // add extra fields if not already there
314 if ($extrafields) {
315 foreach ($extrafields as $e) {
316 if ($e === 'id' or property_exists($return, $e)) {
317 continue;
319 $return->{$e} = $record->{$fieldprefix.$e};
323 return $return;
327 * Works out the URL for the users picture.
329 * This method is recommended as it avoids costly redirects of user pictures
330 * if requests are made for non-existent files etc.
332 * @param moodle_page $page
333 * @param renderer_base $renderer
334 * @return moodle_url
336 public function get_url(moodle_page $page, renderer_base $renderer = null) {
337 global $CFG;
339 if (is_null($renderer)) {
340 $renderer = $page->get_renderer('core');
343 // Sort out the filename and size. Size is only required for the gravatar
344 // implementation presently.
345 if (empty($this->size)) {
346 $filename = 'f2';
347 $size = 35;
348 } else if ($this->size === true or $this->size == 1) {
349 $filename = 'f1';
350 $size = 100;
351 } else if ($this->size > 100) {
352 $filename = 'f3';
353 $size = (int)$this->size;
354 } else if ($this->size >= 50) {
355 $filename = 'f1';
356 $size = (int)$this->size;
357 } else {
358 $filename = 'f2';
359 $size = (int)$this->size;
362 $defaulturl = $renderer->pix_url('u/'.$filename); // default image
364 if ((!empty($CFG->forcelogin) and !isloggedin()) ||
365 (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
366 // Protect images if login required and not logged in;
367 // also if login is required for profile images and is not logged in or guest
368 // do not use require_login() because it is expensive and not suitable here anyway.
369 return $defaulturl;
372 // First try to detect deleted users - but do not read from database for performance reasons!
373 if (!empty($this->user->deleted) or strpos($this->user->email, '@') === false) {
374 // All deleted users should have email replaced by md5 hash,
375 // all active users are expected to have valid email.
376 return $defaulturl;
379 // Did the user upload a picture?
380 if ($this->user->picture > 0) {
381 if (!empty($this->user->contextid)) {
382 $contextid = $this->user->contextid;
383 } else {
384 $context = context_user::instance($this->user->id, IGNORE_MISSING);
385 if (!$context) {
386 // This must be an incorrectly deleted user, all other users have context.
387 return $defaulturl;
389 $contextid = $context->id;
392 $path = '/';
393 if (clean_param($page->theme->name, PARAM_THEME) == $page->theme->name) {
394 // We append the theme name to the file path if we have it so that
395 // in the circumstance that the profile picture is not available
396 // when the user actually requests it they still get the profile
397 // picture for the correct theme.
398 $path .= $page->theme->name.'/';
400 // Set the image URL to the URL for the uploaded file and return.
401 $url = moodle_url::make_pluginfile_url($contextid, 'user', 'icon', NULL, $path, $filename);
402 $url->param('rev', $this->user->picture);
403 return $url;
406 if ($this->user->picture == 0 and !empty($CFG->enablegravatar)) {
407 // Normalise the size variable to acceptable bounds
408 if ($size < 1 || $size > 512) {
409 $size = 35;
411 // Hash the users email address
412 $md5 = md5(strtolower(trim($this->user->email)));
413 // Build a gravatar URL with what we know.
415 // Find the best default image URL we can (MDL-35669)
416 if (empty($CFG->gravatardefaulturl)) {
417 $absoluteimagepath = $page->theme->resolve_image_location('u/'.$filename, 'core');
418 if (strpos($absoluteimagepath, $CFG->dirroot) === 0) {
419 $gravatardefault = $CFG->wwwroot . substr($absoluteimagepath, strlen($CFG->dirroot));
420 } else {
421 $gravatardefault = $CFG->wwwroot . '/pix/u/' . $filename . '.png';
423 } else {
424 $gravatardefault = $CFG->gravatardefaulturl;
427 // If the currently requested page is https then we'll return an
428 // https gravatar page.
429 if (is_https()) {
430 $gravatardefault = str_replace($CFG->wwwroot, $CFG->httpswwwroot, $gravatardefault); // Replace by secure url.
431 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
432 } else {
433 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
437 return $defaulturl;
442 * Data structure representing a help icon.
444 * @copyright 2010 Petr Skoda (info@skodak.org)
445 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
446 * @since Moodle 2.0
447 * @package core
448 * @category output
450 class help_icon implements renderable, templatable {
453 * @var string lang pack identifier (without the "_help" suffix),
454 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
455 * must exist.
457 public $identifier;
460 * @var string Component name, the same as in get_string()
462 public $component;
465 * @var string Extra descriptive text next to the icon
467 public $linktext = null;
470 * Constructor
472 * @param string $identifier string for help page title,
473 * string with _help suffix is used for the actual help text.
474 * string with _link suffix is used to create a link to further info (if it exists)
475 * @param string $component
477 public function __construct($identifier, $component) {
478 $this->identifier = $identifier;
479 $this->component = $component;
483 * Verifies that both help strings exists, shows debug warnings if not
485 public function diag_strings() {
486 $sm = get_string_manager();
487 if (!$sm->string_exists($this->identifier, $this->component)) {
488 debugging("Help title string does not exist: [$this->identifier, $this->component]");
490 if (!$sm->string_exists($this->identifier.'_help', $this->component)) {
491 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
496 * Export this data so it can be used as the context for a mustache template.
498 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
499 * @return array
501 public function export_for_template(renderer_base $output) {
502 global $CFG;
504 $title = get_string($this->identifier, $this->component);
506 if (empty($this->linktext)) {
507 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
508 } else {
509 $alt = get_string('helpwiththis');
512 $data = get_formatted_help_string($this->identifier, $this->component, false);
514 $data->alt = $alt;
515 $data->icon = (new pix_icon('help', $alt, 'core', ['class' => 'iconhelp']))->export_for_template($output);
516 $data->linktext = $this->linktext;
517 $data->title = get_string('helpprefix2', '', trim($title, ". \t"));
518 $data->url = (new moodle_url($CFG->httpswwwroot . '/help.php', [
519 'component' => $this->component,
520 'identifier' => $this->identifier,
521 'lang' => current_language()
522 ]))->out(false);
524 $data->ltr = !right_to_left();
525 return $data;
531 * Data structure representing an icon.
533 * @copyright 2010 Petr Skoda
534 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
535 * @since Moodle 2.0
536 * @package core
537 * @category output
539 class pix_icon implements renderable, templatable {
542 * @var string The icon name
544 var $pix;
547 * @var string The component the icon belongs to.
549 var $component;
552 * @var array An array of attributes to use on the icon
554 var $attributes = array();
557 * Constructor
559 * @param string $pix short icon name
560 * @param string $alt The alt text to use for the icon
561 * @param string $component component name
562 * @param array $attributes html attributes
564 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
565 $this->pix = $pix;
566 $this->component = $component;
567 $this->attributes = (array)$attributes;
569 if (empty($this->attributes['class'])) {
570 $this->attributes['class'] = 'smallicon';
573 // If the alt is empty, don't place it in the attributes, otherwise it will override parent alt text.
574 if (!is_null($alt)) {
575 $this->attributes['alt'] = $alt;
577 // If there is no title, set it to the attribute.
578 if (!isset($this->attributes['title'])) {
579 $this->attributes['title'] = $this->attributes['alt'];
581 } else {
582 unset($this->attributes['alt']);
585 if (empty($this->attributes['title'])) {
586 // Remove the title attribute if empty, we probably want to use the parent node's title
587 // and some browsers might overwrite it with an empty title.
588 unset($this->attributes['title']);
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) {
599 $attributes = $this->attributes;
600 $attributes['src'] = $output->pix_url($this->pix, $this->component)->out(false);
601 $templatecontext = array();
602 foreach ($attributes as $name => $value) {
603 $templatecontext[] = array('name' => $name, 'value' => $value);
605 $data = array('attributes' => $templatecontext);
607 return $data;
612 * Data structure representing an emoticon image
614 * @copyright 2010 David Mudrak
615 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
616 * @since Moodle 2.0
617 * @package core
618 * @category output
620 class pix_emoticon extends pix_icon implements renderable {
623 * Constructor
624 * @param string $pix short icon name
625 * @param string $alt alternative text
626 * @param string $component emoticon image provider
627 * @param array $attributes explicit HTML attributes
629 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
630 if (empty($attributes['class'])) {
631 $attributes['class'] = 'emoticon';
633 parent::__construct($pix, $alt, $component, $attributes);
638 * Data structure representing a simple form with only one button.
640 * @copyright 2009 Petr Skoda
641 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
642 * @since Moodle 2.0
643 * @package core
644 * @category output
646 class single_button implements renderable {
649 * @var moodle_url Target url
651 var $url;
654 * @var string Button label
656 var $label;
659 * @var string Form submit method post or get
661 var $method = 'post';
664 * @var string Wrapping div class
666 var $class = 'singlebutton';
669 * @var bool True if button disabled, false if normal
671 var $disabled = false;
674 * @var string Button tooltip
676 var $tooltip = null;
679 * @var string Form id
681 var $formid;
684 * @var array List of attached actions
686 var $actions = array();
689 * @var array $params URL Params
691 var $params;
694 * @var string Action id
696 var $actionid;
699 * Constructor
700 * @param moodle_url $url
701 * @param string $label button text
702 * @param string $method get or post submit method
704 public function __construct(moodle_url $url, $label, $method='post') {
705 $this->url = clone($url);
706 $this->label = $label;
707 $this->method = $method;
711 * Shortcut for adding a JS confirm dialog when the button is clicked.
712 * The message must be a yes/no question.
714 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
716 public function add_confirm_action($confirmmessage) {
717 $this->add_action(new confirm_action($confirmmessage));
721 * Add action to the button.
722 * @param component_action $action
724 public function add_action(component_action $action) {
725 $this->actions[] = $action;
729 * Export data.
731 * @param renderer_base $output Renderer.
732 * @return stdClass
734 public function export_for_template(renderer_base $output) {
735 $url = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
737 $data = new stdClass();
738 $data->id = html_writer::random_id('single_button');
739 $data->formid = $this->formid;
740 $data->method = $this->method;
741 $data->url = $url === '' ? '#' : $url;
742 $data->label = $this->label;
743 $data->classes = $this->class;
744 $data->disabled = $this->disabled;
745 $data->tooltip = $this->tooltip;
747 // Form parameters.
748 $params = $this->url->params();
749 if ($this->method === 'post') {
750 $params['sesskey'] = sesskey();
752 $data->params = array_map(function($key) use ($params) {
753 return ['name' => $key, 'value' => $params[$key]];
754 }, array_keys($params));
756 // Button actions.
757 $actions = $this->actions;
758 $data->actions = array_map(function($action) use ($output) {
759 return $action->export_for_template($output);
760 }, $actions);
761 $data->hasactions = !empty($data->actions);
763 return $data;
769 * Simple form with just one select field that gets submitted automatically.
771 * If JS not enabled small go button is printed too.
773 * @copyright 2009 Petr Skoda
774 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
775 * @since Moodle 2.0
776 * @package core
777 * @category output
779 class single_select implements renderable, templatable {
782 * @var moodle_url Target url - includes hidden fields
784 var $url;
787 * @var string Name of the select element.
789 var $name;
792 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
793 * it is also possible to specify optgroup as complex label array ex.:
794 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
795 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
797 var $options;
800 * @var string Selected option
802 var $selected;
805 * @var array Nothing selected
807 var $nothing;
810 * @var array Extra select field attributes
812 var $attributes = array();
815 * @var string Button label
817 var $label = '';
820 * @var array Button label's attributes
822 var $labelattributes = array();
825 * @var string Form submit method post or get
827 var $method = 'get';
830 * @var string Wrapping div class
832 var $class = 'singleselect';
835 * @var bool True if button disabled, false if normal
837 var $disabled = false;
840 * @var string Button tooltip
842 var $tooltip = null;
845 * @var string Form id
847 var $formid = null;
850 * @var array List of attached actions
852 var $helpicon = null;
855 * Constructor
856 * @param moodle_url $url form action target, includes hidden fields
857 * @param string $name name of selection field - the changing parameter in url
858 * @param array $options list of options
859 * @param string $selected selected element
860 * @param array $nothing
861 * @param string $formid
863 public function __construct(moodle_url $url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
864 $this->url = $url;
865 $this->name = $name;
866 $this->options = $options;
867 $this->selected = $selected;
868 $this->nothing = $nothing;
869 $this->formid = $formid;
873 * Shortcut for adding a JS confirm dialog when the button is clicked.
874 * The message must be a yes/no question.
876 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
878 public function add_confirm_action($confirmmessage) {
879 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
883 * Add action to the button.
885 * @param component_action $action
887 public function add_action(component_action $action) {
888 $this->actions[] = $action;
892 * Adds help icon.
894 * @deprecated since Moodle 2.0
896 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
897 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
901 * Adds help icon.
903 * @param string $identifier The keyword that defines a help page
904 * @param string $component
906 public function set_help_icon($identifier, $component = 'moodle') {
907 $this->helpicon = new help_icon($identifier, $component);
911 * Sets select's label
913 * @param string $label
914 * @param array $attributes (optional)
916 public function set_label($label, $attributes = array()) {
917 $this->label = $label;
918 $this->labelattributes = $attributes;
923 * Export data.
925 * @param renderer_base $output Renderer.
926 * @return stdClass
928 public function export_for_template(renderer_base $output) {
929 $attributes = $this->attributes;
931 $data = new stdClass();
932 $data->name = $this->name;
933 $data->method = $this->method;
934 $data->action = $this->method === 'get' ? $this->url->out_omit_querystring(true) : $this->url->out_omit_querystring();
935 $data->classes = 'autosubmit ' . $this->class;
936 $data->label = $this->label;
937 $data->disabled = $this->disabled;
938 $data->title = $this->tooltip;
939 $data->formid = $this->formid;
940 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('single_select');
941 unset($attributes['id']);
943 // Form parameters.
944 $params = $this->url->params();
945 if ($this->method === 'post') {
946 $params['sesskey'] = sesskey();
948 $data->params = array_map(function($key) use ($params) {
949 return ['name' => $key, 'value' => $params[$key]];
950 }, array_keys($params));
952 // Select options.
953 $hasnothing = false;
954 if (is_string($this->nothing) && $this->nothing !== '') {
955 $nothing = ['' => $this->nothing];
956 $hasnothing = true;
957 } else if (is_array($this->nothing)) {
958 $nothingvalue = reset($this->nothing);
959 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
960 $nothing = [key($this->nothing) => get_string('choosedots')];
961 } else {
962 $nothing = $this->nothing;
964 $hasnothing = true;
966 if ($hasnothing) {
967 $options = $nothing + $this->options;
968 } else {
969 $options = $this->options;
971 $data->hasnothing = $hasnothing;
972 $data->nothingkey = $hasnothing ? key($nothing) : false;
974 foreach ($options as $value => $name) {
975 if (is_array($options[$value])) {
976 foreach ($options[$value] as $optgroupname => $optgroupvalues) {
977 $sublist = [];
978 foreach ($optgroupvalues as $optvalue => $optname) {
979 $sublist[] = [
980 'value' => $optvalue,
981 'name' => $optname,
982 'selected' => strval($this->selected) === strval($optvalue),
985 $data->options[] = [
986 'name' => $optgroupname,
987 'optgroup' => true,
988 'options' => $sublist
991 } else {
992 $data->options[] = [
993 'value' => $value,
994 'name' => $options[$value],
995 'selected' => strval($this->selected) === strval($value),
996 'optgroup' => false
1001 // Label attributes.
1002 $data->labelattributes = [];
1003 foreach ($this->labelattributes as $key => $value) {
1004 $data->labelattributes = ['name' => $key, 'value' => $value];
1007 // Help icon.
1008 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1010 return $data;
1015 * Simple URL selection widget description.
1017 * @copyright 2009 Petr Skoda
1018 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1019 * @since Moodle 2.0
1020 * @package core
1021 * @category output
1023 class url_select implements renderable, templatable {
1025 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
1026 * it is also possible to specify optgroup as complex label array ex.:
1027 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1028 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1030 var $urls;
1033 * @var string Selected option
1035 var $selected;
1038 * @var array Nothing selected
1040 var $nothing;
1043 * @var array Extra select field attributes
1045 var $attributes = array();
1048 * @var string Button label
1050 var $label = '';
1053 * @var array Button label's attributes
1055 var $labelattributes = array();
1058 * @var string Wrapping div class
1060 var $class = 'urlselect';
1063 * @var bool True if button disabled, false if normal
1065 var $disabled = false;
1068 * @var string Button tooltip
1070 var $tooltip = null;
1073 * @var string Form id
1075 var $formid = null;
1078 * @var array List of attached actions
1080 var $helpicon = null;
1083 * @var string If set, makes button visible with given name for button
1085 var $showbutton = null;
1088 * Constructor
1089 * @param array $urls list of options
1090 * @param string $selected selected element
1091 * @param array $nothing
1092 * @param string $formid
1093 * @param string $showbutton Set to text of button if it should be visible
1094 * or null if it should be hidden (hidden version always has text 'go')
1096 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
1097 $this->urls = $urls;
1098 $this->selected = $selected;
1099 $this->nothing = $nothing;
1100 $this->formid = $formid;
1101 $this->showbutton = $showbutton;
1105 * Adds help icon.
1107 * @deprecated since Moodle 2.0
1109 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1110 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1114 * Adds help icon.
1116 * @param string $identifier The keyword that defines a help page
1117 * @param string $component
1119 public function set_help_icon($identifier, $component = 'moodle') {
1120 $this->helpicon = new help_icon($identifier, $component);
1124 * Sets select's label
1126 * @param string $label
1127 * @param array $attributes (optional)
1129 public function set_label($label, $attributes = array()) {
1130 $this->label = $label;
1131 $this->labelattributes = $attributes;
1135 * Clean a URL.
1137 * @param string $value The URL.
1138 * @return The cleaned URL.
1140 protected function clean_url($value) {
1141 global $CFG;
1143 if (empty($value)) {
1144 // Nothing.
1146 } else if (strpos($value, $CFG->wwwroot . '/') === 0) {
1147 $value = str_replace($CFG->wwwroot, '', $value);
1149 } else if (strpos($value, '/') !== 0) {
1150 debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER);
1153 return $value;
1157 * Flatten the options for Mustache.
1159 * This also cleans the URLs.
1161 * @param array $options The options.
1162 * @param array $nothing The nothing option.
1163 * @return array
1165 protected function flatten_options($options, $nothing) {
1166 $flattened = [];
1168 foreach ($options as $value => $option) {
1169 if (is_array($option)) {
1170 foreach ($option as $groupname => $optoptions) {
1171 if (!isset($flattened[$groupname])) {
1172 $flattened[$groupname] = [
1173 'name' => $groupname,
1174 'isgroup' => true,
1175 'options' => []
1178 foreach ($optoptions as $optvalue => $optoption) {
1179 $cleanedvalue = $this->clean_url($optvalue);
1180 $flattened[$groupname]['options'][$cleanedvalue] = [
1181 'name' => $optoption,
1182 'value' => $cleanedvalue,
1183 'selected' => $this->selected == $optvalue,
1188 } else {
1189 $cleanedvalue = $this->clean_url($value);
1190 $flattened[$cleanedvalue] = [
1191 'name' => $option,
1192 'value' => $cleanedvalue,
1193 'selected' => $this->selected == $value,
1198 if (!empty($nothing)) {
1199 $value = key($nothing);
1200 $name = reset($nothing);
1201 $flattened = [
1202 $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected == $value]
1203 ] + $flattened;
1206 // Make non-associative array.
1207 foreach ($flattened as $key => $value) {
1208 if (!empty($value['options'])) {
1209 $flattened[$key]['options'] = array_values($value['options']);
1212 $flattened = array_values($flattened);
1214 return $flattened;
1218 * Export for template.
1220 * @param renderer_base $output Renderer.
1221 * @return stdClass
1223 public function export_for_template(renderer_base $output) {
1224 $attributes = $this->attributes;
1226 $data = new stdClass();
1227 $data->formid = !empty($this->formid) ? $this->formid : html_writer::random_id('url_select_f');
1228 $data->classes = $this->class;
1229 $data->label = $this->label;
1230 $data->disabled = $this->disabled;
1231 $data->title = $this->tooltip;
1232 $data->id = !empty($attributes['id']) ? $attributes['id'] : html_writer::random_id('url_select');
1233 $data->sesskey = sesskey();
1234 $data->action = (new moodle_url('/course/jumpto.php'))->out(false);
1236 // Remove attributes passed as property directly.
1237 unset($attributes['class']);
1238 unset($attributes['id']);
1239 unset($attributes['name']);
1240 unset($attributes['title']);
1242 $data->showbutton = $this->showbutton;
1243 if (empty($this->showbutton)) {
1244 $data->classes .= ' autosubmit';
1247 // Select options.
1248 $nothing = false;
1249 if (is_string($this->nothing) && $this->nothing !== '') {
1250 $nothing = ['' => $this->nothing];
1251 } else if (is_array($this->nothing)) {
1252 $nothingvalue = reset($this->nothing);
1253 if ($nothingvalue === 'choose' || $nothingvalue === 'choosedots') {
1254 $nothing = [key($this->nothing) => get_string('choosedots')];
1255 } else {
1256 $nothing = $this->nothing;
1259 $data->hasnothing = !empty($nothing);
1260 $data->nothingkey = $data->hasnothing ? key($nothing) : false;
1261 $data->options = $this->flatten_options($this->urls, $nothing);
1263 // Label attributes.
1264 $data->labelattributes = [];
1265 foreach ($this->labelattributes as $key => $value) {
1266 $data->labelattributes[] = ['name' => $key, 'value' => $value];
1269 // Help icon.
1270 $data->helpicon = !empty($this->helpicon) ? $this->helpicon->export_for_template($output) : false;
1272 // Finally all the remaining attributes.
1273 $data->attributes = [];
1274 foreach ($this->attributes as $key => $value) {
1275 $data->attributes = ['name' => $key, 'value' => $value];
1278 return $data;
1283 * Data structure describing html link with special action attached.
1285 * @copyright 2010 Petr Skoda
1286 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1287 * @since Moodle 2.0
1288 * @package core
1289 * @category output
1291 class action_link implements renderable {
1294 * @var moodle_url Href url
1296 public $url;
1299 * @var string Link text HTML fragment
1301 public $text;
1304 * @var array HTML attributes
1306 public $attributes;
1309 * @var array List of actions attached to link
1311 public $actions;
1314 * @var pix_icon Optional pix icon to render with the link
1316 public $icon;
1319 * Constructor
1320 * @param moodle_url $url
1321 * @param string $text HTML fragment
1322 * @param component_action $action
1323 * @param array $attributes associative array of html link attributes + disabled
1324 * @param pix_icon $icon optional pix_icon to render with the link text
1326 public function __construct(moodle_url $url,
1327 $text,
1328 component_action $action=null,
1329 array $attributes=null,
1330 pix_icon $icon=null) {
1331 $this->url = clone($url);
1332 $this->text = $text;
1333 $this->attributes = (array)$attributes;
1334 if ($action) {
1335 $this->add_action($action);
1337 $this->icon = $icon;
1341 * Add action to the link.
1343 * @param component_action $action
1345 public function add_action(component_action $action) {
1346 $this->actions[] = $action;
1350 * Adds a CSS class to this action link object
1351 * @param string $class
1353 public function add_class($class) {
1354 if (empty($this->attributes['class'])) {
1355 $this->attributes['class'] = $class;
1356 } else {
1357 $this->attributes['class'] .= ' ' . $class;
1362 * Returns true if the specified class has been added to this link.
1363 * @param string $class
1364 * @return bool
1366 public function has_class($class) {
1367 return strpos(' ' . $this->attributes['class'] . ' ', ' ' . $class . ' ') !== false;
1371 * Return the rendered HTML for the icon. Useful for rendering action links in a template.
1372 * @return string
1374 public function get_icon_html() {
1375 global $OUTPUT;
1376 if (!$this->icon) {
1377 return '';
1379 return $OUTPUT->render($this->icon);
1383 * Export for template.
1385 * @param renderer_base $output The renderer.
1386 * @return stdClass
1388 public function export_for_template(renderer_base $output) {
1389 $data = new stdClass();
1390 $attributes = $this->attributes;
1392 if (empty($attributes['id'])) {
1393 $attributes['id'] = html_writer::random_id('action_link');
1395 $data->id = $attributes['id'];
1396 unset($attributes['id']);
1398 $data->disabled = !empty($attributes['disabled']);
1399 unset($attributes['disabled']);
1401 $data->text = $this->text instanceof renderable ? $output->render($this->text) : (string) $this->text;
1402 $data->url = $this->url ? $this->url->out(false) : '';
1403 $data->icon = $this->icon ? $this->icon->export_for_template($output) : null;
1404 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
1405 unset($attributes['class']);
1407 $data->attributes = array_map(function($key, $value) {
1408 return [
1409 'name' => $key,
1410 'value' => $value
1412 }, array_keys($attributes), $attributes);
1414 $data->actions = array_map(function($action) use ($output) {
1415 return $action->export_for_template($output);
1416 }, !empty($this->actions) ? $this->actions : []);
1417 $data->hasactions = !empty($this->actions);
1419 return $data;
1424 * Simple html output class
1426 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1427 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1428 * @since Moodle 2.0
1429 * @package core
1430 * @category output
1432 class html_writer {
1435 * Outputs a tag with attributes and contents
1437 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1438 * @param string $contents What goes between the opening and closing tags
1439 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1440 * @return string HTML fragment
1442 public static function tag($tagname, $contents, array $attributes = null) {
1443 return self::start_tag($tagname, $attributes) . $contents . self::end_tag($tagname);
1447 * Outputs an opening tag with attributes
1449 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1450 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1451 * @return string HTML fragment
1453 public static function start_tag($tagname, array $attributes = null) {
1454 return '<' . $tagname . self::attributes($attributes) . '>';
1458 * Outputs a closing tag
1460 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1461 * @return string HTML fragment
1463 public static function end_tag($tagname) {
1464 return '</' . $tagname . '>';
1468 * Outputs an empty tag with attributes
1470 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1471 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1472 * @return string HTML fragment
1474 public static function empty_tag($tagname, array $attributes = null) {
1475 return '<' . $tagname . self::attributes($attributes) . ' />';
1479 * Outputs a tag, but only if the contents are not empty
1481 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1482 * @param string $contents What goes between the opening and closing tags
1483 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1484 * @return string HTML fragment
1486 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1487 if ($contents === '' || is_null($contents)) {
1488 return '';
1490 return self::tag($tagname, $contents, $attributes);
1494 * Outputs a HTML attribute and value
1496 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1497 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1498 * @return string HTML fragment
1500 public static function attribute($name, $value) {
1501 if ($value instanceof moodle_url) {
1502 return ' ' . $name . '="' . $value->out() . '"';
1505 // special case, we do not want these in output
1506 if ($value === null) {
1507 return '';
1510 // no sloppy trimming here!
1511 return ' ' . $name . '="' . s($value) . '"';
1515 * Outputs a list of HTML attributes and values
1517 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1518 * The values will be escaped with {@link s()}
1519 * @return string HTML fragment
1521 public static function attributes(array $attributes = null) {
1522 $attributes = (array)$attributes;
1523 $output = '';
1524 foreach ($attributes as $name => $value) {
1525 $output .= self::attribute($name, $value);
1527 return $output;
1531 * Generates a simple image tag with attributes.
1533 * @param string $src The source of image
1534 * @param string $alt The alternate text for image
1535 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1536 * @return string HTML fragment
1538 public static function img($src, $alt, array $attributes = null) {
1539 $attributes = (array)$attributes;
1540 $attributes['src'] = $src;
1541 $attributes['alt'] = $alt;
1543 return self::empty_tag('img', $attributes);
1547 * Generates random html element id.
1549 * @staticvar int $counter
1550 * @staticvar type $uniq
1551 * @param string $base A string fragment that will be included in the random ID.
1552 * @return string A unique ID
1554 public static function random_id($base='random') {
1555 static $counter = 0;
1556 static $uniq;
1558 if (!isset($uniq)) {
1559 $uniq = uniqid();
1562 $counter++;
1563 return $base.$uniq.$counter;
1567 * Generates a simple html link
1569 * @param string|moodle_url $url The URL
1570 * @param string $text The text
1571 * @param array $attributes HTML attributes
1572 * @return string HTML fragment
1574 public static function link($url, $text, array $attributes = null) {
1575 $attributes = (array)$attributes;
1576 $attributes['href'] = $url;
1577 return self::tag('a', $text, $attributes);
1581 * Generates a simple checkbox with optional label
1583 * @param string $name The name of the checkbox
1584 * @param string $value The value of the checkbox
1585 * @param bool $checked Whether the checkbox is checked
1586 * @param string $label The label for the checkbox
1587 * @param array $attributes Any attributes to apply to the checkbox
1588 * @return string html fragment
1590 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1591 $attributes = (array)$attributes;
1592 $output = '';
1594 if ($label !== '' and !is_null($label)) {
1595 if (empty($attributes['id'])) {
1596 $attributes['id'] = self::random_id('checkbox_');
1599 $attributes['type'] = 'checkbox';
1600 $attributes['value'] = $value;
1601 $attributes['name'] = $name;
1602 $attributes['checked'] = $checked ? 'checked' : null;
1604 $output .= self::empty_tag('input', $attributes);
1606 if ($label !== '' and !is_null($label)) {
1607 $output .= self::tag('label', $label, array('for'=>$attributes['id']));
1610 return $output;
1614 * Generates a simple select yes/no form field
1616 * @param string $name name of select element
1617 * @param bool $selected
1618 * @param array $attributes - html select element attributes
1619 * @return string HTML fragment
1621 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1622 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1623 return self::select($options, $name, $selected, null, $attributes);
1627 * Generates a simple select form field
1629 * @param array $options associative array value=>label ex.:
1630 * array(1=>'One, 2=>Two)
1631 * it is also possible to specify optgroup as complex label array ex.:
1632 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1633 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1634 * @param string $name name of select element
1635 * @param string|array $selected value or array of values depending on multiple attribute
1636 * @param array|bool $nothing add nothing selected option, or false of not added
1637 * @param array $attributes html select element attributes
1638 * @return string HTML fragment
1640 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1641 $attributes = (array)$attributes;
1642 if (is_array($nothing)) {
1643 foreach ($nothing as $k=>$v) {
1644 if ($v === 'choose' or $v === 'choosedots') {
1645 $nothing[$k] = get_string('choosedots');
1648 $options = $nothing + $options; // keep keys, do not override
1650 } else if (is_string($nothing) and $nothing !== '') {
1651 // BC
1652 $options = array(''=>$nothing) + $options;
1655 // we may accept more values if multiple attribute specified
1656 $selected = (array)$selected;
1657 foreach ($selected as $k=>$v) {
1658 $selected[$k] = (string)$v;
1661 if (!isset($attributes['id'])) {
1662 $id = 'menu'.$name;
1663 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1664 $id = str_replace('[', '', $id);
1665 $id = str_replace(']', '', $id);
1666 $attributes['id'] = $id;
1669 if (!isset($attributes['class'])) {
1670 $class = 'menu'.$name;
1671 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1672 $class = str_replace('[', '', $class);
1673 $class = str_replace(']', '', $class);
1674 $attributes['class'] = $class;
1676 $attributes['class'] = 'select ' . $attributes['class']; // Add 'select' selector always
1678 $attributes['name'] = $name;
1680 if (!empty($attributes['disabled'])) {
1681 $attributes['disabled'] = 'disabled';
1682 } else {
1683 unset($attributes['disabled']);
1686 $output = '';
1687 foreach ($options as $value=>$label) {
1688 if (is_array($label)) {
1689 // ignore key, it just has to be unique
1690 $output .= self::select_optgroup(key($label), current($label), $selected);
1691 } else {
1692 $output .= self::select_option($label, $value, $selected);
1695 return self::tag('select', $output, $attributes);
1699 * Returns HTML to display a select box option.
1701 * @param string $label The label to display as the option.
1702 * @param string|int $value The value the option represents
1703 * @param array $selected An array of selected options
1704 * @return string HTML fragment
1706 private static function select_option($label, $value, array $selected) {
1707 $attributes = array();
1708 $value = (string)$value;
1709 if (in_array($value, $selected, true)) {
1710 $attributes['selected'] = 'selected';
1712 $attributes['value'] = $value;
1713 return self::tag('option', $label, $attributes);
1717 * Returns HTML to display a select box option group.
1719 * @param string $groupname The label to use for the group
1720 * @param array $options The options in the group
1721 * @param array $selected An array of selected values.
1722 * @return string HTML fragment.
1724 private static function select_optgroup($groupname, $options, array $selected) {
1725 if (empty($options)) {
1726 return '';
1728 $attributes = array('label'=>$groupname);
1729 $output = '';
1730 foreach ($options as $value=>$label) {
1731 $output .= self::select_option($label, $value, $selected);
1733 return self::tag('optgroup', $output, $attributes);
1737 * This is a shortcut for making an hour selector menu.
1739 * @param string $type The type of selector (years, months, days, hours, minutes)
1740 * @param string $name fieldname
1741 * @param int $currenttime A default timestamp in GMT
1742 * @param int $step minute spacing
1743 * @param array $attributes - html select element attributes
1744 * @return HTML fragment
1746 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1747 global $OUTPUT;
1749 if (!$currenttime) {
1750 $currenttime = time();
1752 $calendartype = \core_calendar\type_factory::get_calendar_instance();
1753 $currentdate = $calendartype->timestamp_to_date_array($currenttime);
1754 $userdatetype = $type;
1755 $timeunits = array();
1757 switch ($type) {
1758 case 'years':
1759 $timeunits = $calendartype->get_years();
1760 $userdatetype = 'year';
1761 break;
1762 case 'months':
1763 $timeunits = $calendartype->get_months();
1764 $userdatetype = 'month';
1765 $currentdate['month'] = (int)$currentdate['mon'];
1766 break;
1767 case 'days':
1768 $timeunits = $calendartype->get_days();
1769 $userdatetype = 'mday';
1770 break;
1771 case 'hours':
1772 for ($i=0; $i<=23; $i++) {
1773 $timeunits[$i] = sprintf("%02d",$i);
1775 break;
1776 case 'minutes':
1777 if ($step != 1) {
1778 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1781 for ($i=0; $i<=59; $i+=$step) {
1782 $timeunits[$i] = sprintf("%02d",$i);
1784 break;
1785 default:
1786 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1789 $attributes = (array) $attributes;
1790 $data = (object) [
1791 'name' => $name,
1792 'id' => !empty($attributes['id']) ? $attributes['id'] : self::random_id('ts_'),
1793 'label' => get_string(substr($type, 0, -1), 'form'),
1794 'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) {
1795 return [
1796 'name' => $timeunits[$value],
1797 'value' => $value,
1798 'selected' => $currentdate[$userdatetype] == $value
1800 }, array_keys($timeunits)),
1803 unset($attributes['id']);
1804 unset($attributes['name']);
1805 $data->attributes = array_map(function($name) use ($attributes) {
1806 return [
1807 'name' => $name,
1808 'value' => $attributes[$name]
1810 }, array_keys($attributes));
1812 return $OUTPUT->render_from_template('core/select_time', $data);
1816 * Shortcut for quick making of lists
1818 * Note: 'list' is a reserved keyword ;-)
1820 * @param array $items
1821 * @param array $attributes
1822 * @param string $tag ul or ol
1823 * @return string
1825 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
1826 $output = html_writer::start_tag($tag, $attributes)."\n";
1827 foreach ($items as $item) {
1828 $output .= html_writer::tag('li', $item)."\n";
1830 $output .= html_writer::end_tag($tag);
1831 return $output;
1835 * Returns hidden input fields created from url parameters.
1837 * @param moodle_url $url
1838 * @param array $exclude list of excluded parameters
1839 * @return string HTML fragment
1841 public static function input_hidden_params(moodle_url $url, array $exclude = null) {
1842 $exclude = (array)$exclude;
1843 $params = $url->params();
1844 foreach ($exclude as $key) {
1845 unset($params[$key]);
1848 $output = '';
1849 foreach ($params as $key => $value) {
1850 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
1851 $output .= self::empty_tag('input', $attributes)."\n";
1853 return $output;
1857 * Generate a script tag containing the the specified code.
1859 * @param string $jscode the JavaScript code
1860 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
1861 * @return string HTML, the code wrapped in <script> tags.
1863 public static function script($jscode, $url=null) {
1864 if ($jscode) {
1865 $attributes = array('type'=>'text/javascript');
1866 return self::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
1868 } else if ($url) {
1869 $attributes = array('type'=>'text/javascript', 'src'=>$url);
1870 return self::tag('script', '', $attributes) . "\n";
1872 } else {
1873 return '';
1878 * Renders HTML table
1880 * This method may modify the passed instance by adding some default properties if they are not set yet.
1881 * If this is not what you want, you should make a full clone of your data before passing them to this
1882 * method. In most cases this is not an issue at all so we do not clone by default for performance
1883 * and memory consumption reasons.
1885 * @param html_table $table data to be rendered
1886 * @return string HTML code
1888 public static function table(html_table $table) {
1889 // prepare table data and populate missing properties with reasonable defaults
1890 if (!empty($table->align)) {
1891 foreach ($table->align as $key => $aa) {
1892 if ($aa) {
1893 $table->align[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
1894 } else {
1895 $table->align[$key] = null;
1899 if (!empty($table->size)) {
1900 foreach ($table->size as $key => $ss) {
1901 if ($ss) {
1902 $table->size[$key] = 'width:'. $ss .';';
1903 } else {
1904 $table->size[$key] = null;
1908 if (!empty($table->wrap)) {
1909 foreach ($table->wrap as $key => $ww) {
1910 if ($ww) {
1911 $table->wrap[$key] = 'white-space:nowrap;';
1912 } else {
1913 $table->wrap[$key] = '';
1917 if (!empty($table->head)) {
1918 foreach ($table->head as $key => $val) {
1919 if (!isset($table->align[$key])) {
1920 $table->align[$key] = null;
1922 if (!isset($table->size[$key])) {
1923 $table->size[$key] = null;
1925 if (!isset($table->wrap[$key])) {
1926 $table->wrap[$key] = null;
1931 if (empty($table->attributes['class'])) {
1932 $table->attributes['class'] = 'generaltable';
1934 if (!empty($table->tablealign)) {
1935 $table->attributes['class'] .= ' boxalign' . $table->tablealign;
1938 // explicitly assigned properties override those defined via $table->attributes
1939 $table->attributes['class'] = trim($table->attributes['class']);
1940 $attributes = array_merge($table->attributes, array(
1941 'id' => $table->id,
1942 'width' => $table->width,
1943 'summary' => $table->summary,
1944 'cellpadding' => $table->cellpadding,
1945 'cellspacing' => $table->cellspacing,
1947 $output = html_writer::start_tag('table', $attributes) . "\n";
1949 $countcols = 0;
1951 // Output a caption if present.
1952 if (!empty($table->caption)) {
1953 $captionattributes = array();
1954 if ($table->captionhide) {
1955 $captionattributes['class'] = 'accesshide';
1957 $output .= html_writer::tag(
1958 'caption',
1959 $table->caption,
1960 $captionattributes
1964 if (!empty($table->head)) {
1965 $countcols = count($table->head);
1967 $output .= html_writer::start_tag('thead', array()) . "\n";
1968 $output .= html_writer::start_tag('tr', array()) . "\n";
1969 $keys = array_keys($table->head);
1970 $lastkey = end($keys);
1972 foreach ($table->head as $key => $heading) {
1973 // Convert plain string headings into html_table_cell objects
1974 if (!($heading instanceof html_table_cell)) {
1975 $headingtext = $heading;
1976 $heading = new html_table_cell();
1977 $heading->text = $headingtext;
1978 $heading->header = true;
1981 if ($heading->header !== false) {
1982 $heading->header = true;
1985 if ($heading->header && empty($heading->scope)) {
1986 $heading->scope = 'col';
1989 $heading->attributes['class'] .= ' header c' . $key;
1990 if (isset($table->headspan[$key]) && $table->headspan[$key] > 1) {
1991 $heading->colspan = $table->headspan[$key];
1992 $countcols += $table->headspan[$key] - 1;
1995 if ($key == $lastkey) {
1996 $heading->attributes['class'] .= ' lastcol';
1998 if (isset($table->colclasses[$key])) {
1999 $heading->attributes['class'] .= ' ' . $table->colclasses[$key];
2001 $heading->attributes['class'] = trim($heading->attributes['class']);
2002 $attributes = array_merge($heading->attributes, array(
2003 'style' => $table->align[$key] . $table->size[$key] . $heading->style,
2004 'scope' => $heading->scope,
2005 'colspan' => $heading->colspan,
2008 $tagtype = 'td';
2009 if ($heading->header === true) {
2010 $tagtype = 'th';
2012 $output .= html_writer::tag($tagtype, $heading->text, $attributes) . "\n";
2014 $output .= html_writer::end_tag('tr') . "\n";
2015 $output .= html_writer::end_tag('thead') . "\n";
2017 if (empty($table->data)) {
2018 // For valid XHTML strict every table must contain either a valid tr
2019 // or a valid tbody... both of which must contain a valid td
2020 $output .= html_writer::start_tag('tbody', array('class' => 'empty'));
2021 $output .= html_writer::tag('tr', html_writer::tag('td', '', array('colspan'=>count($table->head))));
2022 $output .= html_writer::end_tag('tbody');
2026 if (!empty($table->data)) {
2027 $keys = array_keys($table->data);
2028 $lastrowkey = end($keys);
2029 $output .= html_writer::start_tag('tbody', array());
2031 foreach ($table->data as $key => $row) {
2032 if (($row === 'hr') && ($countcols)) {
2033 $output .= html_writer::tag('td', html_writer::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
2034 } else {
2035 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
2036 if (!($row instanceof html_table_row)) {
2037 $newrow = new html_table_row();
2039 foreach ($row as $cell) {
2040 if (!($cell instanceof html_table_cell)) {
2041 $cell = new html_table_cell($cell);
2043 $newrow->cells[] = $cell;
2045 $row = $newrow;
2048 if (isset($table->rowclasses[$key])) {
2049 $row->attributes['class'] .= ' ' . $table->rowclasses[$key];
2052 if ($key == $lastrowkey) {
2053 $row->attributes['class'] .= ' lastrow';
2056 // Explicitly assigned properties should override those defined in the attributes.
2057 $row->attributes['class'] = trim($row->attributes['class']);
2058 $trattributes = array_merge($row->attributes, array(
2059 'id' => $row->id,
2060 'style' => $row->style,
2062 $output .= html_writer::start_tag('tr', $trattributes) . "\n";
2063 $keys2 = array_keys($row->cells);
2064 $lastkey = end($keys2);
2066 $gotlastkey = false; //flag for sanity checking
2067 foreach ($row->cells as $key => $cell) {
2068 if ($gotlastkey) {
2069 //This should never happen. Why do we have a cell after the last cell?
2070 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
2073 if (!($cell instanceof html_table_cell)) {
2074 $mycell = new html_table_cell();
2075 $mycell->text = $cell;
2076 $cell = $mycell;
2079 if (($cell->header === true) && empty($cell->scope)) {
2080 $cell->scope = 'row';
2083 if (isset($table->colclasses[$key])) {
2084 $cell->attributes['class'] .= ' ' . $table->colclasses[$key];
2087 $cell->attributes['class'] .= ' cell c' . $key;
2088 if ($key == $lastkey) {
2089 $cell->attributes['class'] .= ' lastcol';
2090 $gotlastkey = true;
2092 $tdstyle = '';
2093 $tdstyle .= isset($table->align[$key]) ? $table->align[$key] : '';
2094 $tdstyle .= isset($table->size[$key]) ? $table->size[$key] : '';
2095 $tdstyle .= isset($table->wrap[$key]) ? $table->wrap[$key] : '';
2096 $cell->attributes['class'] = trim($cell->attributes['class']);
2097 $tdattributes = array_merge($cell->attributes, array(
2098 'style' => $tdstyle . $cell->style,
2099 'colspan' => $cell->colspan,
2100 'rowspan' => $cell->rowspan,
2101 'id' => $cell->id,
2102 'abbr' => $cell->abbr,
2103 'scope' => $cell->scope,
2105 $tagtype = 'td';
2106 if ($cell->header === true) {
2107 $tagtype = 'th';
2109 $output .= html_writer::tag($tagtype, $cell->text, $tdattributes) . "\n";
2112 $output .= html_writer::end_tag('tr') . "\n";
2114 $output .= html_writer::end_tag('tbody') . "\n";
2116 $output .= html_writer::end_tag('table') . "\n";
2118 return $output;
2122 * Renders form element label
2124 * By default, the label is suffixed with a label separator defined in the
2125 * current language pack (colon by default in the English lang pack).
2126 * Adding the colon can be explicitly disabled if needed. Label separators
2127 * are put outside the label tag itself so they are not read by
2128 * screenreaders (accessibility).
2130 * Parameter $for explicitly associates the label with a form control. When
2131 * set, the value of this attribute must be the same as the value of
2132 * the id attribute of the form control in the same document. When null,
2133 * the label being defined is associated with the control inside the label
2134 * element.
2136 * @param string $text content of the label tag
2137 * @param string|null $for id of the element this label is associated with, null for no association
2138 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
2139 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
2140 * @return string HTML of the label element
2142 public static function label($text, $for, $colonize = true, array $attributes=array()) {
2143 if (!is_null($for)) {
2144 $attributes = array_merge($attributes, array('for' => $for));
2146 $text = trim($text);
2147 $label = self::tag('label', $text, $attributes);
2149 // TODO MDL-12192 $colonize disabled for now yet
2150 // if (!empty($text) and $colonize) {
2151 // // the $text may end with the colon already, though it is bad string definition style
2152 // $colon = get_string('labelsep', 'langconfig');
2153 // if (!empty($colon)) {
2154 // $trimmed = trim($colon);
2155 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
2156 // //debugging('The label text should not end with colon or other label separator,
2157 // // please fix the string definition.', DEBUG_DEVELOPER);
2158 // } else {
2159 // $label .= $colon;
2160 // }
2161 // }
2162 // }
2164 return $label;
2168 * Combines a class parameter with other attributes. Aids in code reduction
2169 * because the class parameter is very frequently used.
2171 * If the class attribute is specified both in the attributes and in the
2172 * class parameter, the two values are combined with a space between.
2174 * @param string $class Optional CSS class (or classes as space-separated list)
2175 * @param array $attributes Optional other attributes as array
2176 * @return array Attributes (or null if still none)
2178 private static function add_class($class = '', array $attributes = null) {
2179 if ($class !== '') {
2180 $classattribute = array('class' => $class);
2181 if ($attributes) {
2182 if (array_key_exists('class', $attributes)) {
2183 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
2184 } else {
2185 $attributes = $classattribute + $attributes;
2187 } else {
2188 $attributes = $classattribute;
2191 return $attributes;
2195 * Creates a <div> tag. (Shortcut function.)
2197 * @param string $content HTML content of tag
2198 * @param string $class Optional CSS class (or classes as space-separated list)
2199 * @param array $attributes Optional other attributes as array
2200 * @return string HTML code for div
2202 public static function div($content, $class = '', array $attributes = null) {
2203 return self::tag('div', $content, self::add_class($class, $attributes));
2207 * Starts a <div> tag. (Shortcut function.)
2209 * @param string $class Optional CSS class (or classes as space-separated list)
2210 * @param array $attributes Optional other attributes as array
2211 * @return string HTML code for open div tag
2213 public static function start_div($class = '', array $attributes = null) {
2214 return self::start_tag('div', self::add_class($class, $attributes));
2218 * Ends a <div> tag. (Shortcut function.)
2220 * @return string HTML code for close div tag
2222 public static function end_div() {
2223 return self::end_tag('div');
2227 * Creates a <span> tag. (Shortcut function.)
2229 * @param string $content HTML content of tag
2230 * @param string $class Optional CSS class (or classes as space-separated list)
2231 * @param array $attributes Optional other attributes as array
2232 * @return string HTML code for span
2234 public static function span($content, $class = '', array $attributes = null) {
2235 return self::tag('span', $content, self::add_class($class, $attributes));
2239 * Starts a <span> tag. (Shortcut function.)
2241 * @param string $class Optional CSS class (or classes as space-separated list)
2242 * @param array $attributes Optional other attributes as array
2243 * @return string HTML code for open span tag
2245 public static function start_span($class = '', array $attributes = null) {
2246 return self::start_tag('span', self::add_class($class, $attributes));
2250 * Ends a <span> tag. (Shortcut function.)
2252 * @return string HTML code for close span tag
2254 public static function end_span() {
2255 return self::end_tag('span');
2260 * Simple javascript output class
2262 * @copyright 2010 Petr Skoda
2263 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2264 * @since Moodle 2.0
2265 * @package core
2266 * @category output
2268 class js_writer {
2271 * Returns javascript code calling the function
2273 * @param string $function function name, can be complex like Y.Event.purgeElement
2274 * @param array $arguments parameters
2275 * @param int $delay execution delay in seconds
2276 * @return string JS code fragment
2278 public static function function_call($function, array $arguments = null, $delay=0) {
2279 if ($arguments) {
2280 $arguments = array_map('json_encode', convert_to_array($arguments));
2281 $arguments = implode(', ', $arguments);
2282 } else {
2283 $arguments = '';
2285 $js = "$function($arguments);";
2287 if ($delay) {
2288 $delay = $delay * 1000; // in miliseconds
2289 $js = "setTimeout(function() { $js }, $delay);";
2291 return $js . "\n";
2295 * Special function which adds Y as first argument of function call.
2297 * @param string $function The function to call
2298 * @param array $extraarguments Any arguments to pass to it
2299 * @return string Some JS code
2301 public static function function_call_with_Y($function, array $extraarguments = null) {
2302 if ($extraarguments) {
2303 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
2304 $arguments = 'Y, ' . implode(', ', $extraarguments);
2305 } else {
2306 $arguments = 'Y';
2308 return "$function($arguments);\n";
2312 * Returns JavaScript code to initialise a new object
2314 * @param string $var If it is null then no var is assigned the new object.
2315 * @param string $class The class to initialise an object for.
2316 * @param array $arguments An array of args to pass to the init method.
2317 * @param array $requirements Any modules required for this class.
2318 * @param int $delay The delay before initialisation. 0 = no delay.
2319 * @return string Some JS code
2321 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
2322 if (is_array($arguments)) {
2323 $arguments = array_map('json_encode', convert_to_array($arguments));
2324 $arguments = implode(', ', $arguments);
2327 if ($var === null) {
2328 $js = "new $class(Y, $arguments);";
2329 } else if (strpos($var, '.')!==false) {
2330 $js = "$var = new $class(Y, $arguments);";
2331 } else {
2332 $js = "var $var = new $class(Y, $arguments);";
2335 if ($delay) {
2336 $delay = $delay * 1000; // in miliseconds
2337 $js = "setTimeout(function() { $js }, $delay);";
2340 if (count($requirements) > 0) {
2341 $requirements = implode("', '", $requirements);
2342 $js = "Y.use('$requirements', function(Y){ $js });";
2344 return $js."\n";
2348 * Returns code setting value to variable
2350 * @param string $name
2351 * @param mixed $value json serialised value
2352 * @param bool $usevar add var definition, ignored for nested properties
2353 * @return string JS code fragment
2355 public static function set_variable($name, $value, $usevar = true) {
2356 $output = '';
2358 if ($usevar) {
2359 if (strpos($name, '.')) {
2360 $output .= '';
2361 } else {
2362 $output .= 'var ';
2366 $output .= "$name = ".json_encode($value).";";
2368 return $output;
2372 * Writes event handler attaching code
2374 * @param array|string $selector standard YUI selector for elements, may be
2375 * array or string, element id is in the form "#idvalue"
2376 * @param string $event A valid DOM event (click, mousedown, change etc.)
2377 * @param string $function The name of the function to call
2378 * @param array $arguments An optional array of argument parameters to pass to the function
2379 * @return string JS code fragment
2381 public static function event_handler($selector, $event, $function, array $arguments = null) {
2382 $selector = json_encode($selector);
2383 $output = "Y.on('$event', $function, $selector, null";
2384 if (!empty($arguments)) {
2385 $output .= ', ' . json_encode($arguments);
2387 return $output . ");\n";
2392 * Holds all the information required to render a <table> by {@link core_renderer::table()}
2394 * Example of usage:
2395 * $t = new html_table();
2396 * ... // set various properties of the object $t as described below
2397 * echo html_writer::table($t);
2399 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
2400 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2401 * @since Moodle 2.0
2402 * @package core
2403 * @category output
2405 class html_table {
2408 * @var string Value to use for the id attribute of the table
2410 public $id = null;
2413 * @var array Attributes of HTML attributes for the <table> element
2415 public $attributes = array();
2418 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
2419 * For more control over the rendering of the headers, an array of html_table_cell objects
2420 * can be passed instead of an array of strings.
2422 * Example of usage:
2423 * $t->head = array('Student', 'Grade');
2425 public $head;
2428 * @var array An array that can be used to make a heading span multiple columns.
2429 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
2430 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
2432 * Example of usage:
2433 * $t->headspan = array(2,1);
2435 public $headspan;
2438 * @var array An array of column alignments.
2439 * The value is used as CSS 'text-align' property. Therefore, possible
2440 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
2441 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
2443 * Examples of usage:
2444 * $t->align = array(null, 'right');
2445 * or
2446 * $t->align[1] = 'right';
2448 public $align;
2451 * @var array The value is used as CSS 'size' property.
2453 * Examples of usage:
2454 * $t->size = array('50%', '50%');
2455 * or
2456 * $t->size[1] = '120px';
2458 public $size;
2461 * @var array An array of wrapping information.
2462 * The only possible value is 'nowrap' that sets the
2463 * CSS property 'white-space' to the value 'nowrap' in the given column.
2465 * Example of usage:
2466 * $t->wrap = array(null, 'nowrap');
2468 public $wrap;
2471 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2472 * $head specified, the string 'hr' (for horizontal ruler) can be used
2473 * instead of an array of cells data resulting in a divider rendered.
2475 * Example of usage with array of arrays:
2476 * $row1 = array('Harry Potter', '76 %');
2477 * $row2 = array('Hermione Granger', '100 %');
2478 * $t->data = array($row1, $row2);
2480 * Example with array of html_table_row objects: (used for more fine-grained control)
2481 * $cell1 = new html_table_cell();
2482 * $cell1->text = 'Harry Potter';
2483 * $cell1->colspan = 2;
2484 * $row1 = new html_table_row();
2485 * $row1->cells[] = $cell1;
2486 * $cell2 = new html_table_cell();
2487 * $cell2->text = 'Hermione Granger';
2488 * $cell3 = new html_table_cell();
2489 * $cell3->text = '100 %';
2490 * $row2 = new html_table_row();
2491 * $row2->cells = array($cell2, $cell3);
2492 * $t->data = array($row1, $row2);
2494 public $data;
2497 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2498 * @var string Width of the table, percentage of the page preferred.
2500 public $width = null;
2503 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2504 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2506 public $tablealign = null;
2509 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2510 * @var int Padding on each cell, in pixels
2512 public $cellpadding = null;
2515 * @var int Spacing between cells, in pixels
2516 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2518 public $cellspacing = null;
2521 * @var array Array of classes to add to particular rows, space-separated string.
2522 * Class 'lastrow' is added automatically for the last row in the table.
2524 * Example of usage:
2525 * $t->rowclasses[9] = 'tenth'
2527 public $rowclasses;
2530 * @var array An array of classes to add to every cell in a particular column,
2531 * space-separated string. Class 'cell' is added automatically by the renderer.
2532 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2533 * respectively. Class 'lastcol' is added automatically for all last cells
2534 * in a row.
2536 * Example of usage:
2537 * $t->colclasses = array(null, 'grade');
2539 public $colclasses;
2542 * @var string Description of the contents for screen readers.
2544 public $summary;
2547 * @var string Caption for the table, typically a title.
2549 * Example of usage:
2550 * $t->caption = "TV Guide";
2552 public $caption;
2555 * @var bool Whether to hide the table's caption from sighted users.
2557 * Example of usage:
2558 * $t->caption = "TV Guide";
2559 * $t->captionhide = true;
2561 public $captionhide = false;
2564 * Constructor
2566 public function __construct() {
2567 $this->attributes['class'] = '';
2572 * Component representing a table row.
2574 * @copyright 2009 Nicolas Connault
2575 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2576 * @since Moodle 2.0
2577 * @package core
2578 * @category output
2580 class html_table_row {
2583 * @var string Value to use for the id attribute of the row.
2585 public $id = null;
2588 * @var array Array of html_table_cell objects
2590 public $cells = array();
2593 * @var string Value to use for the style attribute of the table row
2595 public $style = null;
2598 * @var array Attributes of additional HTML attributes for the <tr> element
2600 public $attributes = array();
2603 * Constructor
2604 * @param array $cells
2606 public function __construct(array $cells=null) {
2607 $this->attributes['class'] = '';
2608 $cells = (array)$cells;
2609 foreach ($cells as $cell) {
2610 if ($cell instanceof html_table_cell) {
2611 $this->cells[] = $cell;
2612 } else {
2613 $this->cells[] = new html_table_cell($cell);
2620 * Component representing a table cell.
2622 * @copyright 2009 Nicolas Connault
2623 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2624 * @since Moodle 2.0
2625 * @package core
2626 * @category output
2628 class html_table_cell {
2631 * @var string Value to use for the id attribute of the cell.
2633 public $id = null;
2636 * @var string The contents of the cell.
2638 public $text;
2641 * @var string Abbreviated version of the contents of the cell.
2643 public $abbr = null;
2646 * @var int Number of columns this cell should span.
2648 public $colspan = null;
2651 * @var int Number of rows this cell should span.
2653 public $rowspan = null;
2656 * @var string Defines a way to associate header cells and data cells in a table.
2658 public $scope = null;
2661 * @var bool Whether or not this cell is a header cell.
2663 public $header = null;
2666 * @var string Value to use for the style attribute of the table cell
2668 public $style = null;
2671 * @var array Attributes of additional HTML attributes for the <td> element
2673 public $attributes = array();
2676 * Constructs a table cell
2678 * @param string $text
2680 public function __construct($text = null) {
2681 $this->text = $text;
2682 $this->attributes['class'] = '';
2687 * Component representing a paging bar.
2689 * @copyright 2009 Nicolas Connault
2690 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2691 * @since Moodle 2.0
2692 * @package core
2693 * @category output
2695 class paging_bar implements renderable, templatable {
2698 * @var int The maximum number of pagelinks to display.
2700 public $maxdisplay = 18;
2703 * @var int The total number of entries to be pages through..
2705 public $totalcount;
2708 * @var int The page you are currently viewing.
2710 public $page;
2713 * @var int The number of entries that should be shown per page.
2715 public $perpage;
2718 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2719 * an equals sign and the page number.
2720 * If this is a moodle_url object then the pagevar param will be replaced by
2721 * the page no, for each page.
2723 public $baseurl;
2726 * @var string This is the variable name that you use for the pagenumber in your
2727 * code (ie. 'tablepage', 'blogpage', etc)
2729 public $pagevar;
2732 * @var string A HTML link representing the "previous" page.
2734 public $previouslink = null;
2737 * @var string A HTML link representing the "next" page.
2739 public $nextlink = null;
2742 * @var string A HTML link representing the first page.
2744 public $firstlink = null;
2747 * @var string A HTML link representing the last page.
2749 public $lastlink = null;
2752 * @var array An array of strings. One of them is just a string: the current page
2754 public $pagelinks = array();
2757 * Constructor paging_bar with only the required params.
2759 * @param int $totalcount The total number of entries available to be paged through
2760 * @param int $page The page you are currently viewing
2761 * @param int $perpage The number of entries that should be shown per page
2762 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2763 * @param string $pagevar name of page parameter that holds the page number
2765 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2766 $this->totalcount = $totalcount;
2767 $this->page = $page;
2768 $this->perpage = $perpage;
2769 $this->baseurl = $baseurl;
2770 $this->pagevar = $pagevar;
2774 * Prepares the paging bar for output.
2776 * This method validates the arguments set up for the paging bar and then
2777 * produces fragments of HTML to assist display later on.
2779 * @param renderer_base $output
2780 * @param moodle_page $page
2781 * @param string $target
2782 * @throws coding_exception
2784 public function prepare(renderer_base $output, moodle_page $page, $target) {
2785 if (!isset($this->totalcount) || is_null($this->totalcount)) {
2786 throw new coding_exception('paging_bar requires a totalcount value.');
2788 if (!isset($this->page) || is_null($this->page)) {
2789 throw new coding_exception('paging_bar requires a page value.');
2791 if (empty($this->perpage)) {
2792 throw new coding_exception('paging_bar requires a perpage value.');
2794 if (empty($this->baseurl)) {
2795 throw new coding_exception('paging_bar requires a baseurl value.');
2798 if ($this->totalcount > $this->perpage) {
2799 $pagenum = $this->page - 1;
2801 if ($this->page > 0) {
2802 $this->previouslink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('previous'), array('class'=>'previous'));
2805 if ($this->perpage > 0) {
2806 $lastpage = ceil($this->totalcount / $this->perpage);
2807 } else {
2808 $lastpage = 1;
2811 if ($this->page > round(($this->maxdisplay/3)*2)) {
2812 $currpage = $this->page - round($this->maxdisplay/3);
2814 $this->firstlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>0)), '1', array('class'=>'first'));
2815 } else {
2816 $currpage = 0;
2819 $displaycount = $displaypage = 0;
2821 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2822 $displaypage = $currpage + 1;
2824 if ($this->page == $currpage) {
2825 $this->pagelinks[] = html_writer::span($displaypage, 'current-page');
2826 } else {
2827 $pagelink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$currpage)), $displaypage);
2828 $this->pagelinks[] = $pagelink;
2831 $displaycount++;
2832 $currpage++;
2835 if ($currpage < $lastpage) {
2836 $lastpageactual = $lastpage - 1;
2837 $this->lastlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$lastpageactual)), $lastpage, array('class'=>'last'));
2840 $pagenum = $this->page + 1;
2842 if ($pagenum != $lastpage) {
2843 $this->nextlink = html_writer::link(new moodle_url($this->baseurl, array($this->pagevar=>$pagenum)), get_string('next'), array('class'=>'next'));
2849 * Export for template.
2851 * @param renderer_base $output The renderer.
2852 * @return stdClass
2854 public function export_for_template(renderer_base $output) {
2855 $data = new stdClass();
2856 $data->previous = null;
2857 $data->next = null;
2858 $data->first = null;
2859 $data->last = null;
2860 $data->label = get_string('page');
2861 $data->pages = [];
2862 $data->haspages = $this->totalcount > $this->perpage;
2864 if (!$data->haspages) {
2865 return $data;
2868 if ($this->page > 0) {
2869 $data->previous = [
2870 'page' => $this->page - 1,
2871 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page - 1]))->out(false)
2875 $currpage = 0;
2876 if ($this->page > round(($this->maxdisplay / 3) * 2)) {
2877 $currpage = $this->page - round($this->maxdisplay / 3);
2878 $data->first = [
2879 'page' => 1,
2880 'url' => (new moodle_url($this->baseurl, [$this->pagevar => 0]))->out(false)
2884 $lastpage = 1;
2885 if ($this->perpage > 0) {
2886 $lastpage = ceil($this->totalcount / $this->perpage);
2889 $displaycount = 0;
2890 $displaypage = 0;
2891 while ($displaycount < $this->maxdisplay and $currpage < $lastpage) {
2892 $displaypage = $currpage + 1;
2894 $iscurrent = $this->page == $currpage;
2895 $link = new moodle_url($this->baseurl, [$this->pagevar => $currpage]);
2897 $data->pages[] = [
2898 'page' => $displaypage,
2899 'active' => $iscurrent,
2900 'url' => $iscurrent ? null : $link->out(false)
2903 $displaycount++;
2904 $currpage++;
2907 if ($currpage < $lastpage) {
2908 $data->last = [
2909 'page' => $lastpage,
2910 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $lastpage - 1]))->out(false)
2914 if ($this->page + 1 != $lastpage) {
2915 $data->next = [
2916 'page' => $this->page + 1,
2917 'url' => (new moodle_url($this->baseurl, [$this->pagevar => $this->page + 1]))->out(false)
2921 return $data;
2926 * This class represents how a block appears on a page.
2928 * During output, each block instance is asked to return a block_contents object,
2929 * those are then passed to the $OUTPUT->block function for display.
2931 * contents should probably be generated using a moodle_block_..._renderer.
2933 * Other block-like things that need to appear on the page, for example the
2934 * add new block UI, are also represented as block_contents objects.
2936 * @copyright 2009 Tim Hunt
2937 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2938 * @since Moodle 2.0
2939 * @package core
2940 * @category output
2942 class block_contents {
2944 /** Used when the block cannot be collapsed **/
2945 const NOT_HIDEABLE = 0;
2947 /** Used when the block can be collapsed but currently is not **/
2948 const VISIBLE = 1;
2950 /** Used when the block has been collapsed **/
2951 const HIDDEN = 2;
2954 * @var int Used to set $skipid.
2956 protected static $idcounter = 1;
2959 * @var int All the blocks (or things that look like blocks) printed on
2960 * a page are given a unique number that can be used to construct id="" attributes.
2961 * This is set automatically be the {@link prepare()} method.
2962 * Do not try to set it manually.
2964 public $skipid;
2967 * @var int If this is the contents of a real block, this should be set
2968 * to the block_instance.id. Otherwise this should be set to 0.
2970 public $blockinstanceid = 0;
2973 * @var int If this is a real block instance, and there is a corresponding
2974 * block_position.id for the block on this page, this should be set to that id.
2975 * Otherwise it should be 0.
2977 public $blockpositionid = 0;
2980 * @var array An array of attribute => value pairs that are put on the outer div of this
2981 * block. {@link $id} and {@link $classes} attributes should be set separately.
2983 public $attributes;
2986 * @var string The title of this block. If this came from user input, it should already
2987 * have had format_string() processing done on it. This will be output inside
2988 * <h2> tags. Please do not cause invalid XHTML.
2990 public $title = '';
2993 * @var string The label to use when the block does not, or will not have a visible title.
2994 * You should never set this as well as title... it will just be ignored.
2996 public $arialabel = '';
2999 * @var string HTML for the content
3001 public $content = '';
3004 * @var array An alternative to $content, it you want a list of things with optional icons.
3006 public $footer = '';
3009 * @var string Any small print that should appear under the block to explain
3010 * to the teacher about the block, for example 'This is a sticky block that was
3011 * added in the system context.'
3013 public $annotation = '';
3016 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
3017 * the user can toggle whether this block is visible.
3019 public $collapsible = self::NOT_HIDEABLE;
3022 * Set this to true if the block is dockable.
3023 * @var bool
3025 public $dockable = false;
3028 * @var array A (possibly empty) array of editing controls. Each element of
3029 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
3030 * $icon is the icon name. Fed to $OUTPUT->pix_url.
3032 public $controls = array();
3036 * Create new instance of block content
3037 * @param array $attributes
3039 public function __construct(array $attributes = null) {
3040 $this->skipid = self::$idcounter;
3041 self::$idcounter += 1;
3043 if ($attributes) {
3044 // standard block
3045 $this->attributes = $attributes;
3046 } else {
3047 // simple "fake" blocks used in some modules and "Add new block" block
3048 $this->attributes = array('class'=>'block');
3053 * Add html class to block
3055 * @param string $class
3057 public function add_class($class) {
3058 $this->attributes['class'] .= ' '.$class;
3064 * This class represents a target for where a block can go when it is being moved.
3066 * This needs to be rendered as a form with the given hidden from fields, and
3067 * clicking anywhere in the form should submit it. The form action should be
3068 * $PAGE->url.
3070 * @copyright 2009 Tim Hunt
3071 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3072 * @since Moodle 2.0
3073 * @package core
3074 * @category output
3076 class block_move_target {
3079 * @var moodle_url Move url
3081 public $url;
3084 * Constructor
3085 * @param moodle_url $url
3087 public function __construct(moodle_url $url) {
3088 $this->url = $url;
3093 * Custom menu item
3095 * This class is used to represent one item within a custom menu that may or may
3096 * not have children.
3098 * @copyright 2010 Sam Hemelryk
3099 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3100 * @since Moodle 2.0
3101 * @package core
3102 * @category output
3104 class custom_menu_item implements renderable, templatable {
3107 * @var string The text to show for the item
3109 protected $text;
3112 * @var moodle_url The link to give the icon if it has no children
3114 protected $url;
3117 * @var string A title to apply to the item. By default the text
3119 protected $title;
3122 * @var int A sort order for the item, not necessary if you order things in
3123 * the CFG var.
3125 protected $sort;
3128 * @var custom_menu_item A reference to the parent for this item or NULL if
3129 * it is a top level item
3131 protected $parent;
3134 * @var array A array in which to store children this item has.
3136 protected $children = array();
3139 * @var int A reference to the sort var of the last child that was added
3141 protected $lastsort = 0;
3144 * Constructs the new custom menu item
3146 * @param string $text
3147 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
3148 * @param string $title A title to apply to this item [Optional]
3149 * @param int $sort A sort or to use if we need to sort differently [Optional]
3150 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
3151 * belongs to, only if the child has a parent. [Optional]
3153 public function __construct($text, moodle_url $url=null, $title=null, $sort = null, custom_menu_item $parent = null) {
3154 $this->text = $text;
3155 $this->url = $url;
3156 $this->title = $title;
3157 $this->sort = (int)$sort;
3158 $this->parent = $parent;
3162 * Adds a custom menu item as a child of this node given its properties.
3164 * @param string $text
3165 * @param moodle_url $url
3166 * @param string $title
3167 * @param int $sort
3168 * @return custom_menu_item
3170 public function add($text, moodle_url $url = null, $title = null, $sort = null) {
3171 $key = count($this->children);
3172 if (empty($sort)) {
3173 $sort = $this->lastsort + 1;
3175 $this->children[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
3176 $this->lastsort = (int)$sort;
3177 return $this->children[$key];
3181 * Removes a custom menu item that is a child or descendant to the current menu.
3183 * Returns true if child was found and removed.
3185 * @param custom_menu_item $menuitem
3186 * @return bool
3188 public function remove_child(custom_menu_item $menuitem) {
3189 $removed = false;
3190 if (($key = array_search($menuitem, $this->children)) !== false) {
3191 unset($this->children[$key]);
3192 $this->children = array_values($this->children);
3193 $removed = true;
3194 } else {
3195 foreach ($this->children as $child) {
3196 if ($removed = $child->remove_child($menuitem)) {
3197 break;
3201 return $removed;
3205 * Returns the text for this item
3206 * @return string
3208 public function get_text() {
3209 return $this->text;
3213 * Returns the url for this item
3214 * @return moodle_url
3216 public function get_url() {
3217 return $this->url;
3221 * Returns the title for this item
3222 * @return string
3224 public function get_title() {
3225 return $this->title;
3229 * Sorts and returns the children for this item
3230 * @return array
3232 public function get_children() {
3233 $this->sort();
3234 return $this->children;
3238 * Gets the sort order for this child
3239 * @return int
3241 public function get_sort_order() {
3242 return $this->sort;
3246 * Gets the parent this child belong to
3247 * @return custom_menu_item
3249 public function get_parent() {
3250 return $this->parent;
3254 * Sorts the children this item has
3256 public function sort() {
3257 usort($this->children, array('custom_menu','sort_custom_menu_items'));
3261 * Returns true if this item has any children
3262 * @return bool
3264 public function has_children() {
3265 return (count($this->children) > 0);
3269 * Sets the text for the node
3270 * @param string $text
3272 public function set_text($text) {
3273 $this->text = (string)$text;
3277 * Sets the title for the node
3278 * @param string $title
3280 public function set_title($title) {
3281 $this->title = (string)$title;
3285 * Sets the url for the node
3286 * @param moodle_url $url
3288 public function set_url(moodle_url $url) {
3289 $this->url = $url;
3293 * Export this data so it can be used as the context for a mustache template.
3295 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
3296 * @return array
3298 public function export_for_template(renderer_base $output) {
3299 global $CFG;
3301 require_once($CFG->libdir . '/externallib.php');
3303 $syscontext = context_system::instance();
3305 $context = new stdClass();
3306 $context->text = external_format_string($this->text, $syscontext->id);
3307 $context->url = $this->url ? $this->url->out() : null;
3308 $context->title = external_format_string($this->title, $syscontext->id);
3309 $context->sort = $this->sort;
3310 $context->children = array();
3311 if (preg_match("/^#+$/", $this->text)) {
3312 $context->divider = true;
3314 $context->haschildren = !empty($this->children) && (count($this->children) > 0);
3315 foreach ($this->children as $child) {
3316 $child = $child->export_for_template($output);
3317 array_push($context->children, $child);
3320 return $context;
3325 * Custom menu class
3327 * This class is used to operate a custom menu that can be rendered for the page.
3328 * The custom menu is built using $CFG->custommenuitems and is a structured collection
3329 * of custom_menu_item nodes that can be rendered by the core renderer.
3331 * To configure the custom menu:
3332 * Settings: Administration > Appearance > Themes > Theme settings
3334 * @copyright 2010 Sam Hemelryk
3335 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3336 * @since Moodle 2.0
3337 * @package core
3338 * @category output
3340 class custom_menu extends custom_menu_item {
3343 * @var string The language we should render for, null disables multilang support.
3345 protected $currentlanguage = null;
3348 * Creates the custom menu
3350 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
3351 * @param string $currentlanguage the current language code, null disables multilang support
3353 public function __construct($definition = '', $currentlanguage = null) {
3354 $this->currentlanguage = $currentlanguage;
3355 parent::__construct('root'); // create virtual root element of the menu
3356 if (!empty($definition)) {
3357 $this->override_children(self::convert_text_to_menu_nodes($definition, $currentlanguage));
3362 * Overrides the children of this custom menu. Useful when getting children
3363 * from $CFG->custommenuitems
3365 * @param array $children
3367 public function override_children(array $children) {
3368 $this->children = array();
3369 foreach ($children as $child) {
3370 if ($child instanceof custom_menu_item) {
3371 $this->children[] = $child;
3377 * Converts a string into a structured array of custom_menu_items which can
3378 * then be added to a custom menu.
3380 * Structure:
3381 * text|url|title|langs
3382 * The number of hyphens at the start determines the depth of the item. The
3383 * languages are optional, comma separated list of languages the line is for.
3385 * Example structure:
3386 * First level first item|http://www.moodle.com/
3387 * -Second level first item|http://www.moodle.com/partners/
3388 * -Second level second item|http://www.moodle.com/hq/
3389 * --Third level first item|http://www.moodle.com/jobs/
3390 * -Second level third item|http://www.moodle.com/development/
3391 * First level second item|http://www.moodle.com/feedback/
3392 * First level third item
3393 * English only|http://moodle.com|English only item|en
3394 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
3397 * @static
3398 * @param string $text the menu items definition
3399 * @param string $language the language code, null disables multilang support
3400 * @return array
3402 public static function convert_text_to_menu_nodes($text, $language = null) {
3403 $root = new custom_menu();
3404 $lastitem = $root;
3405 $lastdepth = 0;
3406 $hiddenitems = array();
3407 $lines = explode("\n", $text);
3408 foreach ($lines as $linenumber => $line) {
3409 $line = trim($line);
3410 if (strlen($line) == 0) {
3411 continue;
3413 // Parse item settings.
3414 $itemtext = null;
3415 $itemurl = null;
3416 $itemtitle = null;
3417 $itemvisible = true;
3418 $settings = explode('|', $line);
3419 foreach ($settings as $i => $setting) {
3420 $setting = trim($setting);
3421 if (!empty($setting)) {
3422 switch ($i) {
3423 case 0:
3424 $itemtext = ltrim($setting, '-');
3425 $itemtitle = $itemtext;
3426 break;
3427 case 1:
3428 try {
3429 $itemurl = new moodle_url($setting);
3430 } catch (moodle_exception $exception) {
3431 // We're not actually worried about this, we don't want to mess up the display
3432 // just for a wrongly entered URL.
3433 $itemurl = null;
3435 break;
3436 case 2:
3437 $itemtitle = $setting;
3438 break;
3439 case 3:
3440 if (!empty($language)) {
3441 $itemlanguages = array_map('trim', explode(',', $setting));
3442 $itemvisible &= in_array($language, $itemlanguages);
3444 break;
3448 // Get depth of new item.
3449 preg_match('/^(\-*)/', $line, $match);
3450 $itemdepth = strlen($match[1]) + 1;
3451 // Find parent item for new item.
3452 while (($lastdepth - $itemdepth) >= 0) {
3453 $lastitem = $lastitem->get_parent();
3454 $lastdepth--;
3456 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber + 1);
3457 $lastdepth++;
3458 if (!$itemvisible) {
3459 $hiddenitems[] = $lastitem;
3462 foreach ($hiddenitems as $item) {
3463 $item->parent->remove_child($item);
3465 return $root->get_children();
3469 * Sorts two custom menu items
3471 * This function is designed to be used with the usort method
3472 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
3474 * @static
3475 * @param custom_menu_item $itema
3476 * @param custom_menu_item $itemb
3477 * @return int
3479 public static function sort_custom_menu_items(custom_menu_item $itema, custom_menu_item $itemb) {
3480 $itema = $itema->get_sort_order();
3481 $itemb = $itemb->get_sort_order();
3482 if ($itema == $itemb) {
3483 return 0;
3485 return ($itema > $itemb) ? +1 : -1;
3490 * Stores one tab
3492 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3493 * @package core
3495 class tabobject implements renderable, templatable {
3496 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
3497 var $id;
3498 /** @var moodle_url|string link */
3499 var $link;
3500 /** @var string text on the tab */
3501 var $text;
3502 /** @var string title under the link, by defaul equals to text */
3503 var $title;
3504 /** @var bool whether to display a link under the tab name when it's selected */
3505 var $linkedwhenselected = false;
3506 /** @var bool whether the tab is inactive */
3507 var $inactive = false;
3508 /** @var bool indicates that this tab's child is selected */
3509 var $activated = false;
3510 /** @var bool indicates that this tab is selected */
3511 var $selected = false;
3512 /** @var array stores children tabobjects */
3513 var $subtree = array();
3514 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
3515 var $level = 1;
3518 * Constructor
3520 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
3521 * @param string|moodle_url $link
3522 * @param string $text text on the tab
3523 * @param string $title title under the link, by defaul equals to text
3524 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
3526 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
3527 $this->id = $id;
3528 $this->link = $link;
3529 $this->text = $text;
3530 $this->title = $title ? $title : $text;
3531 $this->linkedwhenselected = $linkedwhenselected;
3535 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
3537 * @param string $selected the id of the selected tab (whatever row it's on),
3538 * if null marks all tabs as unselected
3539 * @return bool whether this tab is selected or contains selected tab in its subtree
3541 protected function set_selected($selected) {
3542 if ((string)$selected === (string)$this->id) {
3543 $this->selected = true;
3544 // This tab is selected. No need to travel through subtree.
3545 return true;
3547 foreach ($this->subtree as $subitem) {
3548 if ($subitem->set_selected($selected)) {
3549 // This tab has child that is selected. Mark it as activated. No need to check other children.
3550 $this->activated = true;
3551 return true;
3554 return false;
3558 * Travels through tree and finds a tab with specified id
3560 * @param string $id
3561 * @return tabtree|null
3563 public function find($id) {
3564 if ((string)$this->id === (string)$id) {
3565 return $this;
3567 foreach ($this->subtree as $tab) {
3568 if ($obj = $tab->find($id)) {
3569 return $obj;
3572 return null;
3576 * Allows to mark each tab's level in the tree before rendering.
3578 * @param int $level
3580 protected function set_level($level) {
3581 $this->level = $level;
3582 foreach ($this->subtree as $tab) {
3583 $tab->set_level($level + 1);
3588 * Export for template.
3590 * @param renderer_base $output Renderer.
3591 * @return object
3593 public function export_for_template(renderer_base $output) {
3594 if ($this->inactive || ($this->selected && !$this->linkedwhenselected) || $this->activated) {
3595 $link = null;
3596 } else {
3597 $link = $this->link;
3599 $active = $this->activated || $this->selected;
3601 return (object) [
3602 'id' => $this->id,
3603 'link' => is_object($link) ? $link->out(false) : $link,
3604 'text' => $this->text,
3605 'title' => $this->title,
3606 'inactive' => !$active && $this->inactive,
3607 'active' => $active,
3608 'level' => $this->level,
3615 * Renderable for the main page header.
3617 * @package core
3618 * @category output
3619 * @since 2.9
3620 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
3621 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3623 class context_header implements renderable {
3626 * @var string $heading Main heading.
3628 public $heading;
3630 * @var int $headinglevel Main heading 'h' tag level.
3632 public $headinglevel;
3634 * @var string|null $imagedata HTML code for the picture in the page header.
3636 public $imagedata;
3638 * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
3639 * array elements - title => alternate text for the image, or if no image is available the button text.
3640 * url => Link for the button to head to. Should be a moodle_url.
3641 * image => location to the image, or name of the image in /pix/t/{image name}.
3642 * linkattributes => additional attributes for the <a href> element.
3643 * page => page object. Don't include if the image is an external image.
3645 public $additionalbuttons;
3648 * Constructor.
3650 * @param string $heading Main heading data.
3651 * @param int $headinglevel Main heading 'h' tag level.
3652 * @param string|null $imagedata HTML code for the picture in the page header.
3653 * @param string $additionalbuttons Buttons for the header e.g. Messaging button for the user header.
3655 public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null) {
3657 $this->heading = $heading;
3658 $this->headinglevel = $headinglevel;
3659 $this->imagedata = $imagedata;
3660 $this->additionalbuttons = $additionalbuttons;
3661 // If we have buttons then format them.
3662 if (isset($this->additionalbuttons)) {
3663 $this->format_button_images();
3668 * Adds an array element for a formatted image.
3670 protected function format_button_images() {
3672 foreach ($this->additionalbuttons as $buttontype => $button) {
3673 $page = $button['page'];
3674 // If no image is provided then just use the title.
3675 if (!isset($button['image'])) {
3676 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['title'];
3677 } else {
3678 // Check to see if this is an internal Moodle icon.
3679 $internalimage = $page->theme->resolve_image_location('t/' . $button['image'], 'moodle');
3680 if ($internalimage) {
3681 $this->additionalbuttons[$buttontype]['formattedimage'] = 't/' . $button['image'];
3682 } else {
3683 // Treat as an external image.
3684 $this->additionalbuttons[$buttontype]['formattedimage'] = $button['image'];
3688 if (isset($button['linkattributes']['class'])) {
3689 $class = $button['linkattributes']['class'] . ' btn';
3690 } else {
3691 $class = 'btn';
3693 // Add the bootstrap 'btn' class for formatting.
3694 $this->additionalbuttons[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
3695 array('class' => $class));
3701 * Stores tabs list
3703 * Example how to print a single line tabs:
3704 * $rows = array(
3705 * new tabobject(...),
3706 * new tabobject(...)
3707 * );
3708 * echo $OUTPUT->tabtree($rows, $selectedid);
3710 * Multiple row tabs may not look good on some devices but if you want to use them
3711 * you can specify ->subtree for the active tabobject.
3713 * @copyright 2013 Marina Glancy
3714 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3715 * @since Moodle 2.5
3716 * @package core
3717 * @category output
3719 class tabtree extends tabobject {
3721 * Constuctor
3723 * It is highly recommended to call constructor when list of tabs is already
3724 * populated, this way you ensure that selected and inactive tabs are located
3725 * and attribute level is set correctly.
3727 * @param array $tabs array of tabs, each of them may have it's own ->subtree
3728 * @param string|null $selected which tab to mark as selected, all parent tabs will
3729 * automatically be marked as activated
3730 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3731 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
3733 public function __construct($tabs, $selected = null, $inactive = null) {
3734 $this->subtree = $tabs;
3735 if ($selected !== null) {
3736 $this->set_selected($selected);
3738 if ($inactive !== null) {
3739 if (is_array($inactive)) {
3740 foreach ($inactive as $id) {
3741 if ($tab = $this->find($id)) {
3742 $tab->inactive = true;
3745 } else if ($tab = $this->find($inactive)) {
3746 $tab->inactive = true;
3749 $this->set_level(0);
3753 * Export for template.
3755 * @param renderer_base $output Renderer.
3756 * @return object
3758 public function export_for_template(renderer_base $output) {
3759 $tabs = [];
3760 $secondrow = false;
3762 foreach ($this->subtree as $tab) {
3763 $tabs[] = $tab->export_for_template($output);
3764 if (!empty($tab->subtree) && ($tab->level == 0 || $tab->selected || $tab->activated)) {
3765 $secondrow = new tabtree($tab->subtree);
3769 return (object) [
3770 'tabs' => $tabs,
3771 'secondrow' => $secondrow ? $secondrow->export_for_template($output) : false
3777 * An action menu.
3779 * This action menu component takes a series of primary and secondary actions.
3780 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
3781 * down menu.
3783 * @package core
3784 * @category output
3785 * @copyright 2013 Sam Hemelryk
3786 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3788 class action_menu implements renderable, templatable {
3791 * Top right alignment.
3793 const TL = 1;
3796 * Top right alignment.
3798 const TR = 2;
3801 * Top right alignment.
3803 const BL = 3;
3806 * Top right alignment.
3808 const BR = 4;
3811 * The instance number. This is unique to this instance of the action menu.
3812 * @var int
3814 protected $instance = 0;
3817 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
3818 * @var array
3820 protected $primaryactions = array();
3823 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
3824 * @var array
3826 protected $secondaryactions = array();
3829 * An array of attributes added to the container of the action menu.
3830 * Initialised with defaults during construction.
3831 * @var array
3833 public $attributes = array();
3835 * An array of attributes added to the container of the primary actions.
3836 * Initialised with defaults during construction.
3837 * @var array
3839 public $attributesprimary = array();
3841 * An array of attributes added to the container of the secondary actions.
3842 * Initialised with defaults during construction.
3843 * @var array
3845 public $attributessecondary = array();
3848 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
3849 * @var array
3851 public $actiontext = null;
3854 * An icon to use for the toggling the secondary menu (dropdown).
3855 * @var actionicon
3857 public $actionicon;
3860 * Any text to use for the toggling the secondary menu (dropdown).
3861 * @var menutrigger
3863 public $menutrigger = '';
3866 * Place the action menu before all other actions.
3867 * @var prioritise
3869 public $prioritise = false;
3872 * Constructs the action menu with the given items.
3874 * @param array $actions An array of actions.
3876 public function __construct(array $actions = array()) {
3877 static $initialised = 0;
3878 $this->instance = $initialised;
3879 $initialised++;
3881 $this->attributes = array(
3882 'id' => 'action-menu-'.$this->instance,
3883 'class' => 'moodle-actionmenu',
3884 'data-enhance' => 'moodle-core-actionmenu'
3886 $this->attributesprimary = array(
3887 'id' => 'action-menu-'.$this->instance.'-menubar',
3888 'class' => 'menubar',
3889 'role' => 'menubar'
3891 $this->attributessecondary = array(
3892 'id' => 'action-menu-'.$this->instance.'-menu',
3893 'class' => 'menu',
3894 'data-rel' => 'menu-content',
3895 'aria-labelledby' => 'action-menu-toggle-'.$this->instance,
3896 'role' => 'menu'
3898 $this->set_alignment(self::TR, self::BR);
3899 foreach ($actions as $action) {
3900 $this->add($action);
3904 public function set_menu_trigger($trigger) {
3905 $this->menutrigger = $trigger;
3909 * Return true if there is at least one visible link in the menu.
3911 * @return bool
3913 public function is_empty() {
3914 return !count($this->primaryactions) && !count($this->secondaryactions);
3918 * Initialises JS required fore the action menu.
3919 * The JS is only required once as it manages all action menu's on the page.
3921 * @param moodle_page $page
3923 public function initialise_js(moodle_page $page) {
3924 static $initialised = false;
3925 if (!$initialised) {
3926 $page->requires->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
3927 $initialised = true;
3932 * Adds an action to this action menu.
3934 * @param action_menu_link|pix_icon|string $action
3936 public function add($action) {
3937 if ($action instanceof action_link) {
3938 if ($action->primary) {
3939 $this->add_primary_action($action);
3940 } else {
3941 $this->add_secondary_action($action);
3943 } else if ($action instanceof pix_icon) {
3944 $this->add_primary_action($action);
3945 } else {
3946 $this->add_secondary_action($action);
3951 * Adds a primary action to the action menu.
3953 * @param action_menu_link|action_link|pix_icon|string $action
3955 public function add_primary_action($action) {
3956 if ($action instanceof action_link || $action instanceof pix_icon) {
3957 $action->attributes['role'] = 'menuitem';
3958 if ($action instanceof action_menu_link) {
3959 $action->actionmenu = $this;
3962 $this->primaryactions[] = $action;
3966 * Adds a secondary action to the action menu.
3968 * @param action_link|pix_icon|string $action
3970 public function add_secondary_action($action) {
3971 if ($action instanceof action_link || $action instanceof pix_icon) {
3972 $action->attributes['role'] = 'menuitem';
3973 if ($action instanceof action_menu_link) {
3974 $action->actionmenu = $this;
3977 $this->secondaryactions[] = $action;
3981 * Returns the primary actions ready to be rendered.
3983 * @param core_renderer $output The renderer to use for getting icons.
3984 * @return array
3986 public function get_primary_actions(core_renderer $output = null) {
3987 global $OUTPUT;
3988 if ($output === null) {
3989 $output = $OUTPUT;
3991 $pixicon = $this->actionicon;
3992 $linkclasses = array('toggle-display');
3994 $title = '';
3995 if (!empty($this->menutrigger)) {
3996 $pixicon = '<b class="caret"></b>';
3997 $linkclasses[] = 'textmenu';
3998 } else {
3999 $title = new lang_string('actions', 'moodle');
4000 $this->actionicon = new pix_icon(
4001 't/edit_menu',
4003 'moodle',
4004 array('class' => 'iconsmall actionmenu', 'title' => '')
4006 $pixicon = $this->actionicon;
4008 if ($pixicon instanceof renderable) {
4009 $pixicon = $output->render($pixicon);
4010 if ($pixicon instanceof pix_icon && isset($pixicon->attributes['alt'])) {
4011 $title = $pixicon->attributes['alt'];
4014 $string = '';
4015 if ($this->actiontext) {
4016 $string = $this->actiontext;
4018 $actions = $this->primaryactions;
4019 $attributes = array(
4020 'class' => implode(' ', $linkclasses),
4021 'title' => $title,
4022 'id' => 'action-menu-toggle-'.$this->instance,
4023 'role' => 'menuitem'
4025 $link = html_writer::link('#', $string . $this->menutrigger . $pixicon, $attributes);
4026 if ($this->prioritise) {
4027 array_unshift($actions, $link);
4028 } else {
4029 $actions[] = $link;
4031 return $actions;
4035 * Returns the secondary actions ready to be rendered.
4036 * @return array
4038 public function get_secondary_actions() {
4039 return $this->secondaryactions;
4043 * Sets the selector that should be used to find the owning node of this menu.
4044 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
4046 public function set_owner_selector($selector) {
4047 $this->attributes['data-owner'] = $selector;
4051 * Sets the alignment of the dialogue in relation to button used to toggle it.
4053 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4054 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4056 public function set_alignment($dialogue, $button) {
4057 if (isset($this->attributessecondary['data-align'])) {
4058 // We've already got one set, lets remove the old class so as to avoid troubles.
4059 $class = $this->attributessecondary['class'];
4060 $search = 'align-'.$this->attributessecondary['data-align'];
4061 $this->attributessecondary['class'] = str_replace($search, '', $class);
4063 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
4064 $this->attributessecondary['data-align'] = $align;
4065 $this->attributessecondary['class'] .= ' align-'.$align;
4069 * Returns a string to describe the alignment.
4071 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4072 * @return string
4074 protected function get_align_string($align) {
4075 switch ($align) {
4076 case self::TL :
4077 return 'tl';
4078 case self::TR :
4079 return 'tr';
4080 case self::BL :
4081 return 'bl';
4082 case self::BR :
4083 return 'br';
4084 default :
4085 return 'tl';
4090 * Sets a constraint for the dialogue.
4092 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
4093 * element the constraint identifies.
4095 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
4097 public function set_constraint($ancestorselector) {
4098 $this->attributessecondary['data-constraint'] = $ancestorselector;
4102 * If you call this method the action menu will be displayed but will not be enhanced.
4104 * By not displaying the menu enhanced all items will be displayed in a single row.
4106 * @deprecated since Moodle 3.2
4108 public function do_not_enhance() {
4109 debugging('The method action_menu::do_not_enhance() is deprecated, use a list of action_icon instead.', DEBUG_DEVELOPER);
4113 * Returns true if this action menu will be enhanced.
4115 * @return bool
4117 public function will_be_enhanced() {
4118 return isset($this->attributes['data-enhance']);
4122 * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
4124 * This property can be useful when the action menu is displayed within a parent element that is either floated
4125 * or relatively positioned.
4126 * In that situation the width of the menu is determined by the width of the parent element which may not be large
4127 * enough for the menu items without them wrapping.
4128 * This disables the wrapping so that the menu takes on the width of the longest item.
4130 * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
4132 public function set_nowrap_on_items($value = true) {
4133 $class = 'nowrap-items';
4134 if (!empty($this->attributes['class'])) {
4135 $pos = strpos($this->attributes['class'], $class);
4136 if ($value === true && $pos === false) {
4137 // The value is true and the class has not been set yet. Add it.
4138 $this->attributes['class'] .= ' '.$class;
4139 } else if ($value === false && $pos !== false) {
4140 // The value is false and the class has been set. Remove it.
4141 $this->attributes['class'] = substr($this->attributes['class'], $pos, strlen($class));
4143 } else if ($value) {
4144 // The value is true and the class has not been set yet. Add it.
4145 $this->attributes['class'] = $class;
4150 * Export for template.
4152 * @param renderer_base $output The renderer.
4153 * @return stdClass
4155 public function export_for_template(renderer_base $output) {
4156 $data = new stdClass();
4157 $attributes = $this->attributes;
4158 $attributesprimary = $this->attributesprimary;
4159 $attributessecondary = $this->attributessecondary;
4161 $data->instance = $this->instance;
4163 $data->classes = isset($attributes['class']) ? $attributes['class'] : '';
4164 unset($attributes['class']);
4166 $data->attributes = array_map(function($key, $value) {
4167 return [ 'name' => $key, 'value' => $value ];
4168 }, array_keys($attributes), $attributes);
4170 $primary = new stdClass();
4171 $primary->title = '';
4172 $primary->prioritise = $this->prioritise;
4174 $primary->classes = isset($attributesprimary['class']) ? $attributesprimary['class'] : '';
4175 unset($attributesprimary['class']);
4176 $primary->attributes = array_map(function($key, $value) {
4177 return [ 'name' => $key, 'value' => $value ];
4178 }, array_keys($attributesprimary), $attributesprimary);
4180 $actionicon = $this->actionicon;
4181 if (!empty($this->menutrigger)) {
4182 $primary->menutrigger = $this->menutrigger;
4183 } else {
4184 $primary->title = get_string('actions');
4185 $actionicon = new pix_icon('t/edit_menu', '', 'moodle', ['class' => 'iconsmall actionmenu', 'title' => '']);
4188 if ($actionicon instanceof pix_icon) {
4189 $primary->icon = $actionicon->export_for_template($output);
4190 $primary->title = !empty($actionicon->attributes['alt']) ? $this->actionicon->attributes['alt'] : '';
4191 } else {
4192 $primary->iconraw = $actionicon ? $output->render($actionicon) : '';
4195 $primary->actiontext = $this->actiontext ? (string) $this->actiontext : '';
4196 $primary->items = array_map(function($item) use ($output) {
4197 $data = (object) [];
4198 if ($item instanceof action_menu_link) {
4199 $data->actionmenulink = $item->export_for_template($output);
4200 } else if ($item instanceof action_menu_filler) {
4201 $data->actionmenufiller = $item->export_for_template($output);
4202 } else if ($item instanceof action_link) {
4203 $data->actionlink = $item->export_for_template($output);
4204 } else if ($item instanceof pix_icon) {
4205 $data->pixicon = $item->export_for_template($output);
4206 } else {
4207 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4209 return $data;
4210 }, $this->primaryactions);
4212 $secondary = new stdClass();
4213 $secondary->classes = isset($attributessecondary['class']) ? $attributessecondary['class'] : '';
4214 unset($attributessecondary['class']);
4215 $secondary->attributes = array_map(function($key, $value) {
4216 return [ 'name' => $key, 'value' => $value ];
4217 }, array_keys($attributessecondary), $attributessecondary);
4218 $secondary->items = array_map(function($item) use ($output) {
4219 $data = (object) [];
4220 if ($item instanceof action_menu_link) {
4221 $data->actionmenulink = $item->export_for_template($output);
4222 } else if ($item instanceof action_menu_filler) {
4223 $data->actionmenufiller = $item->export_for_template($output);
4224 } else if ($item instanceof action_link) {
4225 $data->actionlink = $item->export_for_template($output);
4226 } else if ($item instanceof pix_icon) {
4227 $data->pixicon = $item->export_for_template($output);
4228 } else {
4229 $data->rawhtml = ($item instanceof renderable) ? $output->render($item) : $item;
4231 return $data;
4232 }, $this->secondaryactions);
4234 $data->primary = $primary;
4235 $data->secondary = $secondary;
4237 return $data;
4243 * An action menu filler
4245 * @package core
4246 * @category output
4247 * @copyright 2013 Andrew Nicols
4248 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4250 class action_menu_filler extends action_link implements renderable {
4253 * True if this is a primary action. False if not.
4254 * @var bool
4256 public $primary = true;
4259 * Constructs the object.
4261 public function __construct() {
4266 * An action menu action
4268 * @package core
4269 * @category output
4270 * @copyright 2013 Sam Hemelryk
4271 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4273 class action_menu_link extends action_link implements renderable {
4276 * True if this is a primary action. False if not.
4277 * @var bool
4279 public $primary = true;
4282 * The action menu this link has been added to.
4283 * @var action_menu
4285 public $actionmenu = null;
4288 * Constructs the object.
4290 * @param moodle_url $url The URL for the action.
4291 * @param pix_icon $icon The icon to represent the action.
4292 * @param string $text The text to represent the action.
4293 * @param bool $primary Whether this is a primary action or not.
4294 * @param array $attributes Any attribtues associated with the action.
4296 public function __construct(moodle_url $url, pix_icon $icon = null, $text, $primary = true, array $attributes = array()) {
4297 parent::__construct($url, $text, null, $attributes, $icon);
4298 $this->primary = (bool)$primary;
4299 $this->add_class('menu-action');
4300 $this->attributes['role'] = 'menuitem';
4304 * Export for template.
4306 * @param renderer_base $output The renderer.
4307 * @return stdClass
4309 public function export_for_template(renderer_base $output) {
4310 static $instance = 1;
4312 $data = parent::export_for_template($output);
4313 $data->instance = $instance++;
4315 // Ignore what the parent did with the attributes, except for ID and class.
4316 $data->attributes = [];
4317 $attributes = $this->attributes;
4318 unset($attributes['id']);
4319 unset($attributes['class']);
4321 // Handle text being a renderable.
4322 $comparetoalt = $this->text;
4323 if ($this->text instanceof renderable) {
4324 $data->text = $this->render($this->text);
4325 $comparetoalt = '';
4327 $comparetoalt = (string) $comparetoalt;
4329 $data->showtext = (!$this->icon || $this->primary === false);
4331 $data->icon = null;
4332 if ($this->icon) {
4333 $icon = $this->icon;
4334 if ($this->primary || !$this->actionmenu->will_be_enhanced()) {
4335 $attributes['title'] = $data->text;
4337 if (!$this->primary && $this->actionmenu->will_be_enhanced()) {
4338 if ((string) $icon->attributes['alt'] === $comparetoalt) {
4339 $icon->attributes['alt'] = '';
4341 if (isset($icon->attributes['title']) && (string) $icon->attributes['title'] === $comparetoalt) {
4342 unset($icon->attributes['title']);
4345 $data->icon = $icon ? $icon->export_for_template($output) : null;
4348 $data->disabled = !empty($attributes['disabled']);
4349 unset($attributes['disabled']);
4351 $data->attributes = array_map(function($key, $value) {
4352 return [
4353 'name' => $key,
4354 'value' => $value
4356 }, array_keys($attributes), $attributes);
4358 return $data;
4363 * A primary action menu action
4365 * @package core
4366 * @category output
4367 * @copyright 2013 Sam Hemelryk
4368 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4370 class action_menu_link_primary extends action_menu_link {
4372 * Constructs the object.
4374 * @param moodle_url $url
4375 * @param pix_icon $icon
4376 * @param string $text
4377 * @param array $attributes
4379 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
4380 parent::__construct($url, $icon, $text, true, $attributes);
4385 * A secondary action menu action
4387 * @package core
4388 * @category output
4389 * @copyright 2013 Sam Hemelryk
4390 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4392 class action_menu_link_secondary extends action_menu_link {
4394 * Constructs the object.
4396 * @param moodle_url $url
4397 * @param pix_icon $icon
4398 * @param string $text
4399 * @param array $attributes
4401 public function __construct(moodle_url $url, pix_icon $icon = null, $text, array $attributes = array()) {
4402 parent::__construct($url, $icon, $text, false, $attributes);
4407 * Represents a set of preferences groups.
4409 * @package core
4410 * @category output
4411 * @copyright 2015 Frédéric Massart - FMCorz.net
4412 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4414 class preferences_groups implements renderable {
4417 * Array of preferences_group.
4418 * @var array
4420 public $groups;
4423 * Constructor.
4424 * @param array $groups of preferences_group
4426 public function __construct($groups) {
4427 $this->groups = $groups;
4433 * Represents a group of preferences page link.
4435 * @package core
4436 * @category output
4437 * @copyright 2015 Frédéric Massart - FMCorz.net
4438 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4440 class preferences_group implements renderable {
4443 * Title of the group.
4444 * @var string
4446 public $title;
4449 * Array of navigation_node.
4450 * @var array
4452 public $nodes;
4455 * Constructor.
4456 * @param string $title The title.
4457 * @param array $nodes of navigation_node.
4459 public function __construct($title, $nodes) {
4460 $this->title = $title;
4461 $this->nodes = $nodes;
4466 * Progress bar class.
4468 * Manages the display of a progress bar.
4470 * To use this class.
4471 * - construct
4472 * - call create (or use the 3rd param to the constructor)
4473 * - call update or update_full() or update() repeatedly
4475 * @copyright 2008 jamiesensei
4476 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4477 * @package core
4478 * @category output
4480 class progress_bar implements renderable, templatable {
4481 /** @var string html id */
4482 private $html_id;
4483 /** @var int total width */
4484 private $width;
4485 /** @var int last percentage printed */
4486 private $percent = 0;
4487 /** @var int time when last printed */
4488 private $lastupdate = 0;
4489 /** @var int when did we start printing this */
4490 private $time_start = 0;
4493 * Constructor
4495 * Prints JS code if $autostart true.
4497 * @param string $htmlid The container ID.
4498 * @param int $width The suggested width.
4499 * @param bool $autostart Whether to start the progress bar right away.
4501 public function __construct($htmlid = '', $width = 500, $autostart = false) {
4502 if (!empty($htmlid)) {
4503 $this->html_id = $htmlid;
4504 } else {
4505 $this->html_id = 'pbar_'.uniqid();
4508 $this->width = $width;
4510 if ($autostart) {
4511 $this->create();
4516 * Create a new progress bar, this function will output html.
4518 * @return void Echo's output
4520 public function create() {
4521 global $OUTPUT;
4523 $this->time_start = microtime(true);
4524 if (CLI_SCRIPT) {
4525 return; // Temporary solution for cli scripts.
4528 flush();
4529 echo $OUTPUT->render($this);
4530 flush();
4534 * Update the progress bar.
4536 * @param int $percent From 1-100.
4537 * @param string $msg The message.
4538 * @return void Echo's output
4539 * @throws coding_exception
4541 private function _update($percent, $msg) {
4542 if (empty($this->time_start)) {
4543 throw new coding_exception('You must call create() (or use the $autostart ' .
4544 'argument to the constructor) before you try updating the progress bar.');
4547 if (CLI_SCRIPT) {
4548 return; // Temporary solution for cli scripts.
4551 $estimate = $this->estimate($percent);
4553 if ($estimate === null) {
4554 // Always do the first and last updates.
4555 } else if ($estimate == 0) {
4556 // Always do the last updates.
4557 } else if ($this->lastupdate + 20 < time()) {
4558 // We must update otherwise browser would time out.
4559 } else if (round($this->percent, 2) === round($percent, 2)) {
4560 // No significant change, no need to update anything.
4561 return;
4564 $estimatemsg = null;
4565 if (is_numeric($estimate)) {
4566 $estimatemsg = get_string('secondsleft', 'moodle', round($estimate, 2));
4569 $this->percent = round($percent, 2);
4570 $this->lastupdate = microtime(true);
4572 echo html_writer::script(js_writer::function_call('updateProgressBar',
4573 array($this->html_id, $this->percent, $msg, $estimatemsg)));
4574 flush();
4578 * Estimate how much time it is going to take.
4580 * @param int $pt From 1-100.
4581 * @return mixed Null (unknown), or int.
4583 private function estimate($pt) {
4584 if ($this->lastupdate == 0) {
4585 return null;
4587 if ($pt < 0.00001) {
4588 return null; // We do not know yet how long it will take.
4590 if ($pt > 99.99999) {
4591 return 0; // Nearly done, right?
4593 $consumed = microtime(true) - $this->time_start;
4594 if ($consumed < 0.001) {
4595 return null;
4598 return (100 - $pt) * ($consumed / $pt);
4602 * Update progress bar according percent.
4604 * @param int $percent From 1-100.
4605 * @param string $msg The message needed to be shown.
4607 public function update_full($percent, $msg) {
4608 $percent = max(min($percent, 100), 0);
4609 $this->_update($percent, $msg);
4613 * Update progress bar according the number of tasks.
4615 * @param int $cur Current task number.
4616 * @param int $total Total task number.
4617 * @param string $msg The message needed to be shown.
4619 public function update($cur, $total, $msg) {
4620 $percent = ($cur / $total) * 100;
4621 $this->update_full($percent, $msg);
4625 * Restart the progress bar.
4627 public function restart() {
4628 $this->percent = 0;
4629 $this->lastupdate = 0;
4630 $this->time_start = 0;
4634 * Export for template.
4636 * @param renderer_base $output The renderer.
4637 * @return array
4639 public function export_for_template(renderer_base $output) {
4640 return [
4641 'id' => $this->html_id,
4642 'width' => $this->width,