2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Classes representing HTML elements, used by $OUTPUT methods
20 * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
25 * @copyright 2009 Tim Hunt
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29 defined('MOODLE_INTERNAL') ||
die();
32 * Interface marking other classes as suitable for renderer_base::render()
34 * @copyright 2010 Petr Skoda (skodak) info@skodak.org
38 interface renderable
{
39 // intentionally empty
43 * Interface marking other classes having the ability to export their data for use by templates.
45 * @copyright 2015 Damyon Wiese
50 interface templatable
{
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);
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
73 class file_picker
implements renderable
{
76 * @var stdClass An object containing options for the file picker
81 * Constructs a file picker object.
83 * The following are possible options for the filepicker:
84 * - accepted_types (*)
85 * - return_types (FILE_INTERNAL)
87 * - client_id (uniqid)
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');
99 'accepted_types'=>'*',
100 'return_types'=>FILE_INTERNAL
,
101 'env' => 'filepicker',
102 'client_id' => uniqid(),
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);
123 $file = $fs->get_file($usercontext->id
, 'user', 'draft', $options->itemid
, $options->filepath
, $options->filename
);
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
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.
166 * @var int The course id. Used when constructing the link to the user's
167 * profile, page course id used if not specified.
172 * @var bool Add course profile link to image
177 * @var int Size in pixels. Special values are (true/1 = 100px) and
179 * for backward compatibility.
184 * @var bool Add non-blank alt-text to the image.
185 * Default true, set to false when image alt just duplicates text in screenreaders.
187 public $alttext = true;
190 * @var bool Whether or not to open the link in a popup window.
192 public $popup = false;
195 * @var string Image class attribute
197 public $class = 'userpicture';
200 * @var bool Whether to be visible to screen readers.
202 public $visibletoscreenreaders = true;
205 * @var bool Whether to include the fullname in the user picture link.
207 public $includefullname = false;
210 * @var mixed Include user authentication token. True indicates to generate a token for current user, and integer value
211 * indicates to generate a token for the user whose id is the value indicated.
213 public $includetoken = false;
216 * User picture constructor.
218 * @param stdClass $user user record with at least id, picture, imagealt, firstname and lastname set.
219 * It is recommended to add also contextid of the user for performance reasons.
221 public function __construct(stdClass
$user) {
224 if (empty($user->id
)) {
225 throw new coding_exception('User id is required when printing user avatar image.');
228 // only touch the DB if we are missing data and complain loudly...
230 foreach (self
::$fields as $field) {
231 if (!array_key_exists($field, $user)) {
233 debugging('Missing '.$field.' property in $user object, this is a performance problem that needs to be fixed by a developer. '
234 .'Please use user_picture::fields() to get the full list of required fields.', DEBUG_DEVELOPER
);
240 $this->user
= $DB->get_record('user', array('id'=>$user->id
), self
::fields(), MUST_EXIST
);
242 $this->user
= clone($user);
247 * Returns a list of required user fields, useful when fetching required user info from db.
249 * In some cases we have to fetch the user data together with some other information,
250 * the idalias is useful there because the id would otherwise override the main
251 * id of the result record. Please note it has to be converted back to id before rendering.
253 * @param string $tableprefix name of database table prefix in query
254 * @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)
255 * @param string $idalias alias of id field
256 * @param string $fieldprefix prefix to add to all columns in their aliases, does not apply to 'id'
259 public static function fields($tableprefix = '', array $extrafields = NULL, $idalias = 'id', $fieldprefix = '') {
260 if (!$tableprefix and !$extrafields and !$idalias) {
261 return implode(',', self
::$fields);
266 foreach (self
::$fields as $field) {
267 if ($field === 'id' and $idalias and $idalias !== 'id') {
268 $fields[$field] = "$tableprefix$field AS $idalias";
270 if ($fieldprefix and $field !== 'id') {
271 $fields[$field] = "$tableprefix$field AS $fieldprefix$field";
273 $fields[$field] = "$tableprefix$field";
277 // add extra fields if not already there
279 foreach ($extrafields as $e) {
280 if ($e === 'id' or isset($fields[$e])) {
284 $fields[$e] = "$tableprefix$e AS $fieldprefix$e";
286 $fields[$e] = "$tableprefix$e";
290 return implode(',', $fields);
294 * Extract the aliased user fields from a given record
296 * Given a record that was previously obtained using {@link self::fields()} with aliases,
297 * this method extracts user related unaliased fields.
299 * @param stdClass $record containing user picture fields
300 * @param array $extrafields extra fields included in the $record
301 * @param string $idalias alias of the id field
302 * @param string $fieldprefix prefix added to all columns in their aliases, does not apply to 'id'
303 * @return stdClass object with unaliased user fields
305 public static function unalias(stdClass
$record, array $extrafields = null, $idalias = 'id', $fieldprefix = '') {
307 if (empty($idalias)) {
311 $return = new stdClass();
313 foreach (self
::$fields as $field) {
314 if ($field === 'id') {
315 if (property_exists($record, $idalias)) {
316 $return->id
= $record->{$idalias};
319 if (property_exists($record, $fieldprefix.$field)) {
320 $return->{$field} = $record->{$fieldprefix.$field};
324 // add extra fields if not already there
326 foreach ($extrafields as $e) {
327 if ($e === 'id' or property_exists($return, $e)) {
330 $return->{$e} = $record->{$fieldprefix.$e};
338 * Works out the URL for the users picture.
340 * This method is recommended as it avoids costly redirects of user pictures
341 * if requests are made for non-existent files etc.
343 * @param moodle_page $page
344 * @param renderer_base $renderer
347 public function get_url(moodle_page
$page, renderer_base
$renderer = null) {
350 if (is_null($renderer)) {
351 $renderer = $page->get_renderer('core');
354 // Sort out the filename and size. Size is only required for the gravatar
355 // implementation presently.
356 if (empty($this->size
)) {
359 } else if ($this->size
=== true or $this->size
== 1) {
362 } else if ($this->size
> 100) {
364 $size = (int)$this->size
;
365 } else if ($this->size
>= 50) {
367 $size = (int)$this->size
;
370 $size = (int)$this->size
;
373 $defaulturl = $renderer->image_url('u/'.$filename); // default image
375 if ((!empty($CFG->forcelogin
) and !isloggedin()) ||
376 (!empty($CFG->forceloginforprofileimage
) && (!isloggedin() ||
isguestuser()))) {
377 // Protect images if login required and not logged in;
378 // also if login is required for profile images and is not logged in or guest
379 // do not use require_login() because it is expensive and not suitable here anyway.
383 // First try to detect deleted users - but do not read from database for performance reasons!
384 if (!empty($this->user
->deleted
) or strpos($this->user
->email
, '@') === false) {
385 // All deleted users should have email replaced by md5 hash,
386 // all active users are expected to have valid email.
390 // Did the user upload a picture?
391 if ($this->user
->picture
> 0) {
392 if (!empty($this->user
->contextid
)) {
393 $contextid = $this->user
->contextid
;
395 $context = context_user
::instance($this->user
->id
, IGNORE_MISSING
);
397 // This must be an incorrectly deleted user, all other users have context.
400 $contextid = $context->id
;
404 if (clean_param($page->theme
->name
, PARAM_THEME
) == $page->theme
->name
) {
405 // We append the theme name to the file path if we have it so that
406 // in the circumstance that the profile picture is not available
407 // when the user actually requests it they still get the profile
408 // picture for the correct theme.
409 $path .= $page->theme
->name
.'/';
411 // Set the image URL to the URL for the uploaded file and return.
412 $url = moodle_url
::make_pluginfile_url(
413 $contextid, 'user', 'icon', null, $path, $filename, false, $this->includetoken
);
414 $url->param('rev', $this->user
->picture
);
418 if ($this->user
->picture
== 0 and !empty($CFG->enablegravatar
)) {
419 // Normalise the size variable to acceptable bounds
420 if ($size < 1 ||
$size > 512) {
423 // Hash the users email address
424 $md5 = md5(strtolower(trim($this->user
->email
)));
425 // Build a gravatar URL with what we know.
427 // Find the best default image URL we can (MDL-35669)
428 if (empty($CFG->gravatardefaulturl
)) {
429 $absoluteimagepath = $page->theme
->resolve_image_location('u/'.$filename, 'core');
430 if (strpos($absoluteimagepath, $CFG->dirroot
) === 0) {
431 $gravatardefault = $CFG->wwwroot
. substr($absoluteimagepath, strlen($CFG->dirroot
));
433 $gravatardefault = $CFG->wwwroot
. '/pix/u/' . $filename . '.png';
436 $gravatardefault = $CFG->gravatardefaulturl
;
439 // If the currently requested page is https then we'll return an
440 // https gravatar page.
442 return new moodle_url("https://secure.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
444 return new moodle_url("http://www.gravatar.com/avatar/{$md5}", array('s' => $size, 'd' => $gravatardefault));
453 * Data structure representing a help icon.
455 * @copyright 2010 Petr Skoda (info@skodak.org)
456 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
461 class help_icon
implements renderable
, templatable
{
464 * @var string lang pack identifier (without the "_help" suffix),
465 * both get_string($identifier, $component) and get_string($identifier.'_help', $component)
471 * @var string Component name, the same as in get_string()
476 * @var string Extra descriptive text next to the icon
478 public $linktext = null;
483 * @param string $identifier string for help page title,
484 * string with _help suffix is used for the actual help text.
485 * string with _link suffix is used to create a link to further info (if it exists)
486 * @param string $component
488 public function __construct($identifier, $component) {
489 $this->identifier
= $identifier;
490 $this->component
= $component;
494 * Verifies that both help strings exists, shows debug warnings if not
496 public function diag_strings() {
497 $sm = get_string_manager();
498 if (!$sm->string_exists($this->identifier
, $this->component
)) {
499 debugging("Help title string does not exist: [$this->identifier, $this->component]");
501 if (!$sm->string_exists($this->identifier
.'_help', $this->component
)) {
502 debugging("Help contents string does not exist: [{$this->identifier}_help, $this->component]");
507 * Export this data so it can be used as the context for a mustache template.
509 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
512 public function export_for_template(renderer_base
$output) {
515 $title = get_string($this->identifier
, $this->component
);
517 if (empty($this->linktext
)) {
518 $alt = get_string('helpprefix2', '', trim($title, ". \t"));
520 $alt = get_string('helpwiththis');
523 $data = get_formatted_help_string($this->identifier
, $this->component
, false);
526 $data->icon
= (new pix_icon('help', $alt, 'core', ['class' => 'iconhelp']))->export_for_template($output);
527 $data->linktext
= $this->linktext
;
528 $data->title
= get_string('helpprefix2', '', trim($title, ". \t"));
531 'component' => $this->component
,
532 'identifier' => $this->identifier
,
533 'lang' => current_language()
536 // Debugging feature lets you display string identifier and component.
537 if (isset($CFG->debugstringids
) && $CFG->debugstringids
&& optional_param('strings', 0, PARAM_INT
)) {
538 $options['strings'] = 1;
541 $data->url
= (new moodle_url('/help.php', $options))->out(false);
542 $data->ltr
= !right_to_left();
549 * Data structure representing an icon font.
551 * @copyright 2016 Damyon Wiese
552 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
556 class pix_icon_font
implements templatable
{
559 * @var pix_icon $pixicon The original icon.
561 private $pixicon = null;
564 * @var string $key The mapped key.
569 * @var bool $mapped The icon could not be mapped.
576 * @param pix_icon $pixicon The original icon
578 public function __construct(pix_icon
$pixicon) {
581 $this->pixicon
= $pixicon;
582 $this->mapped
= false;
583 $iconsystem = \core\output\icon_system
::instance();
585 $this->key
= $iconsystem->remap_icon_name($pixicon->pix
, $pixicon->component
);
586 if (!empty($this->key
)) {
587 $this->mapped
= true;
592 * Return true if this pix_icon was successfully mapped to an icon font.
596 public function is_mapped() {
597 return $this->mapped
;
601 * Export this data so it can be used as the context for a mustache template.
603 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
606 public function export_for_template(renderer_base
$output) {
608 $pixdata = $this->pixicon
->export_for_template($output);
610 $title = isset($this->pixicon
->attributes
['title']) ?
$this->pixicon
->attributes
['title'] : '';
611 $alt = isset($this->pixicon
->attributes
['alt']) ?
$this->pixicon
->attributes
['alt'] : '';
616 'extraclasses' => $pixdata['extraclasses'],
627 * Data structure representing an icon subtype.
629 * @copyright 2016 Damyon Wiese
630 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
634 class pix_icon_fontawesome
extends pix_icon_font
{
639 * Data structure representing an icon.
641 * @copyright 2010 Petr Skoda
642 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
647 class pix_icon
implements renderable
, templatable
{
650 * @var string The icon name
655 * @var string The component the icon belongs to.
660 * @var array An array of attributes to use on the icon
662 var $attributes = array();
667 * @param string $pix short icon name
668 * @param string $alt The alt text to use for the icon
669 * @param string $component component name
670 * @param array $attributes html attributes
672 public function __construct($pix, $alt, $component='moodle', array $attributes = null) {
676 $this->component
= $component;
677 $this->attributes
= (array)$attributes;
679 if (empty($this->attributes
['class'])) {
680 $this->attributes
['class'] = '';
683 // Set an additional class for big icons so that they can be styled properly.
684 if (substr($pix, 0, 2) === 'b/') {
685 $this->attributes
['class'] .= ' iconsize-big';
688 // If the alt is empty, don't place it in the attributes, otherwise it will override parent alt text.
689 if (!is_null($alt)) {
690 $this->attributes
['alt'] = $alt;
692 // If there is no title, set it to the attribute.
693 if (!isset($this->attributes
['title'])) {
694 $this->attributes
['title'] = $this->attributes
['alt'];
697 unset($this->attributes
['alt']);
700 if (empty($this->attributes
['title'])) {
701 // Remove the title attribute if empty, we probably want to use the parent node's title
702 // and some browsers might overwrite it with an empty title.
703 unset($this->attributes
['title']);
706 // Hide icons from screen readers that have no alt.
707 if (empty($this->attributes
['alt'])) {
708 $this->attributes
['aria-hidden'] = 'true';
713 * Export this data so it can be used as the context for a mustache template.
715 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
718 public function export_for_template(renderer_base
$output) {
719 $attributes = $this->attributes
;
722 foreach ($attributes as $key => $item) {
723 if ($key == 'class') {
724 $extraclasses = $item;
725 unset($attributes[$key]);
730 $attributes['src'] = $output->image_url($this->pix
, $this->component
)->out(false);
731 $templatecontext = array();
732 foreach ($attributes as $name => $value) {
733 $templatecontext[] = array('name' => $name, 'value' => $value);
735 $title = isset($attributes['title']) ?
$attributes['title'] : '';
737 $title = isset($attributes['alt']) ?
$attributes['alt'] : '';
740 'attributes' => $templatecontext,
741 'extraclasses' => $extraclasses
748 * Much simpler version of export that will produce the data required to render this pix with the
749 * pix helper in a mustache tag.
753 public function export_for_pix() {
754 $title = isset($this->attributes
['title']) ?
$this->attributes
['title'] : '';
756 $title = isset($this->attributes
['alt']) ?
$this->attributes
['alt'] : '';
760 'component' => $this->component
,
767 * Data structure representing an activity icon.
769 * The difference is that activity icons will always render with the standard icon system (no font icons).
771 * @copyright 2017 Damyon Wiese
772 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
775 class image_icon
extends pix_icon
{
779 * Data structure representing an emoticon image
781 * @copyright 2010 David Mudrak
782 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
787 class pix_emoticon
extends pix_icon
implements renderable
{
791 * @param string $pix short icon name
792 * @param string $alt alternative text
793 * @param string $component emoticon image provider
794 * @param array $attributes explicit HTML attributes
796 public function __construct($pix, $alt, $component = 'moodle', array $attributes = array()) {
797 if (empty($attributes['class'])) {
798 $attributes['class'] = 'emoticon';
800 parent
::__construct($pix, $alt, $component, $attributes);
805 * Data structure representing a simple form with only one button.
807 * @copyright 2009 Petr Skoda
808 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
813 class single_button
implements renderable
{
816 * @var moodle_url Target url
821 * @var string Button label
826 * @var string Form submit method post or get
828 public $method = 'post';
831 * @var string Wrapping div class
833 public $class = 'singlebutton';
836 * @var bool True if button is primary button. Used for styling.
838 public $primary = false;
841 * @var bool True if button disabled, false if normal
843 public $disabled = false;
846 * @var string Button tooltip
848 public $tooltip = null;
851 * @var string Form id
856 * @var array List of attached actions
858 public $actions = array();
861 * @var array $params URL Params
866 * @var string Action id
872 * @param moodle_url $url
873 * @param string $label button text
874 * @param string $method get or post submit method
876 public function __construct(moodle_url
$url, $label, $method='post', $primary=false) {
877 $this->url
= clone($url);
878 $this->label
= $label;
879 $this->method
= $method;
880 $this->primary
= $primary;
884 * Shortcut for adding a JS confirm dialog when the button is clicked.
885 * The message must be a yes/no question.
887 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
889 public function add_confirm_action($confirmmessage) {
890 $this->add_action(new confirm_action($confirmmessage));
894 * Add action to the button.
895 * @param component_action $action
897 public function add_action(component_action
$action) {
898 $this->actions
[] = $action;
904 * @param renderer_base $output Renderer.
907 public function export_for_template(renderer_base
$output) {
908 $url = $this->method
=== 'get' ?
$this->url
->out_omit_querystring(true) : $this->url
->out_omit_querystring();
910 $data = new stdClass();
911 $data->id
= html_writer
::random_id('single_button');
912 $data->formid
= $this->formid
;
913 $data->method
= $this->method
;
914 $data->url
= $url === '' ?
'#' : $url;
915 $data->label
= $this->label
;
916 $data->classes
= $this->class;
917 $data->disabled
= $this->disabled
;
918 $data->tooltip
= $this->tooltip
;
919 $data->primary
= $this->primary
;
922 $params = $this->url
->params();
923 if ($this->method
=== 'post') {
924 $params['sesskey'] = sesskey();
926 $data->params
= array_map(function($key) use ($params) {
927 return ['name' => $key, 'value' => $params[$key]];
928 }, array_keys($params));
931 $actions = $this->actions
;
932 $data->actions
= array_map(function($action) use ($output) {
933 return $action->export_for_template($output);
935 $data->hasactions
= !empty($data->actions
);
943 * Simple form with just one select field that gets submitted automatically.
945 * If JS not enabled small go button is printed too.
947 * @copyright 2009 Petr Skoda
948 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
953 class single_select
implements renderable
, templatable
{
956 * @var moodle_url Target url - includes hidden fields
961 * @var string Name of the select element.
966 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
967 * it is also possible to specify optgroup as complex label array ex.:
968 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
969 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
974 * @var string Selected option
979 * @var array Nothing selected
984 * @var array Extra select field attributes
986 var $attributes = array();
989 * @var string Button label
994 * @var array Button label's attributes
996 var $labelattributes = array();
999 * @var string Form submit method post or get
1001 var $method = 'get';
1004 * @var string Wrapping div class
1006 var $class = 'singleselect';
1009 * @var bool True if button disabled, false if normal
1011 var $disabled = false;
1014 * @var string Button tooltip
1016 var $tooltip = null;
1019 * @var string Form id
1024 * @var help_icon The help icon for this element.
1026 var $helpicon = null;
1030 * @param moodle_url $url form action target, includes hidden fields
1031 * @param string $name name of selection field - the changing parameter in url
1032 * @param array $options list of options
1033 * @param string $selected selected element
1034 * @param array $nothing
1035 * @param string $formid
1037 public function __construct(moodle_url
$url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1039 $this->name
= $name;
1040 $this->options
= $options;
1041 $this->selected
= $selected;
1042 $this->nothing
= $nothing;
1043 $this->formid
= $formid;
1047 * Shortcut for adding a JS confirm dialog when the button is clicked.
1048 * The message must be a yes/no question.
1050 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
1052 public function add_confirm_action($confirmmessage) {
1053 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
1057 * Add action to the button.
1059 * @param component_action $action
1061 public function add_action(component_action
$action) {
1062 $this->actions
[] = $action;
1068 * @deprecated since Moodle 2.0
1070 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1071 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1077 * @param string $identifier The keyword that defines a help page
1078 * @param string $component
1080 public function set_help_icon($identifier, $component = 'moodle') {
1081 $this->helpicon
= new help_icon($identifier, $component);
1085 * Sets select's label
1087 * @param string $label
1088 * @param array $attributes (optional)
1090 public function set_label($label, $attributes = array()) {
1091 $this->label
= $label;
1092 $this->labelattributes
= $attributes;
1099 * @param renderer_base $output Renderer.
1102 public function export_for_template(renderer_base
$output) {
1103 $attributes = $this->attributes
;
1105 $data = new stdClass();
1106 $data->name
= $this->name
;
1107 $data->method
= $this->method
;
1108 $data->action
= $this->method
=== 'get' ?
$this->url
->out_omit_querystring(true) : $this->url
->out_omit_querystring();
1109 $data->classes
= $this->class;
1110 $data->label
= $this->label
;
1111 $data->disabled
= $this->disabled
;
1112 $data->title
= $this->tooltip
;
1113 $data->formid
= !empty($this->formid
) ?
$this->formid
: html_writer
::random_id('single_select_f');
1114 $data->id
= !empty($attributes['id']) ?
$attributes['id'] : html_writer
::random_id('single_select');
1116 // Select element attributes.
1117 // Unset attributes that are already predefined in the template.
1118 unset($attributes['id']);
1119 unset($attributes['class']);
1120 unset($attributes['name']);
1121 unset($attributes['title']);
1122 unset($attributes['disabled']);
1124 // Map the attributes.
1125 $data->attributes
= array_map(function($key) use ($attributes) {
1126 return ['name' => $key, 'value' => $attributes[$key]];
1127 }, array_keys($attributes));
1130 $params = $this->url
->params();
1131 if ($this->method
=== 'post') {
1132 $params['sesskey'] = sesskey();
1134 $data->params
= array_map(function($key) use ($params) {
1135 return ['name' => $key, 'value' => $params[$key]];
1136 }, array_keys($params));
1139 $hasnothing = false;
1140 if (is_string($this->nothing
) && $this->nothing
!== '') {
1141 $nothing = ['' => $this->nothing
];
1144 } else if (is_array($this->nothing
)) {
1145 $nothingvalue = reset($this->nothing
);
1146 if ($nothingvalue === 'choose' ||
$nothingvalue === 'choosedots') {
1147 $nothing = [key($this->nothing
) => get_string('choosedots')];
1149 $nothing = $this->nothing
;
1152 $nothingkey = key($this->nothing
);
1155 $options = $nothing +
$this->options
;
1157 $options = $this->options
;
1160 foreach ($options as $value => $name) {
1161 if (is_array($options[$value])) {
1162 foreach ($options[$value] as $optgroupname => $optgroupvalues) {
1164 foreach ($optgroupvalues as $optvalue => $optname) {
1166 'value' => $optvalue,
1168 'selected' => strval($this->selected
) === strval($optvalue),
1171 if ($hasnothing && $nothingkey === $optvalue) {
1172 $option['ignore'] = 'data-ignore';
1175 $sublist[] = $option;
1177 $data->options
[] = [
1178 'name' => $optgroupname,
1180 'options' => $sublist
1186 'name' => $options[$value],
1187 'selected' => strval($this->selected
) === strval($value),
1191 if ($hasnothing && $nothingkey === $value) {
1192 $option['ignore'] = 'data-ignore';
1195 $data->options
[] = $option;
1199 // Label attributes.
1200 $data->labelattributes
= [];
1201 // Unset label attributes that are already in the template.
1202 unset($this->labelattributes
['for']);
1203 // Map the label attributes.
1204 foreach ($this->labelattributes
as $key => $value) {
1205 $data->labelattributes
[] = ['name' => $key, 'value' => $value];
1209 $data->helpicon
= !empty($this->helpicon
) ?
$this->helpicon
->export_for_template($output) : false;
1216 * Simple URL selection widget description.
1218 * @copyright 2009 Petr Skoda
1219 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1224 class url_select
implements renderable
, templatable
{
1226 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
1227 * it is also possible to specify optgroup as complex label array ex.:
1228 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1229 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1234 * @var string Selected option
1239 * @var array Nothing selected
1244 * @var array Extra select field attributes
1246 var $attributes = array();
1249 * @var string Button label
1254 * @var array Button label's attributes
1256 var $labelattributes = array();
1259 * @var string Wrapping div class
1261 var $class = 'urlselect';
1264 * @var bool True if button disabled, false if normal
1266 var $disabled = false;
1269 * @var string Button tooltip
1271 var $tooltip = null;
1274 * @var string Form id
1279 * @var help_icon The help icon for this element.
1281 var $helpicon = null;
1284 * @var string If set, makes button visible with given name for button
1286 var $showbutton = null;
1290 * @param array $urls list of options
1291 * @param string $selected selected element
1292 * @param array $nothing
1293 * @param string $formid
1294 * @param string $showbutton Set to text of button if it should be visible
1295 * or null if it should be hidden (hidden version always has text 'go')
1297 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
1298 $this->urls
= $urls;
1299 $this->selected
= $selected;
1300 $this->nothing
= $nothing;
1301 $this->formid
= $formid;
1302 $this->showbutton
= $showbutton;
1308 * @deprecated since Moodle 2.0
1310 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1311 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1317 * @param string $identifier The keyword that defines a help page
1318 * @param string $component
1320 public function set_help_icon($identifier, $component = 'moodle') {
1321 $this->helpicon
= new help_icon($identifier, $component);
1325 * Sets select's label
1327 * @param string $label
1328 * @param array $attributes (optional)
1330 public function set_label($label, $attributes = array()) {
1331 $this->label
= $label;
1332 $this->labelattributes
= $attributes;
1338 * @param string $value The URL.
1339 * @return The cleaned URL.
1341 protected function clean_url($value) {
1344 if (empty($value)) {
1347 } else if (strpos($value, $CFG->wwwroot
. '/') === 0) {
1348 $value = str_replace($CFG->wwwroot
, '', $value);
1350 } else if (strpos($value, '/') !== 0) {
1351 debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER
);
1358 * Flatten the options for Mustache.
1360 * This also cleans the URLs.
1362 * @param array $options The options.
1363 * @param array $nothing The nothing option.
1366 protected function flatten_options($options, $nothing) {
1369 foreach ($options as $value => $option) {
1370 if (is_array($option)) {
1371 foreach ($option as $groupname => $optoptions) {
1372 if (!isset($flattened[$groupname])) {
1373 $flattened[$groupname] = [
1374 'name' => $groupname,
1379 foreach ($optoptions as $optvalue => $optoption) {
1380 $cleanedvalue = $this->clean_url($optvalue);
1381 $flattened[$groupname]['options'][$cleanedvalue] = [
1382 'name' => $optoption,
1383 'value' => $cleanedvalue,
1384 'selected' => $this->selected
== $optvalue,
1390 $cleanedvalue = $this->clean_url($value);
1391 $flattened[$cleanedvalue] = [
1393 'value' => $cleanedvalue,
1394 'selected' => $this->selected
== $value,
1399 if (!empty($nothing)) {
1400 $value = key($nothing);
1401 $name = reset($nothing);
1403 $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected
== $value]
1407 // Make non-associative array.
1408 foreach ($flattened as $key => $value) {
1409 if (!empty($value['options'])) {
1410 $flattened[$key]['options'] = array_values($value['options']);
1413 $flattened = array_values($flattened);
1419 * Export for template.
1421 * @param renderer_base $output Renderer.
1424 public function export_for_template(renderer_base
$output) {
1425 $attributes = $this->attributes
;
1427 $data = new stdClass();
1428 $data->formid
= !empty($this->formid
) ?
$this->formid
: html_writer
::random_id('url_select_f');
1429 $data->classes
= $this->class;
1430 $data->label
= $this->label
;
1431 $data->disabled
= $this->disabled
;
1432 $data->title
= $this->tooltip
;
1433 $data->id
= !empty($attributes['id']) ?
$attributes['id'] : html_writer
::random_id('url_select');
1434 $data->sesskey
= sesskey();
1435 $data->action
= (new moodle_url('/course/jumpto.php'))->out(false);
1437 // Remove attributes passed as property directly.
1438 unset($attributes['class']);
1439 unset($attributes['id']);
1440 unset($attributes['name']);
1441 unset($attributes['title']);
1442 unset($attributes['disabled']);
1444 $data->showbutton
= $this->showbutton
;
1448 if (is_string($this->nothing
) && $this->nothing
!== '') {
1449 $nothing = ['' => $this->nothing
];
1450 } else if (is_array($this->nothing
)) {
1451 $nothingvalue = reset($this->nothing
);
1452 if ($nothingvalue === 'choose' ||
$nothingvalue === 'choosedots') {
1453 $nothing = [key($this->nothing
) => get_string('choosedots')];
1455 $nothing = $this->nothing
;
1458 $data->options
= $this->flatten_options($this->urls
, $nothing);
1460 // Label attributes.
1461 $data->labelattributes
= [];
1462 // Unset label attributes that are already in the template.
1463 unset($this->labelattributes
['for']);
1464 // Map the label attributes.
1465 foreach ($this->labelattributes
as $key => $value) {
1466 $data->labelattributes
[] = ['name' => $key, 'value' => $value];
1470 $data->helpicon
= !empty($this->helpicon
) ?
$this->helpicon
->export_for_template($output) : false;
1472 // Finally all the remaining attributes.
1473 $data->attributes
= [];
1474 foreach ($attributes as $key => $value) {
1475 $data->attributes
[] = ['name' => $key, 'value' => $value];
1483 * Data structure describing html link with special action attached.
1485 * @copyright 2010 Petr Skoda
1486 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1491 class action_link
implements renderable
{
1494 * @var moodle_url Href url
1499 * @var string Link text HTML fragment
1504 * @var array HTML attributes
1509 * @var array List of actions attached to link
1514 * @var pix_icon Optional pix icon to render with the link
1520 * @param moodle_url $url
1521 * @param string $text HTML fragment
1522 * @param component_action $action
1523 * @param array $attributes associative array of html link attributes + disabled
1524 * @param pix_icon $icon optional pix_icon to render with the link text
1526 public function __construct(moodle_url
$url,
1528 component_action
$action=null,
1529 array $attributes=null,
1530 pix_icon
$icon=null) {
1531 $this->url
= clone($url);
1532 $this->text
= $text;
1533 $this->attributes
= (array)$attributes;
1535 $this->add_action($action);
1537 $this->icon
= $icon;
1541 * Add action to the link.
1543 * @param component_action $action
1545 public function add_action(component_action
$action) {
1546 $this->actions
[] = $action;
1550 * Adds a CSS class to this action link object
1551 * @param string $class
1553 public function add_class($class) {
1554 if (empty($this->attributes
['class'])) {
1555 $this->attributes
['class'] = $class;
1557 $this->attributes
['class'] .= ' ' . $class;
1562 * Returns true if the specified class has been added to this link.
1563 * @param string $class
1566 public function has_class($class) {
1567 return strpos(' ' . $this->attributes
['class'] . ' ', ' ' . $class . ' ') !== false;
1571 * Return the rendered HTML for the icon. Useful for rendering action links in a template.
1574 public function get_icon_html() {
1579 return $OUTPUT->render($this->icon
);
1583 * Export for template.
1585 * @param renderer_base $output The renderer.
1588 public function export_for_template(renderer_base
$output) {
1589 $data = new stdClass();
1590 $attributes = $this->attributes
;
1592 if (empty($attributes['id'])) {
1593 $attributes['id'] = html_writer
::random_id('action_link');
1595 $data->id
= $attributes['id'];
1596 unset($attributes['id']);
1598 $data->disabled
= !empty($attributes['disabled']);
1599 unset($attributes['disabled']);
1601 $data->text
= $this->text
instanceof renderable ?
$output->render($this->text
) : (string) $this->text
;
1602 $data->url
= $this->url ?
$this->url
->out(false) : '';
1603 $data->icon
= $this->icon ?
$this->icon
->export_for_pix() : null;
1604 $data->classes
= isset($attributes['class']) ?
$attributes['class'] : '';
1605 unset($attributes['class']);
1607 $data->attributes
= array_map(function($key, $value) {
1612 }, array_keys($attributes), $attributes);
1614 $data->actions
= array_map(function($action) use ($output) {
1615 return $action->export_for_template($output);
1616 }, !empty($this->actions
) ?
$this->actions
: []);
1617 $data->hasactions
= !empty($this->actions
);
1624 * Simple html output class
1626 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1627 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1635 * Outputs a tag with attributes and contents
1637 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1638 * @param string $contents What goes between the opening and closing tags
1639 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1640 * @return string HTML fragment
1642 public static function tag($tagname, $contents, array $attributes = null) {
1643 return self
::start_tag($tagname, $attributes) . $contents . self
::end_tag($tagname);
1647 * Outputs an opening tag with attributes
1649 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1650 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1651 * @return string HTML fragment
1653 public static function start_tag($tagname, array $attributes = null) {
1654 return '<' . $tagname . self
::attributes($attributes) . '>';
1658 * Outputs a closing tag
1660 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1661 * @return string HTML fragment
1663 public static function end_tag($tagname) {
1664 return '</' . $tagname . '>';
1668 * Outputs an empty tag with attributes
1670 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1671 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1672 * @return string HTML fragment
1674 public static function empty_tag($tagname, array $attributes = null) {
1675 return '<' . $tagname . self
::attributes($attributes) . ' />';
1679 * Outputs a tag, but only if the contents are not empty
1681 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1682 * @param string $contents What goes between the opening and closing tags
1683 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1684 * @return string HTML fragment
1686 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1687 if ($contents === '' ||
is_null($contents)) {
1690 return self
::tag($tagname, $contents, $attributes);
1694 * Outputs a HTML attribute and value
1696 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1697 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1698 * @return string HTML fragment
1700 public static function attribute($name, $value) {
1701 if ($value instanceof moodle_url
) {
1702 return ' ' . $name . '="' . $value->out() . '"';
1705 // special case, we do not want these in output
1706 if ($value === null) {
1710 // no sloppy trimming here!
1711 return ' ' . $name . '="' . s($value) . '"';
1715 * Outputs a list of HTML attributes and values
1717 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1718 * The values will be escaped with {@link s()}
1719 * @return string HTML fragment
1721 public static function attributes(array $attributes = null) {
1722 $attributes = (array)$attributes;
1724 foreach ($attributes as $name => $value) {
1725 $output .= self
::attribute($name, $value);
1731 * Generates a simple image tag with attributes.
1733 * @param string $src The source of image
1734 * @param string $alt The alternate text for image
1735 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1736 * @return string HTML fragment
1738 public static function img($src, $alt, array $attributes = null) {
1739 $attributes = (array)$attributes;
1740 $attributes['src'] = $src;
1741 $attributes['alt'] = $alt;
1743 return self
::empty_tag('img', $attributes);
1747 * Generates random html element id.
1749 * @staticvar int $counter
1750 * @staticvar type $uniq
1751 * @param string $base A string fragment that will be included in the random ID.
1752 * @return string A unique ID
1754 public static function random_id($base='random') {
1755 static $counter = 0;
1758 if (!isset($uniq)) {
1763 return $base.$uniq.$counter;
1767 * Generates a simple html link
1769 * @param string|moodle_url $url The URL
1770 * @param string $text The text
1771 * @param array $attributes HTML attributes
1772 * @return string HTML fragment
1774 public static function link($url, $text, array $attributes = null) {
1775 $attributes = (array)$attributes;
1776 $attributes['href'] = $url;
1777 return self
::tag('a', $text, $attributes);
1781 * Generates a simple checkbox with optional label
1783 * @param string $name The name of the checkbox
1784 * @param string $value The value of the checkbox
1785 * @param bool $checked Whether the checkbox is checked
1786 * @param string $label The label for the checkbox
1787 * @param array $attributes Any attributes to apply to the checkbox
1788 * @return string html fragment
1790 public static function checkbox($name, $value, $checked = true, $label = '', array $attributes = null) {
1791 $attributes = (array)$attributes;
1794 if ($label !== '' and !is_null($label)) {
1795 if (empty($attributes['id'])) {
1796 $attributes['id'] = self
::random_id('checkbox_');
1799 $attributes['type'] = 'checkbox';
1800 $attributes['value'] = $value;
1801 $attributes['name'] = $name;
1802 $attributes['checked'] = $checked ?
'checked' : null;
1804 $output .= self
::empty_tag('input', $attributes);
1806 if ($label !== '' and !is_null($label)) {
1807 $output .= self
::tag('label', $label, array('for'=>$attributes['id']));
1814 * Generates a simple select yes/no form field
1816 * @param string $name name of select element
1817 * @param bool $selected
1818 * @param array $attributes - html select element attributes
1819 * @return string HTML fragment
1821 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1822 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1823 return self
::select($options, $name, $selected, null, $attributes);
1827 * Generates a simple select form field
1829 * @param array $options associative array value=>label ex.:
1830 * array(1=>'One, 2=>Two)
1831 * it is also possible to specify optgroup as complex label array ex.:
1832 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1833 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1834 * @param string $name name of select element
1835 * @param string|array $selected value or array of values depending on multiple attribute
1836 * @param array|bool $nothing add nothing selected option, or false of not added
1837 * @param array $attributes html select element attributes
1838 * @return string HTML fragment
1840 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1841 $attributes = (array)$attributes;
1842 if (is_array($nothing)) {
1843 foreach ($nothing as $k=>$v) {
1844 if ($v === 'choose' or $v === 'choosedots') {
1845 $nothing[$k] = get_string('choosedots');
1848 $options = $nothing +
$options; // keep keys, do not override
1850 } else if (is_string($nothing) and $nothing !== '') {
1852 $options = array(''=>$nothing) +
$options;
1855 // we may accept more values if multiple attribute specified
1856 $selected = (array)$selected;
1857 foreach ($selected as $k=>$v) {
1858 $selected[$k] = (string)$v;
1861 if (!isset($attributes['id'])) {
1863 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1864 $id = str_replace('[', '', $id);
1865 $id = str_replace(']', '', $id);
1866 $attributes['id'] = $id;
1869 if (!isset($attributes['class'])) {
1870 $class = 'menu'.$name;
1871 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1872 $class = str_replace('[', '', $class);
1873 $class = str_replace(']', '', $class);
1874 $attributes['class'] = $class;
1876 $attributes['class'] = 'select custom-select ' . $attributes['class']; // Add 'select' selector always.
1878 $attributes['name'] = $name;
1880 if (!empty($attributes['disabled'])) {
1881 $attributes['disabled'] = 'disabled';
1883 unset($attributes['disabled']);
1887 foreach ($options as $value=>$label) {
1888 if (is_array($label)) {
1889 // ignore key, it just has to be unique
1890 $output .= self
::select_optgroup(key($label), current($label), $selected);
1892 $output .= self
::select_option($label, $value, $selected);
1895 return self
::tag('select', $output, $attributes);
1899 * Returns HTML to display a select box option.
1901 * @param string $label The label to display as the option.
1902 * @param string|int $value The value the option represents
1903 * @param array $selected An array of selected options
1904 * @return string HTML fragment
1906 private static function select_option($label, $value, array $selected) {
1907 $attributes = array();
1908 $value = (string)$value;
1909 if (in_array($value, $selected, true)) {
1910 $attributes['selected'] = 'selected';
1912 $attributes['value'] = $value;
1913 return self
::tag('option', $label, $attributes);
1917 * Returns HTML to display a select box option group.
1919 * @param string $groupname The label to use for the group
1920 * @param array $options The options in the group
1921 * @param array $selected An array of selected values.
1922 * @return string HTML fragment.
1924 private static function select_optgroup($groupname, $options, array $selected) {
1925 if (empty($options)) {
1928 $attributes = array('label'=>$groupname);
1930 foreach ($options as $value=>$label) {
1931 $output .= self
::select_option($label, $value, $selected);
1933 return self
::tag('optgroup', $output, $attributes);
1937 * This is a shortcut for making an hour selector menu.
1939 * @param string $type The type of selector (years, months, days, hours, minutes)
1940 * @param string $name fieldname
1941 * @param int $currenttime A default timestamp in GMT
1942 * @param int $step minute spacing
1943 * @param array $attributes - html select element attributes
1944 * @return HTML fragment
1946 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1949 if (!$currenttime) {
1950 $currenttime = time();
1952 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1953 $currentdate = $calendartype->timestamp_to_date_array($currenttime);
1954 $userdatetype = $type;
1955 $timeunits = array();
1959 $timeunits = $calendartype->get_years();
1960 $userdatetype = 'year';
1963 $timeunits = $calendartype->get_months();
1964 $userdatetype = 'month';
1965 $currentdate['month'] = (int)$currentdate['mon'];
1968 $timeunits = $calendartype->get_days();
1969 $userdatetype = 'mday';
1972 for ($i=0; $i<=23; $i++
) {
1973 $timeunits[$i] = sprintf("%02d",$i);
1978 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
1981 for ($i=0; $i<=59; $i+
=$step) {
1982 $timeunits[$i] = sprintf("%02d",$i);
1986 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
1989 $attributes = (array) $attributes;
1992 'id' => !empty($attributes['id']) ?
$attributes['id'] : self
::random_id('ts_'),
1993 'label' => get_string(substr($type, 0, -1), 'form'),
1994 'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) {
1996 'name' => $timeunits[$value],
1998 'selected' => $currentdate[$userdatetype] == $value
2000 }, array_keys($timeunits)),
2003 unset($attributes['id']);
2004 unset($attributes['name']);
2005 $data->attributes
= array_map(function($name) use ($attributes) {
2008 'value' => $attributes[$name]
2010 }, array_keys($attributes));
2012 return $OUTPUT->render_from_template('core/select_time', $data);
2016 * Shortcut for quick making of lists
2018 * Note: 'list' is a reserved keyword ;-)
2020 * @param array $items
2021 * @param array $attributes
2022 * @param string $tag ul or ol
2025 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
2026 $output = html_writer
::start_tag($tag, $attributes)."\n";
2027 foreach ($items as $item) {
2028 $output .= html_writer
::tag('li', $item)."\n";
2030 $output .= html_writer
::end_tag($tag);
2035 * Returns hidden input fields created from url parameters.
2037 * @param moodle_url $url
2038 * @param array $exclude list of excluded parameters
2039 * @return string HTML fragment
2041 public static function input_hidden_params(moodle_url
$url, array $exclude = null) {
2042 $exclude = (array)$exclude;
2043 $params = $url->params();
2044 foreach ($exclude as $key) {
2045 unset($params[$key]);
2049 foreach ($params as $key => $value) {
2050 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
2051 $output .= self
::empty_tag('input', $attributes)."\n";
2057 * Generate a script tag containing the the specified code.
2059 * @param string $jscode the JavaScript code
2060 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
2061 * @return string HTML, the code wrapped in <script> tags.
2063 public static function script($jscode, $url=null) {
2065 $attributes = array('type'=>'text/javascript');
2066 return self
::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n", $attributes) . "\n";
2069 $attributes = array('type'=>'text/javascript', 'src'=>$url);
2070 return self
::tag('script', '', $attributes) . "\n";
2078 * Renders HTML table
2080 * This method may modify the passed instance by adding some default properties if they are not set yet.
2081 * If this is not what you want, you should make a full clone of your data before passing them to this
2082 * method. In most cases this is not an issue at all so we do not clone by default for performance
2083 * and memory consumption reasons.
2085 * @param html_table $table data to be rendered
2086 * @return string HTML code
2088 public static function table(html_table
$table) {
2089 // prepare table data and populate missing properties with reasonable defaults
2090 if (!empty($table->align
)) {
2091 foreach ($table->align
as $key => $aa) {
2093 $table->align
[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
2095 $table->align
[$key] = null;
2099 if (!empty($table->size
)) {
2100 foreach ($table->size
as $key => $ss) {
2102 $table->size
[$key] = 'width:'. $ss .';';
2104 $table->size
[$key] = null;
2108 if (!empty($table->wrap
)) {
2109 foreach ($table->wrap
as $key => $ww) {
2111 $table->wrap
[$key] = 'white-space:nowrap;';
2113 $table->wrap
[$key] = '';
2117 if (!empty($table->head
)) {
2118 foreach ($table->head
as $key => $val) {
2119 if (!isset($table->align
[$key])) {
2120 $table->align
[$key] = null;
2122 if (!isset($table->size
[$key])) {
2123 $table->size
[$key] = null;
2125 if (!isset($table->wrap
[$key])) {
2126 $table->wrap
[$key] = null;
2131 if (empty($table->attributes
['class'])) {
2132 $table->attributes
['class'] = 'generaltable';
2134 if (!empty($table->tablealign
)) {
2135 $table->attributes
['class'] .= ' boxalign' . $table->tablealign
;
2138 // explicitly assigned properties override those defined via $table->attributes
2139 $table->attributes
['class'] = trim($table->attributes
['class']);
2140 $attributes = array_merge($table->attributes
, array(
2142 'width' => $table->width
,
2143 'summary' => $table->summary
,
2144 'cellpadding' => $table->cellpadding
,
2145 'cellspacing' => $table->cellspacing
,
2147 $output = html_writer
::start_tag('table', $attributes) . "\n";
2151 // Output a caption if present.
2152 if (!empty($table->caption
)) {
2153 $captionattributes = array();
2154 if ($table->captionhide
) {
2155 $captionattributes['class'] = 'accesshide';
2157 $output .= html_writer
::tag(
2164 if (!empty($table->head
)) {
2165 $countcols = count($table->head
);
2167 $output .= html_writer
::start_tag('thead', array()) . "\n";
2168 $output .= html_writer
::start_tag('tr', array()) . "\n";
2169 $keys = array_keys($table->head
);
2170 $lastkey = end($keys);
2172 foreach ($table->head
as $key => $heading) {
2173 // Convert plain string headings into html_table_cell objects
2174 if (!($heading instanceof html_table_cell
)) {
2175 $headingtext = $heading;
2176 $heading = new html_table_cell();
2177 $heading->text
= $headingtext;
2178 $heading->header
= true;
2181 if ($heading->header
!== false) {
2182 $heading->header
= true;
2185 if ($heading->header
&& empty($heading->scope
)) {
2186 $heading->scope
= 'col';
2189 $heading->attributes
['class'] .= ' header c' . $key;
2190 if (isset($table->headspan
[$key]) && $table->headspan
[$key] > 1) {
2191 $heading->colspan
= $table->headspan
[$key];
2192 $countcols +
= $table->headspan
[$key] - 1;
2195 if ($key == $lastkey) {
2196 $heading->attributes
['class'] .= ' lastcol';
2198 if (isset($table->colclasses
[$key])) {
2199 $heading->attributes
['class'] .= ' ' . $table->colclasses
[$key];
2201 $heading->attributes
['class'] = trim($heading->attributes
['class']);
2202 $attributes = array_merge($heading->attributes
, array(
2203 'style' => $table->align
[$key] . $table->size
[$key] . $heading->style
,
2204 'scope' => $heading->scope
,
2205 'colspan' => $heading->colspan
,
2209 if ($heading->header
=== true) {
2212 $output .= html_writer
::tag($tagtype, $heading->text
, $attributes) . "\n";
2214 $output .= html_writer
::end_tag('tr') . "\n";
2215 $output .= html_writer
::end_tag('thead') . "\n";
2217 if (empty($table->data
)) {
2218 // For valid XHTML strict every table must contain either a valid tr
2219 // or a valid tbody... both of which must contain a valid td
2220 $output .= html_writer
::start_tag('tbody', array('class' => 'empty'));
2221 $output .= html_writer
::tag('tr', html_writer
::tag('td', '', array('colspan'=>count($table->head
))));
2222 $output .= html_writer
::end_tag('tbody');
2226 if (!empty($table->data
)) {
2227 $keys = array_keys($table->data
);
2228 $lastrowkey = end($keys);
2229 $output .= html_writer
::start_tag('tbody', array());
2231 foreach ($table->data
as $key => $row) {
2232 if (($row === 'hr') && ($countcols)) {
2233 $output .= html_writer
::tag('td', html_writer
::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
2235 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
2236 if (!($row instanceof html_table_row
)) {
2237 $newrow = new html_table_row();
2239 foreach ($row as $cell) {
2240 if (!($cell instanceof html_table_cell
)) {
2241 $cell = new html_table_cell($cell);
2243 $newrow->cells
[] = $cell;
2248 if (isset($table->rowclasses
[$key])) {
2249 $row->attributes
['class'] .= ' ' . $table->rowclasses
[$key];
2252 if ($key == $lastrowkey) {
2253 $row->attributes
['class'] .= ' lastrow';
2256 // Explicitly assigned properties should override those defined in the attributes.
2257 $row->attributes
['class'] = trim($row->attributes
['class']);
2258 $trattributes = array_merge($row->attributes
, array(
2260 'style' => $row->style
,
2262 $output .= html_writer
::start_tag('tr', $trattributes) . "\n";
2263 $keys2 = array_keys($row->cells
);
2264 $lastkey = end($keys2);
2266 $gotlastkey = false; //flag for sanity checking
2267 foreach ($row->cells
as $key => $cell) {
2269 //This should never happen. Why do we have a cell after the last cell?
2270 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
2273 if (!($cell instanceof html_table_cell
)) {
2274 $mycell = new html_table_cell();
2275 $mycell->text
= $cell;
2279 if (($cell->header
=== true) && empty($cell->scope
)) {
2280 $cell->scope
= 'row';
2283 if (isset($table->colclasses
[$key])) {
2284 $cell->attributes
['class'] .= ' ' . $table->colclasses
[$key];
2287 $cell->attributes
['class'] .= ' cell c' . $key;
2288 if ($key == $lastkey) {
2289 $cell->attributes
['class'] .= ' lastcol';
2293 $tdstyle .= isset($table->align
[$key]) ?
$table->align
[$key] : '';
2294 $tdstyle .= isset($table->size
[$key]) ?
$table->size
[$key] : '';
2295 $tdstyle .= isset($table->wrap
[$key]) ?
$table->wrap
[$key] : '';
2296 $cell->attributes
['class'] = trim($cell->attributes
['class']);
2297 $tdattributes = array_merge($cell->attributes
, array(
2298 'style' => $tdstyle . $cell->style
,
2299 'colspan' => $cell->colspan
,
2300 'rowspan' => $cell->rowspan
,
2302 'abbr' => $cell->abbr
,
2303 'scope' => $cell->scope
,
2306 if ($cell->header
=== true) {
2309 $output .= html_writer
::tag($tagtype, $cell->text
, $tdattributes) . "\n";
2312 $output .= html_writer
::end_tag('tr') . "\n";
2314 $output .= html_writer
::end_tag('tbody') . "\n";
2316 $output .= html_writer
::end_tag('table') . "\n";
2322 * Renders form element label
2324 * By default, the label is suffixed with a label separator defined in the
2325 * current language pack (colon by default in the English lang pack).
2326 * Adding the colon can be explicitly disabled if needed. Label separators
2327 * are put outside the label tag itself so they are not read by
2328 * screenreaders (accessibility).
2330 * Parameter $for explicitly associates the label with a form control. When
2331 * set, the value of this attribute must be the same as the value of
2332 * the id attribute of the form control in the same document. When null,
2333 * the label being defined is associated with the control inside the label
2336 * @param string $text content of the label tag
2337 * @param string|null $for id of the element this label is associated with, null for no association
2338 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
2339 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
2340 * @return string HTML of the label element
2342 public static function label($text, $for, $colonize = true, array $attributes=array()) {
2343 if (!is_null($for)) {
2344 $attributes = array_merge($attributes, array('for' => $for));
2346 $text = trim($text);
2347 $label = self
::tag('label', $text, $attributes);
2349 // TODO MDL-12192 $colonize disabled for now yet
2350 // if (!empty($text) and $colonize) {
2351 // // the $text may end with the colon already, though it is bad string definition style
2352 // $colon = get_string('labelsep', 'langconfig');
2353 // if (!empty($colon)) {
2354 // $trimmed = trim($colon);
2355 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
2356 // //debugging('The label text should not end with colon or other label separator,
2357 // // please fix the string definition.', DEBUG_DEVELOPER);
2359 // $label .= $colon;
2368 * Combines a class parameter with other attributes. Aids in code reduction
2369 * because the class parameter is very frequently used.
2371 * If the class attribute is specified both in the attributes and in the
2372 * class parameter, the two values are combined with a space between.
2374 * @param string $class Optional CSS class (or classes as space-separated list)
2375 * @param array $attributes Optional other attributes as array
2376 * @return array Attributes (or null if still none)
2378 private static function add_class($class = '', array $attributes = null) {
2379 if ($class !== '') {
2380 $classattribute = array('class' => $class);
2382 if (array_key_exists('class', $attributes)) {
2383 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
2385 $attributes = $classattribute +
$attributes;
2388 $attributes = $classattribute;
2395 * Creates a <div> tag. (Shortcut function.)
2397 * @param string $content HTML content of tag
2398 * @param string $class Optional CSS class (or classes as space-separated list)
2399 * @param array $attributes Optional other attributes as array
2400 * @return string HTML code for div
2402 public static function div($content, $class = '', array $attributes = null) {
2403 return self
::tag('div', $content, self
::add_class($class, $attributes));
2407 * Starts a <div> tag. (Shortcut function.)
2409 * @param string $class Optional CSS class (or classes as space-separated list)
2410 * @param array $attributes Optional other attributes as array
2411 * @return string HTML code for open div tag
2413 public static function start_div($class = '', array $attributes = null) {
2414 return self
::start_tag('div', self
::add_class($class, $attributes));
2418 * Ends a <div> tag. (Shortcut function.)
2420 * @return string HTML code for close div tag
2422 public static function end_div() {
2423 return self
::end_tag('div');
2427 * Creates a <span> tag. (Shortcut function.)
2429 * @param string $content HTML content of tag
2430 * @param string $class Optional CSS class (or classes as space-separated list)
2431 * @param array $attributes Optional other attributes as array
2432 * @return string HTML code for span
2434 public static function span($content, $class = '', array $attributes = null) {
2435 return self
::tag('span', $content, self
::add_class($class, $attributes));
2439 * Starts a <span> tag. (Shortcut function.)
2441 * @param string $class Optional CSS class (or classes as space-separated list)
2442 * @param array $attributes Optional other attributes as array
2443 * @return string HTML code for open span tag
2445 public static function start_span($class = '', array $attributes = null) {
2446 return self
::start_tag('span', self
::add_class($class, $attributes));
2450 * Ends a <span> tag. (Shortcut function.)
2452 * @return string HTML code for close span tag
2454 public static function end_span() {
2455 return self
::end_tag('span');
2460 * Simple javascript output class
2462 * @copyright 2010 Petr Skoda
2463 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2471 * Returns javascript code calling the function
2473 * @param string $function function name, can be complex like Y.Event.purgeElement
2474 * @param array $arguments parameters
2475 * @param int $delay execution delay in seconds
2476 * @return string JS code fragment
2478 public static function function_call($function, array $arguments = null, $delay=0) {
2480 $arguments = array_map('json_encode', convert_to_array($arguments));
2481 $arguments = implode(', ', $arguments);
2485 $js = "$function($arguments);";
2488 $delay = $delay * 1000; // in miliseconds
2489 $js = "setTimeout(function() { $js }, $delay);";
2495 * Special function which adds Y as first argument of function call.
2497 * @param string $function The function to call
2498 * @param array $extraarguments Any arguments to pass to it
2499 * @return string Some JS code
2501 public static function function_call_with_Y($function, array $extraarguments = null) {
2502 if ($extraarguments) {
2503 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
2504 $arguments = 'Y, ' . implode(', ', $extraarguments);
2508 return "$function($arguments);\n";
2512 * Returns JavaScript code to initialise a new object
2514 * @param string $var If it is null then no var is assigned the new object.
2515 * @param string $class The class to initialise an object for.
2516 * @param array $arguments An array of args to pass to the init method.
2517 * @param array $requirements Any modules required for this class.
2518 * @param int $delay The delay before initialisation. 0 = no delay.
2519 * @return string Some JS code
2521 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
2522 if (is_array($arguments)) {
2523 $arguments = array_map('json_encode', convert_to_array($arguments));
2524 $arguments = implode(', ', $arguments);
2527 if ($var === null) {
2528 $js = "new $class(Y, $arguments);";
2529 } else if (strpos($var, '.')!==false) {
2530 $js = "$var = new $class(Y, $arguments);";
2532 $js = "var $var = new $class(Y, $arguments);";
2536 $delay = $delay * 1000; // in miliseconds
2537 $js = "setTimeout(function() { $js }, $delay);";
2540 if (count($requirements) > 0) {
2541 $requirements = implode("', '", $requirements);
2542 $js = "Y.use('$requirements', function(Y){ $js });";
2548 * Returns code setting value to variable
2550 * @param string $name
2551 * @param mixed $value json serialised value
2552 * @param bool $usevar add var definition, ignored for nested properties
2553 * @return string JS code fragment
2555 public static function set_variable($name, $value, $usevar = true) {
2559 if (strpos($name, '.')) {
2566 $output .= "$name = ".json_encode($value).";";
2572 * Writes event handler attaching code
2574 * @param array|string $selector standard YUI selector for elements, may be
2575 * array or string, element id is in the form "#idvalue"
2576 * @param string $event A valid DOM event (click, mousedown, change etc.)
2577 * @param string $function The name of the function to call
2578 * @param array $arguments An optional array of argument parameters to pass to the function
2579 * @return string JS code fragment
2581 public static function event_handler($selector, $event, $function, array $arguments = null) {
2582 $selector = json_encode($selector);
2583 $output = "Y.on('$event', $function, $selector, null";
2584 if (!empty($arguments)) {
2585 $output .= ', ' . json_encode($arguments);
2587 return $output . ");\n";
2592 * Holds all the information required to render a <table> by {@link core_renderer::table()}
2595 * $t = new html_table();
2596 * ... // set various properties of the object $t as described below
2597 * echo html_writer::table($t);
2599 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
2600 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2608 * @var string Value to use for the id attribute of the table
2613 * @var array Attributes of HTML attributes for the <table> element
2615 public $attributes = array();
2618 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
2619 * For more control over the rendering of the headers, an array of html_table_cell objects
2620 * can be passed instead of an array of strings.
2623 * $t->head = array('Student', 'Grade');
2628 * @var array An array that can be used to make a heading span multiple columns.
2629 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
2630 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
2633 * $t->headspan = array(2,1);
2638 * @var array An array of column alignments.
2639 * The value is used as CSS 'text-align' property. Therefore, possible
2640 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
2641 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
2643 * Examples of usage:
2644 * $t->align = array(null, 'right');
2646 * $t->align[1] = 'right';
2651 * @var array The value is used as CSS 'size' property.
2653 * Examples of usage:
2654 * $t->size = array('50%', '50%');
2656 * $t->size[1] = '120px';
2661 * @var array An array of wrapping information.
2662 * The only possible value is 'nowrap' that sets the
2663 * CSS property 'white-space' to the value 'nowrap' in the given column.
2666 * $t->wrap = array(null, 'nowrap');
2671 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2672 * $head specified, the string 'hr' (for horizontal ruler) can be used
2673 * instead of an array of cells data resulting in a divider rendered.
2675 * Example of usage with array of arrays:
2676 * $row1 = array('Harry Potter', '76 %');
2677 * $row2 = array('Hermione Granger', '100 %');
2678 * $t->data = array($row1, $row2);
2680 * Example with array of html_table_row objects: (used for more fine-grained control)
2681 * $cell1 = new html_table_cell();
2682 * $cell1->text = 'Harry Potter';
2683 * $cell1->colspan = 2;
2684 * $row1 = new html_table_row();
2685 * $row1->cells[] = $cell1;
2686 * $cell2 = new html_table_cell();
2687 * $cell2->text = 'Hermione Granger';
2688 * $cell3 = new html_table_cell();
2689 * $cell3->text = '100 %';
2690 * $row2 = new html_table_row();
2691 * $row2->cells = array($cell2, $cell3);
2692 * $t->data = array($row1, $row2);
2697 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2698 * @var string Width of the table, percentage of the page preferred.
2700 public $width = null;
2703 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2704 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2706 public $tablealign = null;
2709 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2710 * @var int Padding on each cell, in pixels
2712 public $cellpadding = null;
2715 * @var int Spacing between cells, in pixels
2716 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2718 public $cellspacing = null;
2721 * @var array Array of classes to add to particular rows, space-separated string.
2722 * Class 'lastrow' is added automatically for the last row in the table.
2725 * $t->rowclasses[9] = 'tenth'
2730 * @var array An array of classes to add to every cell in a particular column,
2731 * space-separated string. Class 'cell' is added automatically by the renderer.
2732 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2733 * respectively. Class 'lastcol' is added automatically for all last cells
2737 * $t->colclasses = array(null, 'grade');
2742 * @var string Description of the contents for screen readers.
2747 * @var string Caption for the table, typically a title.
2750 * $t->caption = "TV Guide";
2755 * @var bool Whether to hide the table's caption from sighted users.
2758 * $t->caption = "TV Guide";
2759 * $t->captionhide = true;
2761 public $captionhide = false;
2766 public function __construct() {
2767 $this->attributes
['class'] = '';
2772 * Component representing a table row.
2774 * @copyright 2009 Nicolas Connault
2775 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2780 class html_table_row
{
2783 * @var string Value to use for the id attribute of the row.
2788 * @var array Array of html_table_cell objects
2790 public $cells = array();
2793 * @var string Value to use for the style attribute of the table row
2795 public $style = null;
2798 * @var array Attributes of additional HTML attributes for the <tr> element
2800 public $attributes = array();
2804 * @param array $cells
2806 public function __construct(array $cells=null) {
2807 $this->attributes
['class'] = '';
2808 $cells = (array)$cells;
2809 foreach ($cells as $cell) {
2810 if ($cell instanceof html_table_cell
) {
2811 $this->cells
[] = $cell;
2813 $this->cells
[] = new html_table_cell($cell);
2820 * Component representing a table cell.
2822 * @copyright 2009 Nicolas Connault
2823 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2828 class html_table_cell
{
2831 * @var string Value to use for the id attribute of the cell.
2836 * @var string The contents of the cell.
2841 * @var string Abbreviated version of the contents of the cell.
2843 public $abbr = null;
2846 * @var int Number of columns this cell should span.
2848 public $colspan = null;
2851 * @var int Number of rows this cell should span.
2853 public $rowspan = null;
2856 * @var string Defines a way to associate header cells and data cells in a table.
2858 public $scope = null;
2861 * @var bool Whether or not this cell is a header cell.
2863 public $header = null;
2866 * @var string Value to use for the style attribute of the table cell
2868 public $style = null;
2871 * @var array Attributes of additional HTML attributes for the <td> element
2873 public $attributes = array();
2876 * Constructs a table cell
2878 * @param string $text
2880 public function __construct($text = null) {
2881 $this->text
= $text;
2882 $this->attributes
['class'] = '';
2887 * Component representing a paging bar.
2889 * @copyright 2009 Nicolas Connault
2890 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2895 class paging_bar
implements renderable
, templatable
{
2898 * @var int The maximum number of pagelinks to display.
2900 public $maxdisplay = 18;
2903 * @var int The total number of entries to be pages through..
2908 * @var int The page you are currently viewing.
2913 * @var int The number of entries that should be shown per page.
2918 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2919 * an equals sign and the page number.
2920 * If this is a moodle_url object then the pagevar param will be replaced by
2921 * the page no, for each page.
2926 * @var string This is the variable name that you use for the pagenumber in your
2927 * code (ie. 'tablepage', 'blogpage', etc)
2932 * @var string A HTML link representing the "previous" page.
2934 public $previouslink = null;
2937 * @var string A HTML link representing the "next" page.
2939 public $nextlink = null;
2942 * @var string A HTML link representing the first page.
2944 public $firstlink = null;
2947 * @var string A HTML link representing the last page.
2949 public $lastlink = null;
2952 * @var array An array of strings. One of them is just a string: the current page
2954 public $pagelinks = array();
2957 * Constructor paging_bar with only the required params.
2959 * @param int $totalcount The total number of entries available to be paged through
2960 * @param int $page The page you are currently viewing
2961 * @param int $perpage The number of entries that should be shown per page
2962 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2963 * @param string $pagevar name of page parameter that holds the page number
2965 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2966 $this->totalcount
= $totalcount;
2967 $this->page
= $page;
2968 $this->perpage
= $perpage;
2969 $this->baseurl
= $baseurl;
2970 $this->pagevar
= $pagevar;
2974 * Prepares the paging bar for output.
2976 * This method validates the arguments set up for the paging bar and then
2977 * produces fragments of HTML to assist display later on.
2979 * @param renderer_base $output
2980 * @param moodle_page $page
2981 * @param string $target
2982 * @throws coding_exception
2984 public function prepare(renderer_base
$output, moodle_page
$page, $target) {
2985 if (!isset($this->totalcount
) ||
is_null($this->totalcount
)) {
2986 throw new coding_exception('paging_bar requires a totalcount value.');
2988 if (!isset($this->page
) ||
is_null($this->page
)) {
2989 throw new coding_exception('paging_bar requires a page value.');
2991 if (empty($this->perpage
)) {
2992 throw new coding_exception('paging_bar requires a perpage value.');
2994 if (empty($this->baseurl
)) {
2995 throw new coding_exception('paging_bar requires a baseurl value.');
2998 if ($this->totalcount
> $this->perpage
) {
2999 $pagenum = $this->page
- 1;
3001 if ($this->page
> 0) {
3002 $this->previouslink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$pagenum)), get_string('previous'), array('class'=>'previous'));
3005 if ($this->perpage
> 0) {
3006 $lastpage = ceil($this->totalcount
/ $this->perpage
);
3011 if ($this->page
> round(($this->maxdisplay
/3)*2)) {
3012 $currpage = $this->page
- round($this->maxdisplay
/3);
3014 $this->firstlink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>0)), '1', array('class'=>'first'));
3019 $displaycount = $displaypage = 0;
3021 while ($displaycount < $this->maxdisplay
and $currpage < $lastpage) {
3022 $displaypage = $currpage +
1;
3024 if ($this->page
== $currpage) {
3025 $this->pagelinks
[] = html_writer
::span($displaypage, 'current-page');
3027 $pagelink = html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$currpage)), $displaypage);
3028 $this->pagelinks
[] = $pagelink;
3035 if ($currpage < $lastpage) {
3036 $lastpageactual = $lastpage - 1;
3037 $this->lastlink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$lastpageactual)), $lastpage, array('class'=>'last'));
3040 $pagenum = $this->page +
1;
3042 if ($pagenum != $lastpage) {
3043 $this->nextlink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$pagenum)), get_string('next'), array('class'=>'next'));
3049 * Export for template.
3051 * @param renderer_base $output The renderer.
3054 public function export_for_template(renderer_base
$output) {
3055 $data = new stdClass();
3056 $data->previous
= null;
3058 $data->first
= null;
3060 $data->label
= get_string('page');
3062 $data->haspages
= $this->totalcount
> $this->perpage
;
3064 if (!$data->haspages
) {
3068 if ($this->page
> 0) {
3070 'page' => $this->page
- 1,
3071 'url' => (new moodle_url($this->baseurl
, [$this->pagevar
=> $this->page
- 1]))->out(false)
3076 if ($this->page
> round(($this->maxdisplay
/ 3) * 2)) {
3077 $currpage = $this->page
- round($this->maxdisplay
/ 3);
3080 'url' => (new moodle_url($this->baseurl
, [$this->pagevar
=> 0]))->out(false)
3085 if ($this->perpage
> 0) {
3086 $lastpage = ceil($this->totalcount
/ $this->perpage
);
3091 while ($displaycount < $this->maxdisplay
and $currpage < $lastpage) {
3092 $displaypage = $currpage +
1;
3094 $iscurrent = $this->page
== $currpage;
3095 $link = new moodle_url($this->baseurl
, [$this->pagevar
=> $currpage]);
3098 'page' => $displaypage,
3099 'active' => $iscurrent,
3100 'url' => $iscurrent ?
null : $link->out(false)
3107 if ($currpage < $lastpage) {
3109 'page' => $lastpage,
3110 'url' => (new moodle_url($this->baseurl
, [$this->pagevar
=> $lastpage - 1]))->out(false)
3114 if ($this->page +
1 != $lastpage) {
3116 'page' => $this->page +
1,
3117 'url' => (new moodle_url($this->baseurl
, [$this->pagevar
=> $this->page +
1]))->out(false)
3126 * Component representing initials bar.
3128 * @copyright 2017 Ilya Tregubov
3129 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3134 class initials_bar
implements renderable
, templatable
{
3137 * @var string Currently selected letter.
3142 * @var string Class name to add to this initial bar.
3147 * @var string The name to put in front of this initial bar.
3152 * @var string URL parameter name for this initial.
3157 * @var string URL object.
3162 * @var array An array of letters in the alphabet.
3167 * Constructor initials_bar with only the required params.
3169 * @param string $current the currently selected letter.
3170 * @param string $class class name to add to this initial bar.
3171 * @param string $title the name to put in front of this initial bar.
3172 * @param string $urlvar URL parameter name for this initial.
3173 * @param string $url URL object.
3174 * @param array $alpha of letters in the alphabet.
3176 public function __construct($current, $class, $title, $urlvar, $url, $alpha = null) {
3177 $this->current
= $current;
3178 $this->class = $class;
3179 $this->title
= $title;
3180 $this->urlvar
= $urlvar;
3182 $this->alpha
= $alpha;
3186 * Export for template.
3188 * @param renderer_base $output The renderer.
3191 public function export_for_template(renderer_base
$output) {
3192 $data = new stdClass();
3194 if ($this->alpha
== null) {
3195 $this->alpha
= explode(',', get_string('alphabet', 'langconfig'));
3198 if ($this->current
== 'all') {
3199 $this->current
= '';
3202 // We want to find a letter grouping size which suits the language so
3203 // find the largest group size which is less than 15 chars.
3204 // The choice of 15 chars is the largest number of chars that reasonably
3205 // fits on the smallest supported screen size. By always using a max number
3206 // of groups which is a factor of 2, we always get nice wrapping, and the
3207 // last row is always the shortest.
3208 $groupsize = count($this->alpha
);
3210 while ($groupsize > 15) {
3212 $groupsize = ceil(count($this->alpha
) / $groups);
3215 $groupsizelimit = 0;
3217 foreach ($this->alpha
as $letter) {
3218 if ($groupsizelimit++
> 0 && $groupsizelimit %
$groupsize == 1) {
3221 $groupletter = new stdClass();
3222 $groupletter->name
= $letter;
3223 $groupletter->url
= $this->url
->out(false, array($this->urlvar
=> $letter));
3224 if ($letter == $this->current
) {
3225 $groupletter->selected
= $this->current
;
3227 $data->group
[$groupnumber]->letter
[] = $groupletter;
3230 $data->class = $this->class;
3231 $data->title
= $this->title
;
3232 $data->url
= $this->url
->out(false, array($this->urlvar
=> ''));
3233 $data->current
= $this->current
;
3234 $data->all
= get_string('all');
3241 * This class represents how a block appears on a page.
3243 * During output, each block instance is asked to return a block_contents object,
3244 * those are then passed to the $OUTPUT->block function for display.
3246 * contents should probably be generated using a moodle_block_..._renderer.
3248 * Other block-like things that need to appear on the page, for example the
3249 * add new block UI, are also represented as block_contents objects.
3251 * @copyright 2009 Tim Hunt
3252 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3257 class block_contents
{
3259 /** Used when the block cannot be collapsed **/
3260 const NOT_HIDEABLE
= 0;
3262 /** Used when the block can be collapsed but currently is not **/
3265 /** Used when the block has been collapsed **/
3269 * @var int Used to set $skipid.
3271 protected static $idcounter = 1;
3274 * @var int All the blocks (or things that look like blocks) printed on
3275 * a page are given a unique number that can be used to construct id="" attributes.
3276 * This is set automatically be the {@link prepare()} method.
3277 * Do not try to set it manually.
3282 * @var int If this is the contents of a real block, this should be set
3283 * to the block_instance.id. Otherwise this should be set to 0.
3285 public $blockinstanceid = 0;
3288 * @var int If this is a real block instance, and there is a corresponding
3289 * block_position.id for the block on this page, this should be set to that id.
3290 * Otherwise it should be 0.
3292 public $blockpositionid = 0;
3295 * @var array An array of attribute => value pairs that are put on the outer div of this
3296 * block. {@link $id} and {@link $classes} attributes should be set separately.
3301 * @var string The title of this block. If this came from user input, it should already
3302 * have had format_string() processing done on it. This will be output inside
3303 * <h2> tags. Please do not cause invalid XHTML.
3308 * @var string The label to use when the block does not, or will not have a visible title.
3309 * You should never set this as well as title... it will just be ignored.
3311 public $arialabel = '';
3314 * @var string HTML for the content
3316 public $content = '';
3319 * @var array An alternative to $content, it you want a list of things with optional icons.
3321 public $footer = '';
3324 * @var string Any small print that should appear under the block to explain
3325 * to the teacher about the block, for example 'This is a sticky block that was
3326 * added in the system context.'
3328 public $annotation = '';
3331 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
3332 * the user can toggle whether this block is visible.
3334 public $collapsible = self
::NOT_HIDEABLE
;
3337 * Set this to true if the block is dockable.
3340 public $dockable = false;
3343 * @var array A (possibly empty) array of editing controls. Each element of
3344 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
3345 * $icon is the icon name. Fed to $OUTPUT->image_url.
3347 public $controls = array();
3351 * Create new instance of block content
3352 * @param array $attributes
3354 public function __construct(array $attributes = null) {
3355 $this->skipid
= self
::$idcounter;
3356 self
::$idcounter +
= 1;
3360 $this->attributes
= $attributes;
3362 // simple "fake" blocks used in some modules and "Add new block" block
3363 $this->attributes
= array('class'=>'block');
3368 * Add html class to block
3370 * @param string $class
3372 public function add_class($class) {
3373 $this->attributes
['class'] .= ' '.$class;
3379 * This class represents a target for where a block can go when it is being moved.
3381 * This needs to be rendered as a form with the given hidden from fields, and
3382 * clicking anywhere in the form should submit it. The form action should be
3385 * @copyright 2009 Tim Hunt
3386 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3391 class block_move_target
{
3394 * @var moodle_url Move url
3400 * @param moodle_url $url
3402 public function __construct(moodle_url
$url) {
3410 * This class is used to represent one item within a custom menu that may or may
3411 * not have children.
3413 * @copyright 2010 Sam Hemelryk
3414 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3419 class custom_menu_item
implements renderable
, templatable
{
3422 * @var string The text to show for the item
3427 * @var moodle_url The link to give the icon if it has no children
3432 * @var string A title to apply to the item. By default the text
3437 * @var int A sort order for the item, not necessary if you order things in
3443 * @var custom_menu_item A reference to the parent for this item or NULL if
3444 * it is a top level item
3449 * @var array A array in which to store children this item has.
3451 protected $children = array();
3454 * @var int A reference to the sort var of the last child that was added
3456 protected $lastsort = 0;
3459 * Constructs the new custom menu item
3461 * @param string $text
3462 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
3463 * @param string $title A title to apply to this item [Optional]
3464 * @param int $sort A sort or to use if we need to sort differently [Optional]
3465 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
3466 * belongs to, only if the child has a parent. [Optional]
3468 public function __construct($text, moodle_url
$url=null, $title=null, $sort = null, custom_menu_item
$parent = null) {
3469 $this->text
= $text;
3471 $this->title
= $title;
3472 $this->sort
= (int)$sort;
3473 $this->parent
= $parent;
3477 * Adds a custom menu item as a child of this node given its properties.
3479 * @param string $text
3480 * @param moodle_url $url
3481 * @param string $title
3483 * @return custom_menu_item
3485 public function add($text, moodle_url
$url = null, $title = null, $sort = null) {
3486 $key = count($this->children
);
3488 $sort = $this->lastsort +
1;
3490 $this->children
[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
3491 $this->lastsort
= (int)$sort;
3492 return $this->children
[$key];
3496 * Removes a custom menu item that is a child or descendant to the current menu.
3498 * Returns true if child was found and removed.
3500 * @param custom_menu_item $menuitem
3503 public function remove_child(custom_menu_item
$menuitem) {
3505 if (($key = array_search($menuitem, $this->children
)) !== false) {
3506 unset($this->children
[$key]);
3507 $this->children
= array_values($this->children
);
3510 foreach ($this->children
as $child) {
3511 if ($removed = $child->remove_child($menuitem)) {
3520 * Returns the text for this item
3523 public function get_text() {
3528 * Returns the url for this item
3529 * @return moodle_url
3531 public function get_url() {
3536 * Returns the title for this item
3539 public function get_title() {
3540 return $this->title
;
3544 * Sorts and returns the children for this item
3547 public function get_children() {
3549 return $this->children
;
3553 * Gets the sort order for this child
3556 public function get_sort_order() {
3561 * Gets the parent this child belong to
3562 * @return custom_menu_item
3564 public function get_parent() {
3565 return $this->parent
;
3569 * Sorts the children this item has
3571 public function sort() {
3572 usort($this->children
, array('custom_menu','sort_custom_menu_items'));
3576 * Returns true if this item has any children
3579 public function has_children() {
3580 return (count($this->children
) > 0);
3584 * Sets the text for the node
3585 * @param string $text
3587 public function set_text($text) {
3588 $this->text
= (string)$text;
3592 * Sets the title for the node
3593 * @param string $title
3595 public function set_title($title) {
3596 $this->title
= (string)$title;
3600 * Sets the url for the node
3601 * @param moodle_url $url
3603 public function set_url(moodle_url
$url) {
3608 * Export this data so it can be used as the context for a mustache template.
3610 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
3613 public function export_for_template(renderer_base
$output) {
3616 require_once($CFG->libdir
. '/externallib.php');
3618 $syscontext = context_system
::instance();
3620 $context = new stdClass();
3621 $context->text
= external_format_string($this->text
, $syscontext->id
);
3622 $context->url
= $this->url ?
$this->url
->out() : null;
3623 $context->title
= external_format_string($this->title
, $syscontext->id
);
3624 $context->sort
= $this->sort
;
3625 $context->children
= array();
3626 if (preg_match("/^#+$/", $this->text
)) {
3627 $context->divider
= true;
3629 $context->haschildren
= !empty($this->children
) && (count($this->children
) > 0);
3630 foreach ($this->children
as $child) {
3631 $child = $child->export_for_template($output);
3632 array_push($context->children
, $child);
3642 * This class is used to operate a custom menu that can be rendered for the page.
3643 * The custom menu is built using $CFG->custommenuitems and is a structured collection
3644 * of custom_menu_item nodes that can be rendered by the core renderer.
3646 * To configure the custom menu:
3647 * Settings: Administration > Appearance > Themes > Theme settings
3649 * @copyright 2010 Sam Hemelryk
3650 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3655 class custom_menu
extends custom_menu_item
{
3658 * @var string The language we should render for, null disables multilang support.
3660 protected $currentlanguage = null;
3663 * Creates the custom menu
3665 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
3666 * @param string $currentlanguage the current language code, null disables multilang support
3668 public function __construct($definition = '', $currentlanguage = null) {
3669 $this->currentlanguage
= $currentlanguage;
3670 parent
::__construct('root'); // create virtual root element of the menu
3671 if (!empty($definition)) {
3672 $this->override_children(self
::convert_text_to_menu_nodes($definition, $currentlanguage));
3677 * Overrides the children of this custom menu. Useful when getting children
3678 * from $CFG->custommenuitems
3680 * @param array $children
3682 public function override_children(array $children) {
3683 $this->children
= array();
3684 foreach ($children as $child) {
3685 if ($child instanceof custom_menu_item
) {
3686 $this->children
[] = $child;
3692 * Converts a string into a structured array of custom_menu_items which can
3693 * then be added to a custom menu.
3696 * text|url|title|langs
3697 * The number of hyphens at the start determines the depth of the item. The
3698 * languages are optional, comma separated list of languages the line is for.
3700 * Example structure:
3701 * First level first item|http://www.moodle.com/
3702 * -Second level first item|http://www.moodle.com/partners/
3703 * -Second level second item|http://www.moodle.com/hq/
3704 * --Third level first item|http://www.moodle.com/jobs/
3705 * -Second level third item|http://www.moodle.com/development/
3706 * First level second item|http://www.moodle.com/feedback/
3707 * First level third item
3708 * English only|http://moodle.com|English only item|en
3709 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
3713 * @param string $text the menu items definition
3714 * @param string $language the language code, null disables multilang support
3717 public static function convert_text_to_menu_nodes($text, $language = null) {
3718 $root = new custom_menu();
3721 $hiddenitems = array();
3722 $lines = explode("\n", $text);
3723 foreach ($lines as $linenumber => $line) {
3724 $line = trim($line);
3725 if (strlen($line) == 0) {
3728 // Parse item settings.
3732 $itemvisible = true;
3733 $settings = explode('|', $line);
3734 foreach ($settings as $i => $setting) {
3735 $setting = trim($setting);
3736 if (!empty($setting)) {
3739 $itemtext = ltrim($setting, '-');
3740 $itemtitle = $itemtext;
3744 $itemurl = new moodle_url($setting);
3745 } catch (moodle_exception
$exception) {
3746 // We're not actually worried about this, we don't want to mess up the display
3747 // just for a wrongly entered URL.
3752 $itemtitle = $setting;
3755 if (!empty($language)) {
3756 $itemlanguages = array_map('trim', explode(',', $setting));
3757 $itemvisible &= in_array($language, $itemlanguages);
3763 // Get depth of new item.
3764 preg_match('/^(\-*)/', $line, $match);
3765 $itemdepth = strlen($match[1]) +
1;
3766 // Find parent item for new item.
3767 while (($lastdepth - $itemdepth) >= 0) {
3768 $lastitem = $lastitem->get_parent();
3771 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber +
1);
3773 if (!$itemvisible) {
3774 $hiddenitems[] = $lastitem;
3777 foreach ($hiddenitems as $item) {
3778 $item->parent
->remove_child($item);
3780 return $root->get_children();
3784 * Sorts two custom menu items
3786 * This function is designed to be used with the usort method
3787 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
3790 * @param custom_menu_item $itema
3791 * @param custom_menu_item $itemb
3794 public static function sort_custom_menu_items(custom_menu_item
$itema, custom_menu_item
$itemb) {
3795 $itema = $itema->get_sort_order();
3796 $itemb = $itemb->get_sort_order();
3797 if ($itema == $itemb) {
3800 return ($itema > $itemb) ? +
1 : -1;
3807 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3810 class tabobject
implements renderable
, templatable
{
3811 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
3813 /** @var moodle_url|string link */
3815 /** @var string text on the tab */
3817 /** @var string title under the link, by defaul equals to text */
3819 /** @var bool whether to display a link under the tab name when it's selected */
3820 var $linkedwhenselected = false;
3821 /** @var bool whether the tab is inactive */
3822 var $inactive = false;
3823 /** @var bool indicates that this tab's child is selected */
3824 var $activated = false;
3825 /** @var bool indicates that this tab is selected */
3826 var $selected = false;
3827 /** @var array stores children tabobjects */
3828 var $subtree = array();
3829 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
3835 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
3836 * @param string|moodle_url $link
3837 * @param string $text text on the tab
3838 * @param string $title title under the link, by defaul equals to text
3839 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
3841 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
3843 $this->link
= $link;
3844 $this->text
= $text;
3845 $this->title
= $title ?
$title : $text;
3846 $this->linkedwhenselected
= $linkedwhenselected;
3850 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
3852 * @param string $selected the id of the selected tab (whatever row it's on),
3853 * if null marks all tabs as unselected
3854 * @return bool whether this tab is selected or contains selected tab in its subtree
3856 protected function set_selected($selected) {
3857 if ((string)$selected === (string)$this->id
) {
3858 $this->selected
= true;
3859 // This tab is selected. No need to travel through subtree.
3862 foreach ($this->subtree
as $subitem) {
3863 if ($subitem->set_selected($selected)) {
3864 // This tab has child that is selected. Mark it as activated. No need to check other children.
3865 $this->activated
= true;
3873 * Travels through tree and finds a tab with specified id
3876 * @return tabtree|null
3878 public function find($id) {
3879 if ((string)$this->id
=== (string)$id) {
3882 foreach ($this->subtree
as $tab) {
3883 if ($obj = $tab->find($id)) {
3891 * Allows to mark each tab's level in the tree before rendering.
3895 protected function set_level($level) {
3896 $this->level
= $level;
3897 foreach ($this->subtree
as $tab) {
3898 $tab->set_level($level +
1);
3903 * Export for template.
3905 * @param renderer_base $output Renderer.
3908 public function export_for_template(renderer_base
$output) {
3909 if ($this->inactive ||
($this->selected
&& !$this->linkedwhenselected
) ||
$this->activated
) {
3912 $link = $this->link
;
3914 $active = $this->activated ||
$this->selected
;
3918 'link' => is_object($link) ?
$link->out(false) : $link,
3919 'text' => $this->text
,
3920 'title' => $this->title
,
3921 'inactive' => !$active && $this->inactive
,
3922 'active' => $active,
3923 'level' => $this->level
,
3930 * Renderable for the main page header.
3935 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
3936 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3938 class context_header
implements renderable
{
3941 * @var string $heading Main heading.
3945 * @var int $headinglevel Main heading 'h' tag level.
3947 public $headinglevel;
3949 * @var string|null $imagedata HTML code for the picture in the page header.
3953 * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
3954 * array elements - title => alternate text for the image, or if no image is available the button text.
3955 * url => Link for the button to head to. Should be a moodle_url.
3956 * image => location to the image, or name of the image in /pix/t/{image name}.
3957 * linkattributes => additional attributes for the <a href> element.
3958 * page => page object. Don't include if the image is an external image.
3960 public $additionalbuttons;
3965 * @param string $heading Main heading data.
3966 * @param int $headinglevel Main heading 'h' tag level.
3967 * @param string|null $imagedata HTML code for the picture in the page header.
3968 * @param string $additionalbuttons Buttons for the header e.g. Messaging button for the user header.
3970 public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null) {
3972 $this->heading
= $heading;
3973 $this->headinglevel
= $headinglevel;
3974 $this->imagedata
= $imagedata;
3975 $this->additionalbuttons
= $additionalbuttons;
3976 // If we have buttons then format them.
3977 if (isset($this->additionalbuttons
)) {
3978 $this->format_button_images();
3983 * Adds an array element for a formatted image.
3985 protected function format_button_images() {
3987 foreach ($this->additionalbuttons
as $buttontype => $button) {
3988 $page = $button['page'];
3989 // If no image is provided then just use the title.
3990 if (!isset($button['image'])) {
3991 $this->additionalbuttons
[$buttontype]['formattedimage'] = $button['title'];
3993 // Check to see if this is an internal Moodle icon.
3994 $internalimage = $page->theme
->resolve_image_location('t/' . $button['image'], 'moodle');
3995 if ($internalimage) {
3996 $this->additionalbuttons
[$buttontype]['formattedimage'] = 't/' . $button['image'];
3998 // Treat as an external image.
3999 $this->additionalbuttons
[$buttontype]['formattedimage'] = $button['image'];
4003 if (isset($button['linkattributes']['class'])) {
4004 $class = $button['linkattributes']['class'] . ' btn';
4008 // Add the bootstrap 'btn' class for formatting.
4009 $this->additionalbuttons
[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
4010 array('class' => $class));
4018 * Example how to print a single line tabs:
4020 * new tabobject(...),
4021 * new tabobject(...)
4023 * echo $OUTPUT->tabtree($rows, $selectedid);
4025 * Multiple row tabs may not look good on some devices but if you want to use them
4026 * you can specify ->subtree for the active tabobject.
4028 * @copyright 2013 Marina Glancy
4029 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4034 class tabtree
extends tabobject
{
4038 * It is highly recommended to call constructor when list of tabs is already
4039 * populated, this way you ensure that selected and inactive tabs are located
4040 * and attribute level is set correctly.
4042 * @param array $tabs array of tabs, each of them may have it's own ->subtree
4043 * @param string|null $selected which tab to mark as selected, all parent tabs will
4044 * automatically be marked as activated
4045 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4046 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
4048 public function __construct($tabs, $selected = null, $inactive = null) {
4049 $this->subtree
= $tabs;
4050 if ($selected !== null) {
4051 $this->set_selected($selected);
4053 if ($inactive !== null) {
4054 if (is_array($inactive)) {
4055 foreach ($inactive as $id) {
4056 if ($tab = $this->find($id)) {
4057 $tab->inactive
= true;
4060 } else if ($tab = $this->find($inactive)) {
4061 $tab->inactive
= true;
4064 $this->set_level(0);
4068 * Export for template.
4070 * @param renderer_base $output Renderer.
4073 public function export_for_template(renderer_base
$output) {
4077 foreach ($this->subtree
as $tab) {
4078 $tabs[] = $tab->export_for_template($output);
4079 if (!empty($tab->subtree
) && ($tab->level
== 0 ||
$tab->selected ||
$tab->activated
)) {
4080 $secondrow = new tabtree($tab->subtree
);
4086 'secondrow' => $secondrow ?
$secondrow->export_for_template($output) : false
4094 * This action menu component takes a series of primary and secondary actions.
4095 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
4100 * @copyright 2013 Sam Hemelryk
4101 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4103 class action_menu
implements renderable
, templatable
{
4106 * Top right alignment.
4111 * Top right alignment.
4116 * Top right alignment.
4121 * Top right alignment.
4126 * The instance number. This is unique to this instance of the action menu.
4129 protected $instance = 0;
4132 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
4135 protected $primaryactions = array();
4138 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
4141 protected $secondaryactions = array();
4144 * An array of attributes added to the container of the action menu.
4145 * Initialised with defaults during construction.
4148 public $attributes = array();
4150 * An array of attributes added to the container of the primary actions.
4151 * Initialised with defaults during construction.
4154 public $attributesprimary = array();
4156 * An array of attributes added to the container of the secondary actions.
4157 * Initialised with defaults during construction.
4160 public $attributessecondary = array();
4163 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
4166 public $actiontext = null;
4169 * The string to use for the accessible label for the menu.
4172 public $actionlabel = null;
4175 * An icon to use for the toggling the secondary menu (dropdown).
4181 * Any text to use for the toggling the secondary menu (dropdown).
4184 public $menutrigger = '';
4187 * Any extra classes for toggling to the secondary menu.
4188 * @var triggerextraclasses
4190 public $triggerextraclasses = '';
4193 * Place the action menu before all other actions.
4196 public $prioritise = false;
4199 * Constructs the action menu with the given items.
4201 * @param array $actions An array of actions.
4203 public function __construct(array $actions = array()) {
4204 static $initialised = 0;
4205 $this->instance
= $initialised;
4208 $this->attributes
= array(
4209 'id' => 'action-menu-'.$this->instance
,
4210 'class' => 'moodle-actionmenu',
4211 'data-enhance' => 'moodle-core-actionmenu'
4213 $this->attributesprimary
= array(
4214 'id' => 'action-menu-'.$this->instance
.'-menubar',
4215 'class' => 'menubar',
4218 $this->attributessecondary
= array(
4219 'id' => 'action-menu-'.$this->instance
.'-menu',
4221 'data-rel' => 'menu-content',
4222 'aria-labelledby' => 'action-menu-toggle-'.$this->instance
,
4225 $this->set_alignment(self
::TR
, self
::BR
);
4226 foreach ($actions as $action) {
4227 $this->add($action);
4232 * Sets the label for the menu trigger.
4234 * @param string $label The text
4237 public function set_action_label($label) {
4238 $this->actionlabel
= $label;
4242 * Sets the menu trigger text.
4244 * @param string $trigger The text
4245 * @param string $extraclasses Extra classes to style the secondary menu toggle.
4248 public function set_menu_trigger($trigger, $extraclasses = '') {
4249 $this->menutrigger
= $trigger;
4250 $this->triggerextraclasses
= $extraclasses;
4254 * Return true if there is at least one visible link in the menu.
4258 public function is_empty() {
4259 return !count($this->primaryactions
) && !count($this->secondaryactions
);
4263 * Initialises JS required fore the action menu.
4264 * The JS is only required once as it manages all action menu's on the page.
4266 * @param moodle_page $page
4268 public function initialise_js(moodle_page
$page) {
4269 static $initialised = false;
4270 if (!$initialised) {
4271 $page->requires
->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
4272 $initialised = true;
4277 * Adds an action to this action menu.
4279 * @param action_menu_link|pix_icon|string $action
4281 public function add($action) {
4282 if ($action instanceof action_link
) {
4283 if ($action->primary
) {
4284 $this->add_primary_action($action);
4286 $this->add_secondary_action($action);
4288 } else if ($action instanceof pix_icon
) {
4289 $this->add_primary_action($action);
4291 $this->add_secondary_action($action);
4296 * Adds a primary action to the action menu.
4298 * @param action_menu_link|action_link|pix_icon|string $action
4300 public function add_primary_action($action) {
4301 if ($action instanceof action_link ||
$action instanceof pix_icon
) {
4302 $action->attributes
['role'] = 'menuitem';
4303 if ($action instanceof action_menu_link
) {
4304 $action->actionmenu
= $this;
4307 $this->primaryactions
[] = $action;
4311 * Adds a secondary action to the action menu.
4313 * @param action_link|pix_icon|string $action
4315 public function add_secondary_action($action) {
4316 if ($action instanceof action_link ||
$action instanceof pix_icon
) {
4317 $action->attributes
['role'] = 'menuitem';
4318 if ($action instanceof action_menu_link
) {
4319 $action->actionmenu
= $this;
4322 $this->secondaryactions
[] = $action;
4326 * Returns the primary actions ready to be rendered.
4328 * @param core_renderer $output The renderer to use for getting icons.
4331 public function get_primary_actions(core_renderer
$output = null) {
4333 if ($output === null) {
4336 $pixicon = $this->actionicon
;
4337 $linkclasses = array('toggle-display');
4340 if (!empty($this->menutrigger
)) {
4341 $pixicon = '<b class="caret"></b>';
4342 $linkclasses[] = 'textmenu';
4344 $title = new lang_string('actionsmenu', 'moodle');
4345 $this->actionicon
= new pix_icon(
4349 array('class' => 'iconsmall actionmenu', 'title' => '')
4351 $pixicon = $this->actionicon
;
4353 if ($pixicon instanceof renderable
) {
4354 $pixicon = $output->render($pixicon);
4355 if ($pixicon instanceof pix_icon
&& isset($pixicon->attributes
['alt'])) {
4356 $title = $pixicon->attributes
['alt'];
4360 if ($this->actiontext
) {
4361 $string = $this->actiontext
;
4364 if ($this->actionlabel
) {
4365 $label = $this->actionlabel
;
4369 $actions = $this->primaryactions
;
4370 $attributes = array(
4371 'class' => implode(' ', $linkclasses),
4373 'aria-label' => $label,
4374 'id' => 'action-menu-toggle-'.$this->instance
,
4375 'role' => 'menuitem'
4377 $link = html_writer
::link('#', $string . $this->menutrigger
. $pixicon, $attributes);
4378 if ($this->prioritise
) {
4379 array_unshift($actions, $link);
4387 * Returns the secondary actions ready to be rendered.
4390 public function get_secondary_actions() {
4391 return $this->secondaryactions
;
4395 * Sets the selector that should be used to find the owning node of this menu.
4396 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
4398 public function set_owner_selector($selector) {
4399 $this->attributes
['data-owner'] = $selector;
4403 * Sets the alignment of the dialogue in relation to button used to toggle it.
4405 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4406 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4408 public function set_alignment($dialogue, $button) {
4409 if (isset($this->attributessecondary
['data-align'])) {
4410 // We've already got one set, lets remove the old class so as to avoid troubles.
4411 $class = $this->attributessecondary
['class'];
4412 $search = 'align-'.$this->attributessecondary
['data-align'];
4413 $this->attributessecondary
['class'] = str_replace($search, '', $class);
4415 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
4416 $this->attributessecondary
['data-align'] = $align;
4417 $this->attributessecondary
['class'] .= ' align-'.$align;
4421 * Returns a string to describe the alignment.
4423 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4426 protected function get_align_string($align) {
4442 * Sets a constraint for the dialogue.
4444 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
4445 * element the constraint identifies.
4447 * This is required whenever the action menu is displayed inside any CSS element with the .no-overflow class
4448 * (flexible_table and any of it's child classes are a likely candidate).
4450 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
4452 public function set_constraint($ancestorselector) {
4453 $this->attributessecondary
['data-constraint'] = $ancestorselector;
4457 * If you call this method the action menu will be displayed but will not be enhanced.
4459 * By not displaying the menu enhanced all items will be displayed in a single row.
4461 * @deprecated since Moodle 3.2
4463 public function do_not_enhance() {
4464 debugging('The method action_menu::do_not_enhance() is deprecated, use a list of action_icon instead.', DEBUG_DEVELOPER
);
4468 * Returns true if this action menu will be enhanced.
4472 public function will_be_enhanced() {
4473 return isset($this->attributes
['data-enhance']);
4477 * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
4479 * This property can be useful when the action menu is displayed within a parent element that is either floated
4480 * or relatively positioned.
4481 * In that situation the width of the menu is determined by the width of the parent element which may not be large
4482 * enough for the menu items without them wrapping.
4483 * This disables the wrapping so that the menu takes on the width of the longest item.
4485 * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
4487 public function set_nowrap_on_items($value = true) {
4488 $class = 'nowrap-items';
4489 if (!empty($this->attributes
['class'])) {
4490 $pos = strpos($this->attributes
['class'], $class);
4491 if ($value === true && $pos === false) {
4492 // The value is true and the class has not been set yet. Add it.
4493 $this->attributes
['class'] .= ' '.$class;
4494 } else if ($value === false && $pos !== false) {
4495 // The value is false and the class has been set. Remove it.
4496 $this->attributes
['class'] = substr($this->attributes
['class'], $pos, strlen($class));
4498 } else if ($value) {
4499 // The value is true and the class has not been set yet. Add it.
4500 $this->attributes
['class'] = $class;
4505 * Export for template.
4507 * @param renderer_base $output The renderer.
4510 public function export_for_template(renderer_base
$output) {
4511 $data = new stdClass();
4512 $attributes = $this->attributes
;
4513 $attributesprimary = $this->attributesprimary
;
4514 $attributessecondary = $this->attributessecondary
;
4516 $data->instance
= $this->instance
;
4518 $data->classes
= isset($attributes['class']) ?
$attributes['class'] : '';
4519 unset($attributes['class']);
4521 $data->attributes
= array_map(function($key, $value) {
4522 return [ 'name' => $key, 'value' => $value ];
4523 }, array_keys($attributes), $attributes);
4525 $primary = new stdClass();
4526 $primary->title
= '';
4527 $primary->prioritise
= $this->prioritise
;
4529 $primary->classes
= isset($attributesprimary['class']) ?
$attributesprimary['class'] : '';
4530 unset($attributesprimary['class']);
4531 $primary->attributes
= array_map(function($key, $value) {
4532 return [ 'name' => $key, 'value' => $value ];
4533 }, array_keys($attributesprimary), $attributesprimary);
4535 $actionicon = $this->actionicon
;
4536 if (!empty($this->menutrigger
)) {
4537 $primary->menutrigger
= $this->menutrigger
;
4538 $primary->triggerextraclasses
= $this->triggerextraclasses
;
4539 if ($this->actionlabel
) {
4540 $primary->title
= $this->actionlabel
;
4541 } else if ($this->actiontext
) {
4542 $primary->title
= $this->actiontext
;
4544 $primary->title
= strip_tags($this->menutrigger
);
4547 $primary->title
= get_string('actionsmenu');
4548 $iconattributes = ['class' => 'iconsmall actionmenu', 'title' => $primary->title
];
4549 $actionicon = new pix_icon('t/edit_menu', '', 'moodle', $iconattributes);
4552 if ($actionicon instanceof pix_icon
) {
4553 $primary->icon
= $actionicon->export_for_pix();
4554 if (!empty($actionicon->attributes
['alt'])) {
4555 $primary->title
= $actionicon->attributes
['alt'];
4558 $primary->iconraw
= $actionicon ?
$output->render($actionicon) : '';
4561 $primary->actiontext
= $this->actiontext ?
(string) $this->actiontext
: '';
4562 $primary->items
= array_map(function($item) use ($output) {
4563 $data = (object) [];
4564 if ($item instanceof action_menu_link
) {
4565 $data->actionmenulink
= $item->export_for_template($output);
4566 } else if ($item instanceof action_menu_filler
) {
4567 $data->actionmenufiller
= $item->export_for_template($output);
4568 } else if ($item instanceof action_link
) {
4569 $data->actionlink
= $item->export_for_template($output);
4570 } else if ($item instanceof pix_icon
) {
4571 $data->pixicon
= $item->export_for_template($output);
4573 $data->rawhtml
= ($item instanceof renderable
) ?
$output->render($item) : $item;
4576 }, $this->primaryactions
);
4578 $secondary = new stdClass();
4579 $secondary->classes
= isset($attributessecondary['class']) ?
$attributessecondary['class'] : '';
4580 unset($attributessecondary['class']);
4581 $secondary->attributes
= array_map(function($key, $value) {
4582 return [ 'name' => $key, 'value' => $value ];
4583 }, array_keys($attributessecondary), $attributessecondary);
4584 $secondary->items
= array_map(function($item) use ($output) {
4585 $data = (object) [];
4586 if ($item instanceof action_menu_link
) {
4587 $data->actionmenulink
= $item->export_for_template($output);
4588 } else if ($item instanceof action_menu_filler
) {
4589 $data->actionmenufiller
= $item->export_for_template($output);
4590 } else if ($item instanceof action_link
) {
4591 $data->actionlink
= $item->export_for_template($output);
4592 } else if ($item instanceof pix_icon
) {
4593 $data->pixicon
= $item->export_for_template($output);
4595 $data->rawhtml
= ($item instanceof renderable
) ?
$output->render($item) : $item;
4598 }, $this->secondaryactions
);
4600 $data->primary
= $primary;
4601 $data->secondary
= $secondary;
4609 * An action menu filler
4613 * @copyright 2013 Andrew Nicols
4614 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4616 class action_menu_filler
extends action_link
implements renderable
{
4619 * True if this is a primary action. False if not.
4622 public $primary = true;
4625 * Constructs the object.
4627 public function __construct() {
4632 * An action menu action
4636 * @copyright 2013 Sam Hemelryk
4637 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4639 class action_menu_link
extends action_link
implements renderable
{
4642 * True if this is a primary action. False if not.
4645 public $primary = true;
4648 * The action menu this link has been added to.
4651 public $actionmenu = null;
4654 * Constructs the object.
4656 * @param moodle_url $url The URL for the action.
4657 * @param pix_icon $icon The icon to represent the action.
4658 * @param string $text The text to represent the action.
4659 * @param bool $primary Whether this is a primary action or not.
4660 * @param array $attributes Any attribtues associated with the action.
4662 public function __construct(moodle_url
$url, pix_icon
$icon = null, $text, $primary = true, array $attributes = array()) {
4663 parent
::__construct($url, $text, null, $attributes, $icon);
4664 $this->primary
= (bool)$primary;
4665 $this->add_class('menu-action');
4666 $this->attributes
['role'] = 'menuitem';
4670 * Export for template.
4672 * @param renderer_base $output The renderer.
4675 public function export_for_template(renderer_base
$output) {
4676 static $instance = 1;
4678 $data = parent
::export_for_template($output);
4679 $data->instance
= $instance++
;
4681 // Ignore what the parent did with the attributes, except for ID and class.
4682 $data->attributes
= [];
4683 $attributes = $this->attributes
;
4684 unset($attributes['id']);
4685 unset($attributes['class']);
4687 // Handle text being a renderable.
4688 if ($this->text
instanceof renderable
) {
4689 $data->text
= $this->render($this->text
);
4692 $data->showtext
= (!$this->icon ||
$this->primary
=== false);
4696 $icon = $this->icon
;
4697 if ($this->primary ||
!$this->actionmenu
->will_be_enhanced()) {
4698 $attributes['title'] = $data->text
;
4700 $data->icon
= $icon ?
$icon->export_for_pix() : null;
4703 $data->disabled
= !empty($attributes['disabled']);
4704 unset($attributes['disabled']);
4706 $data->attributes
= array_map(function($key, $value) {
4711 }, array_keys($attributes), $attributes);
4718 * A primary action menu action
4722 * @copyright 2013 Sam Hemelryk
4723 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4725 class action_menu_link_primary
extends action_menu_link
{
4727 * Constructs the object.
4729 * @param moodle_url $url
4730 * @param pix_icon $icon
4731 * @param string $text
4732 * @param array $attributes
4734 public function __construct(moodle_url
$url, pix_icon
$icon = null, $text, array $attributes = array()) {
4735 parent
::__construct($url, $icon, $text, true, $attributes);
4740 * A secondary action menu action
4744 * @copyright 2013 Sam Hemelryk
4745 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4747 class action_menu_link_secondary
extends action_menu_link
{
4749 * Constructs the object.
4751 * @param moodle_url $url
4752 * @param pix_icon $icon
4753 * @param string $text
4754 * @param array $attributes
4756 public function __construct(moodle_url
$url, pix_icon
$icon = null, $text, array $attributes = array()) {
4757 parent
::__construct($url, $icon, $text, false, $attributes);
4762 * Represents a set of preferences groups.
4766 * @copyright 2015 Frédéric Massart - FMCorz.net
4767 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4769 class preferences_groups
implements renderable
{
4772 * Array of preferences_group.
4779 * @param array $groups of preferences_group
4781 public function __construct($groups) {
4782 $this->groups
= $groups;
4788 * Represents a group of preferences page link.
4792 * @copyright 2015 Frédéric Massart - FMCorz.net
4793 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4795 class preferences_group
implements renderable
{
4798 * Title of the group.
4804 * Array of navigation_node.
4811 * @param string $title The title.
4812 * @param array $nodes of navigation_node.
4814 public function __construct($title, $nodes) {
4815 $this->title
= $title;
4816 $this->nodes
= $nodes;
4821 * Progress bar class.
4823 * Manages the display of a progress bar.
4825 * To use this class.
4827 * - call create (or use the 3rd param to the constructor)
4828 * - call update or update_full() or update() repeatedly
4830 * @copyright 2008 jamiesensei
4831 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4835 class progress_bar
implements renderable
, templatable
{
4836 /** @var string html id */
4838 /** @var int total width */
4840 /** @var int last percentage printed */
4841 private $percent = 0;
4842 /** @var int time when last printed */
4843 private $lastupdate = 0;
4844 /** @var int when did we start printing this */
4845 private $time_start = 0;
4850 * Prints JS code if $autostart true.
4852 * @param string $htmlid The container ID.
4853 * @param int $width The suggested width.
4854 * @param bool $autostart Whether to start the progress bar right away.
4856 public function __construct($htmlid = '', $width = 500, $autostart = false) {
4857 if (!CLI_SCRIPT
&& !NO_OUTPUT_BUFFERING
) {
4858 debugging('progress_bar used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', DEBUG_DEVELOPER
);
4861 if (!empty($htmlid)) {
4862 $this->html_id
= $htmlid;
4864 $this->html_id
= 'pbar_'.uniqid();
4867 $this->width
= $width;
4875 * Create a new progress bar, this function will output html.
4877 * @return void Echo's output
4879 public function create() {
4882 $this->time_start
= microtime(true);
4884 return; // Temporary solution for cli scripts.
4888 echo $OUTPUT->render($this);
4893 * Update the progress bar.
4895 * @param int $percent From 1-100.
4896 * @param string $msg The message.
4897 * @return void Echo's output
4898 * @throws coding_exception
4900 private function _update($percent, $msg) {
4901 if (empty($this->time_start
)) {
4902 throw new coding_exception('You must call create() (or use the $autostart ' .
4903 'argument to the constructor) before you try updating the progress bar.');
4907 return; // Temporary solution for cli scripts.
4910 $estimate = $this->estimate($percent);
4912 if ($estimate === null) {
4913 // Always do the first and last updates.
4914 } else if ($estimate == 0) {
4915 // Always do the last updates.
4916 } else if ($this->lastupdate +
20 < time()) {
4917 // We must update otherwise browser would time out.
4918 } else if (round($this->percent
, 2) === round($percent, 2)) {
4919 // No significant change, no need to update anything.
4923 $estimatemsg = null;
4924 if (is_numeric($estimate)) {
4925 $estimatemsg = get_string('secondsleft', 'moodle', round($estimate, 2));
4928 $this->percent
= round($percent, 2);
4929 $this->lastupdate
= microtime(true);
4931 echo html_writer
::script(js_writer
::function_call('updateProgressBar',
4932 array($this->html_id
, $this->percent
, $msg, $estimatemsg)));
4937 * Estimate how much time it is going to take.
4939 * @param int $pt From 1-100.
4940 * @return mixed Null (unknown), or int.
4942 private function estimate($pt) {
4943 if ($this->lastupdate
== 0) {
4946 if ($pt < 0.00001) {
4947 return null; // We do not know yet how long it will take.
4949 if ($pt > 99.99999) {
4950 return 0; // Nearly done, right?
4952 $consumed = microtime(true) - $this->time_start
;
4953 if ($consumed < 0.001) {
4957 return (100 - $pt) * ($consumed / $pt);
4961 * Update progress bar according percent.
4963 * @param int $percent From 1-100.
4964 * @param string $msg The message needed to be shown.
4966 public function update_full($percent, $msg) {
4967 $percent = max(min($percent, 100), 0);
4968 $this->_update($percent, $msg);
4972 * Update progress bar according the number of tasks.
4974 * @param int $cur Current task number.
4975 * @param int $total Total task number.
4976 * @param string $msg The message needed to be shown.
4978 public function update($cur, $total, $msg) {
4979 $percent = ($cur / $total) * 100;
4980 $this->update_full($percent, $msg);
4984 * Restart the progress bar.
4986 public function restart() {
4988 $this->lastupdate
= 0;
4989 $this->time_start
= 0;
4993 * Export for template.
4995 * @param renderer_base $output The renderer.
4998 public function export_for_template(renderer_base
$output) {
5000 'id' => $this->html_id
,
5001 'width' => $this->width
,