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 (!property_exists($user, $field)) {
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
873 protected $attributes = [];
877 * @param moodle_url $url
878 * @param string $label button text
879 * @param string $method get or post submit method
880 * @param array $attributes Attributes for the HTML button tag
882 public function __construct(moodle_url
$url, $label, $method='post', $primary=false, $attributes = []) {
883 $this->url
= clone($url);
884 $this->label
= $label;
885 $this->method
= $method;
886 $this->primary
= $primary;
887 $this->attributes
= $attributes;
891 * Shortcut for adding a JS confirm dialog when the button is clicked.
892 * The message must be a yes/no question.
894 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
896 public function add_confirm_action($confirmmessage) {
897 $this->add_action(new confirm_action($confirmmessage));
901 * Add action to the button.
902 * @param component_action $action
904 public function add_action(component_action
$action) {
905 $this->actions
[] = $action;
909 * Sets an attribute for the HTML button tag.
911 * @param string $name The attribute name
912 * @param mixed $value The value
915 public function set_attribute($name, $value) {
916 $this->attributes
[$name] = $value;
922 * @param renderer_base $output Renderer.
925 public function export_for_template(renderer_base
$output) {
926 $url = $this->method
=== 'get' ?
$this->url
->out_omit_querystring(true) : $this->url
->out_omit_querystring();
928 $data = new stdClass();
929 $data->id
= html_writer
::random_id('single_button');
930 $data->formid
= $this->formid
;
931 $data->method
= $this->method
;
932 $data->url
= $url === '' ?
'#' : $url;
933 $data->label
= $this->label
;
934 $data->classes
= $this->class;
935 $data->disabled
= $this->disabled
;
936 $data->tooltip
= $this->tooltip
;
937 $data->primary
= $this->primary
;
939 $data->attributes
= [];
940 foreach ($this->attributes
as $key => $value) {
941 $data->attributes
[] = ['name' => $key, 'value' => $value];
945 $params = $this->url
->params();
946 if ($this->method
=== 'post') {
947 $params['sesskey'] = sesskey();
949 $data->params
= array_map(function($key) use ($params) {
950 return ['name' => $key, 'value' => $params[$key]];
951 }, array_keys($params));
954 $actions = $this->actions
;
955 $data->actions
= array_map(function($action) use ($output) {
956 return $action->export_for_template($output);
958 $data->hasactions
= !empty($data->actions
);
966 * Simple form with just one select field that gets submitted automatically.
968 * If JS not enabled small go button is printed too.
970 * @copyright 2009 Petr Skoda
971 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
976 class single_select
implements renderable
, templatable
{
979 * @var moodle_url Target url - includes hidden fields
984 * @var string Name of the select element.
989 * @var array $options associative array value=>label ex.: array(1=>'One, 2=>Two)
990 * it is also possible to specify optgroup as complex label array ex.:
991 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
992 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
997 * @var string Selected option
1002 * @var array Nothing selected
1007 * @var array Extra select field attributes
1009 var $attributes = array();
1012 * @var string Button label
1017 * @var array Button label's attributes
1019 var $labelattributes = array();
1022 * @var string Form submit method post or get
1024 var $method = 'get';
1027 * @var string Wrapping div class
1029 var $class = 'singleselect';
1032 * @var bool True if button disabled, false if normal
1034 var $disabled = false;
1037 * @var string Button tooltip
1039 var $tooltip = null;
1042 * @var string Form id
1047 * @var help_icon The help icon for this element.
1049 var $helpicon = null;
1053 * @param moodle_url $url form action target, includes hidden fields
1054 * @param string $name name of selection field - the changing parameter in url
1055 * @param array $options list of options
1056 * @param string $selected selected element
1057 * @param array $nothing
1058 * @param string $formid
1060 public function __construct(moodle_url
$url, $name, array $options, $selected = '', $nothing = array('' => 'choosedots'), $formid = null) {
1062 $this->name
= $name;
1063 $this->options
= $options;
1064 $this->selected
= $selected;
1065 $this->nothing
= $nothing;
1066 $this->formid
= $formid;
1070 * Shortcut for adding a JS confirm dialog when the button is clicked.
1071 * The message must be a yes/no question.
1073 * @param string $confirmmessage The yes/no confirmation question. If "Yes" is clicked, the original action will occur.
1075 public function add_confirm_action($confirmmessage) {
1076 $this->add_action(new component_action('submit', 'M.util.show_confirm_dialog', array('message' => $confirmmessage)));
1080 * Add action to the button.
1082 * @param component_action $action
1084 public function add_action(component_action
$action) {
1085 $this->actions
[] = $action;
1091 * @deprecated since Moodle 2.0
1093 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1094 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1100 * @param string $identifier The keyword that defines a help page
1101 * @param string $component
1103 public function set_help_icon($identifier, $component = 'moodle') {
1104 $this->helpicon
= new help_icon($identifier, $component);
1108 * Sets select's label
1110 * @param string $label
1111 * @param array $attributes (optional)
1113 public function set_label($label, $attributes = array()) {
1114 $this->label
= $label;
1115 $this->labelattributes
= $attributes;
1122 * @param renderer_base $output Renderer.
1125 public function export_for_template(renderer_base
$output) {
1126 $attributes = $this->attributes
;
1128 $data = new stdClass();
1129 $data->name
= $this->name
;
1130 $data->method
= $this->method
;
1131 $data->action
= $this->method
=== 'get' ?
$this->url
->out_omit_querystring(true) : $this->url
->out_omit_querystring();
1132 $data->classes
= $this->class;
1133 $data->label
= $this->label
;
1134 $data->disabled
= $this->disabled
;
1135 $data->title
= $this->tooltip
;
1136 $data->formid
= !empty($this->formid
) ?
$this->formid
: html_writer
::random_id('single_select_f');
1137 $data->id
= !empty($attributes['id']) ?
$attributes['id'] : html_writer
::random_id('single_select');
1139 // Select element attributes.
1140 // Unset attributes that are already predefined in the template.
1141 unset($attributes['id']);
1142 unset($attributes['class']);
1143 unset($attributes['name']);
1144 unset($attributes['title']);
1145 unset($attributes['disabled']);
1147 // Map the attributes.
1148 $data->attributes
= array_map(function($key) use ($attributes) {
1149 return ['name' => $key, 'value' => $attributes[$key]];
1150 }, array_keys($attributes));
1153 $params = $this->url
->params();
1154 if ($this->method
=== 'post') {
1155 $params['sesskey'] = sesskey();
1157 $data->params
= array_map(function($key) use ($params) {
1158 return ['name' => $key, 'value' => $params[$key]];
1159 }, array_keys($params));
1162 $hasnothing = false;
1163 if (is_string($this->nothing
) && $this->nothing
!== '') {
1164 $nothing = ['' => $this->nothing
];
1167 } else if (is_array($this->nothing
)) {
1168 $nothingvalue = reset($this->nothing
);
1169 if ($nothingvalue === 'choose' ||
$nothingvalue === 'choosedots') {
1170 $nothing = [key($this->nothing
) => get_string('choosedots')];
1172 $nothing = $this->nothing
;
1175 $nothingkey = key($this->nothing
);
1178 $options = $nothing +
$this->options
;
1180 $options = $this->options
;
1183 foreach ($options as $value => $name) {
1184 if (is_array($options[$value])) {
1185 foreach ($options[$value] as $optgroupname => $optgroupvalues) {
1187 foreach ($optgroupvalues as $optvalue => $optname) {
1189 'value' => $optvalue,
1191 'selected' => strval($this->selected
) === strval($optvalue),
1194 if ($hasnothing && $nothingkey === $optvalue) {
1195 $option['ignore'] = 'data-ignore';
1198 $sublist[] = $option;
1200 $data->options
[] = [
1201 'name' => $optgroupname,
1203 'options' => $sublist
1209 'name' => $options[$value],
1210 'selected' => strval($this->selected
) === strval($value),
1214 if ($hasnothing && $nothingkey === $value) {
1215 $option['ignore'] = 'data-ignore';
1218 $data->options
[] = $option;
1222 // Label attributes.
1223 $data->labelattributes
= [];
1224 // Unset label attributes that are already in the template.
1225 unset($this->labelattributes
['for']);
1226 // Map the label attributes.
1227 foreach ($this->labelattributes
as $key => $value) {
1228 $data->labelattributes
[] = ['name' => $key, 'value' => $value];
1232 $data->helpicon
= !empty($this->helpicon
) ?
$this->helpicon
->export_for_template($output) : false;
1239 * Simple URL selection widget description.
1241 * @copyright 2009 Petr Skoda
1242 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1247 class url_select
implements renderable
, templatable
{
1249 * @var array $urls associative array value=>label ex.: array(1=>'One, 2=>Two)
1250 * it is also possible to specify optgroup as complex label array ex.:
1251 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1252 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1257 * @var string Selected option
1262 * @var array Nothing selected
1267 * @var array Extra select field attributes
1269 var $attributes = array();
1272 * @var string Button label
1277 * @var array Button label's attributes
1279 var $labelattributes = array();
1282 * @var string Wrapping div class
1284 var $class = 'urlselect';
1287 * @var bool True if button disabled, false if normal
1289 var $disabled = false;
1292 * @var string Button tooltip
1294 var $tooltip = null;
1297 * @var string Form id
1302 * @var help_icon The help icon for this element.
1304 var $helpicon = null;
1307 * @var string If set, makes button visible with given name for button
1309 var $showbutton = null;
1313 * @param array $urls list of options
1314 * @param string $selected selected element
1315 * @param array $nothing
1316 * @param string $formid
1317 * @param string $showbutton Set to text of button if it should be visible
1318 * or null if it should be hidden (hidden version always has text 'go')
1320 public function __construct(array $urls, $selected = '', $nothing = array('' => 'choosedots'), $formid = null, $showbutton = null) {
1321 $this->urls
= $urls;
1322 $this->selected
= $selected;
1323 $this->nothing
= $nothing;
1324 $this->formid
= $formid;
1325 $this->showbutton
= $showbutton;
1331 * @deprecated since Moodle 2.0
1333 public function set_old_help_icon($helppage, $title, $component = 'moodle') {
1334 throw new coding_exception('set_old_help_icon() can not be used any more, please see set_help_icon().');
1340 * @param string $identifier The keyword that defines a help page
1341 * @param string $component
1343 public function set_help_icon($identifier, $component = 'moodle') {
1344 $this->helpicon
= new help_icon($identifier, $component);
1348 * Sets select's label
1350 * @param string $label
1351 * @param array $attributes (optional)
1353 public function set_label($label, $attributes = array()) {
1354 $this->label
= $label;
1355 $this->labelattributes
= $attributes;
1361 * @param string $value The URL.
1362 * @return The cleaned URL.
1364 protected function clean_url($value) {
1367 if (empty($value)) {
1370 } else if (strpos($value, $CFG->wwwroot
. '/') === 0) {
1371 $value = str_replace($CFG->wwwroot
, '', $value);
1373 } else if (strpos($value, '/') !== 0) {
1374 debugging("Invalid url_select urls parameter: url '$value' is not local relative url!", DEBUG_DEVELOPER
);
1381 * Flatten the options for Mustache.
1383 * This also cleans the URLs.
1385 * @param array $options The options.
1386 * @param array $nothing The nothing option.
1389 protected function flatten_options($options, $nothing) {
1392 foreach ($options as $value => $option) {
1393 if (is_array($option)) {
1394 foreach ($option as $groupname => $optoptions) {
1395 if (!isset($flattened[$groupname])) {
1396 $flattened[$groupname] = [
1397 'name' => $groupname,
1402 foreach ($optoptions as $optvalue => $optoption) {
1403 $cleanedvalue = $this->clean_url($optvalue);
1404 $flattened[$groupname]['options'][$cleanedvalue] = [
1405 'name' => $optoption,
1406 'value' => $cleanedvalue,
1407 'selected' => $this->selected
== $optvalue,
1413 $cleanedvalue = $this->clean_url($value);
1414 $flattened[$cleanedvalue] = [
1416 'value' => $cleanedvalue,
1417 'selected' => $this->selected
== $value,
1422 if (!empty($nothing)) {
1423 $value = key($nothing);
1424 $name = reset($nothing);
1426 $value => ['name' => $name, 'value' => $value, 'selected' => $this->selected
== $value]
1430 // Make non-associative array.
1431 foreach ($flattened as $key => $value) {
1432 if (!empty($value['options'])) {
1433 $flattened[$key]['options'] = array_values($value['options']);
1436 $flattened = array_values($flattened);
1442 * Export for template.
1444 * @param renderer_base $output Renderer.
1447 public function export_for_template(renderer_base
$output) {
1448 $attributes = $this->attributes
;
1450 $data = new stdClass();
1451 $data->formid
= !empty($this->formid
) ?
$this->formid
: html_writer
::random_id('url_select_f');
1452 $data->classes
= $this->class;
1453 $data->label
= $this->label
;
1454 $data->disabled
= $this->disabled
;
1455 $data->title
= $this->tooltip
;
1456 $data->id
= !empty($attributes['id']) ?
$attributes['id'] : html_writer
::random_id('url_select');
1457 $data->sesskey
= sesskey();
1458 $data->action
= (new moodle_url('/course/jumpto.php'))->out(false);
1460 // Remove attributes passed as property directly.
1461 unset($attributes['class']);
1462 unset($attributes['id']);
1463 unset($attributes['name']);
1464 unset($attributes['title']);
1465 unset($attributes['disabled']);
1467 $data->showbutton
= $this->showbutton
;
1471 if (is_string($this->nothing
) && $this->nothing
!== '') {
1472 $nothing = ['' => $this->nothing
];
1473 } else if (is_array($this->nothing
)) {
1474 $nothingvalue = reset($this->nothing
);
1475 if ($nothingvalue === 'choose' ||
$nothingvalue === 'choosedots') {
1476 $nothing = [key($this->nothing
) => get_string('choosedots')];
1478 $nothing = $this->nothing
;
1481 $data->options
= $this->flatten_options($this->urls
, $nothing);
1483 // Label attributes.
1484 $data->labelattributes
= [];
1485 // Unset label attributes that are already in the template.
1486 unset($this->labelattributes
['for']);
1487 // Map the label attributes.
1488 foreach ($this->labelattributes
as $key => $value) {
1489 $data->labelattributes
[] = ['name' => $key, 'value' => $value];
1493 $data->helpicon
= !empty($this->helpicon
) ?
$this->helpicon
->export_for_template($output) : false;
1495 // Finally all the remaining attributes.
1496 $data->attributes
= [];
1497 foreach ($attributes as $key => $value) {
1498 $data->attributes
[] = ['name' => $key, 'value' => $value];
1506 * Data structure describing html link with special action attached.
1508 * @copyright 2010 Petr Skoda
1509 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1514 class action_link
implements renderable
{
1517 * @var moodle_url Href url
1522 * @var string Link text HTML fragment
1527 * @var array HTML attributes
1532 * @var array List of actions attached to link
1537 * @var pix_icon Optional pix icon to render with the link
1543 * @param moodle_url $url
1544 * @param string $text HTML fragment
1545 * @param component_action $action
1546 * @param array $attributes associative array of html link attributes + disabled
1547 * @param pix_icon $icon optional pix_icon to render with the link text
1549 public function __construct(moodle_url
$url,
1551 component_action
$action=null,
1552 array $attributes=null,
1553 pix_icon
$icon=null) {
1554 $this->url
= clone($url);
1555 $this->text
= $text;
1556 $this->attributes
= (array)$attributes;
1558 $this->add_action($action);
1560 $this->icon
= $icon;
1564 * Add action to the link.
1566 * @param component_action $action
1568 public function add_action(component_action
$action) {
1569 $this->actions
[] = $action;
1573 * Adds a CSS class to this action link object
1574 * @param string $class
1576 public function add_class($class) {
1577 if (empty($this->attributes
['class'])) {
1578 $this->attributes
['class'] = $class;
1580 $this->attributes
['class'] .= ' ' . $class;
1585 * Returns true if the specified class has been added to this link.
1586 * @param string $class
1589 public function has_class($class) {
1590 return strpos(' ' . $this->attributes
['class'] . ' ', ' ' . $class . ' ') !== false;
1594 * Return the rendered HTML for the icon. Useful for rendering action links in a template.
1597 public function get_icon_html() {
1602 return $OUTPUT->render($this->icon
);
1606 * Export for template.
1608 * @param renderer_base $output The renderer.
1611 public function export_for_template(renderer_base
$output) {
1612 $data = new stdClass();
1613 $attributes = $this->attributes
;
1615 if (empty($attributes['id'])) {
1616 $attributes['id'] = html_writer
::random_id('action_link');
1618 $data->id
= $attributes['id'];
1619 unset($attributes['id']);
1621 $data->disabled
= !empty($attributes['disabled']);
1622 unset($attributes['disabled']);
1624 $data->text
= $this->text
instanceof renderable ?
$output->render($this->text
) : (string) $this->text
;
1625 $data->url
= $this->url ?
$this->url
->out(false) : '';
1626 $data->icon
= $this->icon ?
$this->icon
->export_for_pix() : null;
1627 $data->classes
= isset($attributes['class']) ?
$attributes['class'] : '';
1628 unset($attributes['class']);
1630 $data->attributes
= array_map(function($key, $value) {
1635 }, array_keys($attributes), $attributes);
1637 $data->actions
= array_map(function($action) use ($output) {
1638 return $action->export_for_template($output);
1639 }, !empty($this->actions
) ?
$this->actions
: []);
1640 $data->hasactions
= !empty($this->actions
);
1647 * Simple html output class
1649 * @copyright 2009 Tim Hunt, 2010 Petr Skoda
1650 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1658 * Outputs a tag with attributes and contents
1660 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1661 * @param string $contents What goes between the opening and closing tags
1662 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1663 * @return string HTML fragment
1665 public static function tag($tagname, $contents, array $attributes = null) {
1666 return self
::start_tag($tagname, $attributes) . $contents . self
::end_tag($tagname);
1670 * Outputs an opening tag with attributes
1672 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1673 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1674 * @return string HTML fragment
1676 public static function start_tag($tagname, array $attributes = null) {
1677 return '<' . $tagname . self
::attributes($attributes) . '>';
1681 * Outputs a closing tag
1683 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1684 * @return string HTML fragment
1686 public static function end_tag($tagname) {
1687 return '</' . $tagname . '>';
1691 * Outputs an empty tag with attributes
1693 * @param string $tagname The name of tag ('input', 'img', 'br' etc.)
1694 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1695 * @return string HTML fragment
1697 public static function empty_tag($tagname, array $attributes = null) {
1698 return '<' . $tagname . self
::attributes($attributes) . ' />';
1702 * Outputs a tag, but only if the contents are not empty
1704 * @param string $tagname The name of tag ('a', 'img', 'span' etc.)
1705 * @param string $contents What goes between the opening and closing tags
1706 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1707 * @return string HTML fragment
1709 public static function nonempty_tag($tagname, $contents, array $attributes = null) {
1710 if ($contents === '' ||
is_null($contents)) {
1713 return self
::tag($tagname, $contents, $attributes);
1717 * Outputs a HTML attribute and value
1719 * @param string $name The name of the attribute ('src', 'href', 'class' etc.)
1720 * @param string $value The value of the attribute. The value will be escaped with {@link s()}
1721 * @return string HTML fragment
1723 public static function attribute($name, $value) {
1724 if ($value instanceof moodle_url
) {
1725 return ' ' . $name . '="' . $value->out() . '"';
1728 // special case, we do not want these in output
1729 if ($value === null) {
1733 // no sloppy trimming here!
1734 return ' ' . $name . '="' . s($value) . '"';
1738 * Outputs a list of HTML attributes and values
1740 * @param array $attributes The tag attributes (array('src' => $url, 'class' => 'class1') etc.)
1741 * The values will be escaped with {@link s()}
1742 * @return string HTML fragment
1744 public static function attributes(array $attributes = null) {
1745 $attributes = (array)$attributes;
1747 foreach ($attributes as $name => $value) {
1748 $output .= self
::attribute($name, $value);
1754 * Generates a simple image tag with attributes.
1756 * @param string $src The source of image
1757 * @param string $alt The alternate text for image
1758 * @param array $attributes The tag attributes (array('height' => $max_height, 'class' => 'class1') etc.)
1759 * @return string HTML fragment
1761 public static function img($src, $alt, array $attributes = null) {
1762 $attributes = (array)$attributes;
1763 $attributes['src'] = $src;
1764 $attributes['alt'] = $alt;
1766 return self
::empty_tag('img', $attributes);
1770 * Generates random html element id.
1772 * @staticvar int $counter
1773 * @staticvar type $uniq
1774 * @param string $base A string fragment that will be included in the random ID.
1775 * @return string A unique ID
1777 public static function random_id($base='random') {
1778 static $counter = 0;
1781 if (!isset($uniq)) {
1786 return $base.$uniq.$counter;
1790 * Generates a simple html link
1792 * @param string|moodle_url $url The URL
1793 * @param string $text The text
1794 * @param array $attributes HTML attributes
1795 * @return string HTML fragment
1797 public static function link($url, $text, array $attributes = null) {
1798 $attributes = (array)$attributes;
1799 $attributes['href'] = $url;
1800 return self
::tag('a', $text, $attributes);
1804 * Generates a simple checkbox with optional label
1806 * @param string $name The name of the checkbox
1807 * @param string $value The value of the checkbox
1808 * @param bool $checked Whether the checkbox is checked
1809 * @param string $label The label for the checkbox
1810 * @param array $attributes Any attributes to apply to the checkbox
1811 * @param array $labelattributes Any attributes to apply to the label, if present
1812 * @return string html fragment
1814 public static function checkbox($name, $value, $checked = true, $label = '',
1815 array $attributes = null, array $labelattributes = null) {
1816 $attributes = (array) $attributes;
1819 if ($label !== '' and !is_null($label)) {
1820 if (empty($attributes['id'])) {
1821 $attributes['id'] = self
::random_id('checkbox_');
1824 $attributes['type'] = 'checkbox';
1825 $attributes['value'] = $value;
1826 $attributes['name'] = $name;
1827 $attributes['checked'] = $checked ?
'checked' : null;
1829 $output .= self
::empty_tag('input', $attributes);
1831 if ($label !== '' and !is_null($label)) {
1832 $labelattributes = (array) $labelattributes;
1833 $labelattributes['for'] = $attributes['id'];
1834 $output .= self
::tag('label', $label, $labelattributes);
1841 * Generates a simple select yes/no form field
1843 * @param string $name name of select element
1844 * @param bool $selected
1845 * @param array $attributes - html select element attributes
1846 * @return string HTML fragment
1848 public static function select_yes_no($name, $selected=true, array $attributes = null) {
1849 $options = array('1'=>get_string('yes'), '0'=>get_string('no'));
1850 return self
::select($options, $name, $selected, null, $attributes);
1854 * Generates a simple select form field
1856 * @param array $options associative array value=>label ex.:
1857 * array(1=>'One, 2=>Two)
1858 * it is also possible to specify optgroup as complex label array ex.:
1859 * array(array('Odd'=>array(1=>'One', 3=>'Three)), array('Even'=>array(2=>'Two')))
1860 * array(1=>'One', '--1uniquekey'=>array('More'=>array(2=>'Two', 3=>'Three')))
1861 * @param string $name name of select element
1862 * @param string|array $selected value or array of values depending on multiple attribute
1863 * @param array|bool $nothing add nothing selected option, or false of not added
1864 * @param array $attributes html select element attributes
1865 * @return string HTML fragment
1867 public static function select(array $options, $name, $selected = '', $nothing = array('' => 'choosedots'), array $attributes = null) {
1868 $attributes = (array)$attributes;
1869 if (is_array($nothing)) {
1870 foreach ($nothing as $k=>$v) {
1871 if ($v === 'choose' or $v === 'choosedots') {
1872 $nothing[$k] = get_string('choosedots');
1875 $options = $nothing +
$options; // keep keys, do not override
1877 } else if (is_string($nothing) and $nothing !== '') {
1879 $options = array(''=>$nothing) +
$options;
1882 // we may accept more values if multiple attribute specified
1883 $selected = (array)$selected;
1884 foreach ($selected as $k=>$v) {
1885 $selected[$k] = (string)$v;
1888 if (!isset($attributes['id'])) {
1890 // name may contaion [], which would make an invalid id. e.g. numeric question type editing form, assignment quickgrading
1891 $id = str_replace('[', '', $id);
1892 $id = str_replace(']', '', $id);
1893 $attributes['id'] = $id;
1896 if (!isset($attributes['class'])) {
1897 $class = 'menu'.$name;
1898 // name may contaion [], which would make an invalid class. e.g. numeric question type editing form, assignment quickgrading
1899 $class = str_replace('[', '', $class);
1900 $class = str_replace(']', '', $class);
1901 $attributes['class'] = $class;
1903 $attributes['class'] = 'select custom-select ' . $attributes['class']; // Add 'select' selector always.
1905 $attributes['name'] = $name;
1907 if (!empty($attributes['disabled'])) {
1908 $attributes['disabled'] = 'disabled';
1910 unset($attributes['disabled']);
1914 foreach ($options as $value=>$label) {
1915 if (is_array($label)) {
1916 // ignore key, it just has to be unique
1917 $output .= self
::select_optgroup(key($label), current($label), $selected);
1919 $output .= self
::select_option($label, $value, $selected);
1922 return self
::tag('select', $output, $attributes);
1926 * Returns HTML to display a select box option.
1928 * @param string $label The label to display as the option.
1929 * @param string|int $value The value the option represents
1930 * @param array $selected An array of selected options
1931 * @return string HTML fragment
1933 private static function select_option($label, $value, array $selected) {
1934 $attributes = array();
1935 $value = (string)$value;
1936 if (in_array($value, $selected, true)) {
1937 $attributes['selected'] = 'selected';
1939 $attributes['value'] = $value;
1940 return self
::tag('option', $label, $attributes);
1944 * Returns HTML to display a select box option group.
1946 * @param string $groupname The label to use for the group
1947 * @param array $options The options in the group
1948 * @param array $selected An array of selected values.
1949 * @return string HTML fragment.
1951 private static function select_optgroup($groupname, $options, array $selected) {
1952 if (empty($options)) {
1955 $attributes = array('label'=>$groupname);
1957 foreach ($options as $value=>$label) {
1958 $output .= self
::select_option($label, $value, $selected);
1960 return self
::tag('optgroup', $output, $attributes);
1964 * This is a shortcut for making an hour selector menu.
1966 * @param string $type The type of selector (years, months, days, hours, minutes)
1967 * @param string $name fieldname
1968 * @param int $currenttime A default timestamp in GMT
1969 * @param int $step minute spacing
1970 * @param array $attributes - html select element attributes
1971 * @return HTML fragment
1973 public static function select_time($type, $name, $currenttime = 0, $step = 5, array $attributes = null) {
1976 if (!$currenttime) {
1977 $currenttime = time();
1979 $calendartype = \core_calendar\type_factory
::get_calendar_instance();
1980 $currentdate = $calendartype->timestamp_to_date_array($currenttime);
1981 $userdatetype = $type;
1982 $timeunits = array();
1986 $timeunits = $calendartype->get_years();
1987 $userdatetype = 'year';
1990 $timeunits = $calendartype->get_months();
1991 $userdatetype = 'month';
1992 $currentdate['month'] = (int)$currentdate['mon'];
1995 $timeunits = $calendartype->get_days();
1996 $userdatetype = 'mday';
1999 for ($i=0; $i<=23; $i++
) {
2000 $timeunits[$i] = sprintf("%02d",$i);
2005 $currentdate['minutes'] = ceil($currentdate['minutes']/$step)*$step;
2008 for ($i=0; $i<=59; $i+
=$step) {
2009 $timeunits[$i] = sprintf("%02d",$i);
2013 throw new coding_exception("Time type $type is not supported by html_writer::select_time().");
2016 $attributes = (array) $attributes;
2019 'id' => !empty($attributes['id']) ?
$attributes['id'] : self
::random_id('ts_'),
2020 'label' => get_string(substr($type, 0, -1), 'form'),
2021 'options' => array_map(function($value) use ($timeunits, $currentdate, $userdatetype) {
2023 'name' => $timeunits[$value],
2025 'selected' => $currentdate[$userdatetype] == $value
2027 }, array_keys($timeunits)),
2030 unset($attributes['id']);
2031 unset($attributes['name']);
2032 $data->attributes
= array_map(function($name) use ($attributes) {
2035 'value' => $attributes[$name]
2037 }, array_keys($attributes));
2039 return $OUTPUT->render_from_template('core/select_time', $data);
2043 * Shortcut for quick making of lists
2045 * Note: 'list' is a reserved keyword ;-)
2047 * @param array $items
2048 * @param array $attributes
2049 * @param string $tag ul or ol
2052 public static function alist(array $items, array $attributes = null, $tag = 'ul') {
2053 $output = html_writer
::start_tag($tag, $attributes)."\n";
2054 foreach ($items as $item) {
2055 $output .= html_writer
::tag('li', $item)."\n";
2057 $output .= html_writer
::end_tag($tag);
2062 * Returns hidden input fields created from url parameters.
2064 * @param moodle_url $url
2065 * @param array $exclude list of excluded parameters
2066 * @return string HTML fragment
2068 public static function input_hidden_params(moodle_url
$url, array $exclude = null) {
2069 $exclude = (array)$exclude;
2070 $params = $url->params();
2071 foreach ($exclude as $key) {
2072 unset($params[$key]);
2076 foreach ($params as $key => $value) {
2077 $attributes = array('type'=>'hidden', 'name'=>$key, 'value'=>$value);
2078 $output .= self
::empty_tag('input', $attributes)."\n";
2084 * Generate a script tag containing the the specified code.
2086 * @param string $jscode the JavaScript code
2087 * @param moodle_url|string $url optional url of the external script, $code ignored if specified
2088 * @return string HTML, the code wrapped in <script> tags.
2090 public static function script($jscode, $url=null) {
2092 return self
::tag('script', "\n//<![CDATA[\n$jscode\n//]]>\n") . "\n";
2095 return self
::tag('script', '', ['src' => $url]) . "\n";
2103 * Renders HTML table
2105 * This method may modify the passed instance by adding some default properties if they are not set yet.
2106 * If this is not what you want, you should make a full clone of your data before passing them to this
2107 * method. In most cases this is not an issue at all so we do not clone by default for performance
2108 * and memory consumption reasons.
2110 * @param html_table $table data to be rendered
2111 * @return string HTML code
2113 public static function table(html_table
$table) {
2114 // prepare table data and populate missing properties with reasonable defaults
2115 if (!empty($table->align
)) {
2116 foreach ($table->align
as $key => $aa) {
2118 $table->align
[$key] = 'text-align:'. fix_align_rtl($aa) .';'; // Fix for RTL languages
2120 $table->align
[$key] = null;
2124 if (!empty($table->size
)) {
2125 foreach ($table->size
as $key => $ss) {
2127 $table->size
[$key] = 'width:'. $ss .';';
2129 $table->size
[$key] = null;
2133 if (!empty($table->wrap
)) {
2134 foreach ($table->wrap
as $key => $ww) {
2136 $table->wrap
[$key] = 'white-space:nowrap;';
2138 $table->wrap
[$key] = '';
2142 if (!empty($table->head
)) {
2143 foreach ($table->head
as $key => $val) {
2144 if (!isset($table->align
[$key])) {
2145 $table->align
[$key] = null;
2147 if (!isset($table->size
[$key])) {
2148 $table->size
[$key] = null;
2150 if (!isset($table->wrap
[$key])) {
2151 $table->wrap
[$key] = null;
2156 if (empty($table->attributes
['class'])) {
2157 $table->attributes
['class'] = 'generaltable';
2159 if (!empty($table->tablealign
)) {
2160 $table->attributes
['class'] .= ' boxalign' . $table->tablealign
;
2163 // explicitly assigned properties override those defined via $table->attributes
2164 $table->attributes
['class'] = trim($table->attributes
['class']);
2165 $attributes = array_merge($table->attributes
, array(
2167 'width' => $table->width
,
2168 'summary' => $table->summary
,
2169 'cellpadding' => $table->cellpadding
,
2170 'cellspacing' => $table->cellspacing
,
2172 $output = html_writer
::start_tag('table', $attributes) . "\n";
2176 // Output a caption if present.
2177 if (!empty($table->caption
)) {
2178 $captionattributes = array();
2179 if ($table->captionhide
) {
2180 $captionattributes['class'] = 'accesshide';
2182 $output .= html_writer
::tag(
2189 if (!empty($table->head
)) {
2190 $countcols = count($table->head
);
2192 $output .= html_writer
::start_tag('thead', array()) . "\n";
2193 $output .= html_writer
::start_tag('tr', array()) . "\n";
2194 $keys = array_keys($table->head
);
2195 $lastkey = end($keys);
2197 foreach ($table->head
as $key => $heading) {
2198 // Convert plain string headings into html_table_cell objects
2199 if (!($heading instanceof html_table_cell
)) {
2200 $headingtext = $heading;
2201 $heading = new html_table_cell();
2202 $heading->text
= $headingtext;
2203 $heading->header
= true;
2206 if ($heading->header
!== false) {
2207 $heading->header
= true;
2211 if ($heading->header
&& (string)$heading->text
!= '') {
2215 $heading->attributes
['class'] .= ' header c' . $key;
2216 if (isset($table->headspan
[$key]) && $table->headspan
[$key] > 1) {
2217 $heading->colspan
= $table->headspan
[$key];
2218 $countcols +
= $table->headspan
[$key] - 1;
2221 if ($key == $lastkey) {
2222 $heading->attributes
['class'] .= ' lastcol';
2224 if (isset($table->colclasses
[$key])) {
2225 $heading->attributes
['class'] .= ' ' . $table->colclasses
[$key];
2227 $heading->attributes
['class'] = trim($heading->attributes
['class']);
2228 $attributes = array_merge($heading->attributes
, [
2229 'style' => $table->align
[$key] . $table->size
[$key] . $heading->style
,
2230 'colspan' => $heading->colspan
,
2233 if ($tagtype == 'th') {
2234 $attributes['scope'] = !empty($heading->scope
) ?
$heading->scope
: 'col';
2237 $output .= html_writer
::tag($tagtype, $heading->text
, $attributes) . "\n";
2239 $output .= html_writer
::end_tag('tr') . "\n";
2240 $output .= html_writer
::end_tag('thead') . "\n";
2242 if (empty($table->data
)) {
2243 // For valid XHTML strict every table must contain either a valid tr
2244 // or a valid tbody... both of which must contain a valid td
2245 $output .= html_writer
::start_tag('tbody', array('class' => 'empty'));
2246 $output .= html_writer
::tag('tr', html_writer
::tag('td', '', array('colspan'=>count($table->head
))));
2247 $output .= html_writer
::end_tag('tbody');
2251 if (!empty($table->data
)) {
2252 $keys = array_keys($table->data
);
2253 $lastrowkey = end($keys);
2254 $output .= html_writer
::start_tag('tbody', array());
2256 foreach ($table->data
as $key => $row) {
2257 if (($row === 'hr') && ($countcols)) {
2258 $output .= html_writer
::tag('td', html_writer
::tag('div', '', array('class' => 'tabledivider')), array('colspan' => $countcols));
2260 // Convert array rows to html_table_rows and cell strings to html_table_cell objects
2261 if (!($row instanceof html_table_row
)) {
2262 $newrow = new html_table_row();
2264 foreach ($row as $cell) {
2265 if (!($cell instanceof html_table_cell
)) {
2266 $cell = new html_table_cell($cell);
2268 $newrow->cells
[] = $cell;
2273 if (isset($table->rowclasses
[$key])) {
2274 $row->attributes
['class'] .= ' ' . $table->rowclasses
[$key];
2277 if ($key == $lastrowkey) {
2278 $row->attributes
['class'] .= ' lastrow';
2281 // Explicitly assigned properties should override those defined in the attributes.
2282 $row->attributes
['class'] = trim($row->attributes
['class']);
2283 $trattributes = array_merge($row->attributes
, array(
2285 'style' => $row->style
,
2287 $output .= html_writer
::start_tag('tr', $trattributes) . "\n";
2288 $keys2 = array_keys($row->cells
);
2289 $lastkey = end($keys2);
2291 $gotlastkey = false; //flag for sanity checking
2292 foreach ($row->cells
as $key => $cell) {
2294 //This should never happen. Why do we have a cell after the last cell?
2295 mtrace("A cell with key ($key) was found after the last key ($lastkey)");
2298 if (!($cell instanceof html_table_cell
)) {
2299 $mycell = new html_table_cell();
2300 $mycell->text
= $cell;
2304 if (($cell->header
=== true) && empty($cell->scope
)) {
2305 $cell->scope
= 'row';
2308 if (isset($table->colclasses
[$key])) {
2309 $cell->attributes
['class'] .= ' ' . $table->colclasses
[$key];
2312 $cell->attributes
['class'] .= ' cell c' . $key;
2313 if ($key == $lastkey) {
2314 $cell->attributes
['class'] .= ' lastcol';
2318 $tdstyle .= isset($table->align
[$key]) ?
$table->align
[$key] : '';
2319 $tdstyle .= isset($table->size
[$key]) ?
$table->size
[$key] : '';
2320 $tdstyle .= isset($table->wrap
[$key]) ?
$table->wrap
[$key] : '';
2321 $cell->attributes
['class'] = trim($cell->attributes
['class']);
2322 $tdattributes = array_merge($cell->attributes
, array(
2323 'style' => $tdstyle . $cell->style
,
2324 'colspan' => $cell->colspan
,
2325 'rowspan' => $cell->rowspan
,
2327 'abbr' => $cell->abbr
,
2328 'scope' => $cell->scope
,
2331 if ($cell->header
=== true) {
2334 $output .= html_writer
::tag($tagtype, $cell->text
, $tdattributes) . "\n";
2337 $output .= html_writer
::end_tag('tr') . "\n";
2339 $output .= html_writer
::end_tag('tbody') . "\n";
2341 $output .= html_writer
::end_tag('table') . "\n";
2347 * Renders form element label
2349 * By default, the label is suffixed with a label separator defined in the
2350 * current language pack (colon by default in the English lang pack).
2351 * Adding the colon can be explicitly disabled if needed. Label separators
2352 * are put outside the label tag itself so they are not read by
2353 * screenreaders (accessibility).
2355 * Parameter $for explicitly associates the label with a form control. When
2356 * set, the value of this attribute must be the same as the value of
2357 * the id attribute of the form control in the same document. When null,
2358 * the label being defined is associated with the control inside the label
2361 * @param string $text content of the label tag
2362 * @param string|null $for id of the element this label is associated with, null for no association
2363 * @param bool $colonize add label separator (colon) to the label text, if it is not there yet
2364 * @param array $attributes to be inserted in the tab, for example array('accesskey' => 'a')
2365 * @return string HTML of the label element
2367 public static function label($text, $for, $colonize = true, array $attributes=array()) {
2368 if (!is_null($for)) {
2369 $attributes = array_merge($attributes, array('for' => $for));
2371 $text = trim($text);
2372 $label = self
::tag('label', $text, $attributes);
2374 // TODO MDL-12192 $colonize disabled for now yet
2375 // if (!empty($text) and $colonize) {
2376 // // the $text may end with the colon already, though it is bad string definition style
2377 // $colon = get_string('labelsep', 'langconfig');
2378 // if (!empty($colon)) {
2379 // $trimmed = trim($colon);
2380 // if ((substr($text, -strlen($trimmed)) == $trimmed) or (substr($text, -1) == ':')) {
2381 // //debugging('The label text should not end with colon or other label separator,
2382 // // please fix the string definition.', DEBUG_DEVELOPER);
2384 // $label .= $colon;
2393 * Combines a class parameter with other attributes. Aids in code reduction
2394 * because the class parameter is very frequently used.
2396 * If the class attribute is specified both in the attributes and in the
2397 * class parameter, the two values are combined with a space between.
2399 * @param string $class Optional CSS class (or classes as space-separated list)
2400 * @param array $attributes Optional other attributes as array
2401 * @return array Attributes (or null if still none)
2403 private static function add_class($class = '', array $attributes = null) {
2404 if ($class !== '') {
2405 $classattribute = array('class' => $class);
2407 if (array_key_exists('class', $attributes)) {
2408 $attributes['class'] = trim($attributes['class'] . ' ' . $class);
2410 $attributes = $classattribute +
$attributes;
2413 $attributes = $classattribute;
2420 * Creates a <div> tag. (Shortcut function.)
2422 * @param string $content HTML content of tag
2423 * @param string $class Optional CSS class (or classes as space-separated list)
2424 * @param array $attributes Optional other attributes as array
2425 * @return string HTML code for div
2427 public static function div($content, $class = '', array $attributes = null) {
2428 return self
::tag('div', $content, self
::add_class($class, $attributes));
2432 * Starts a <div> tag. (Shortcut function.)
2434 * @param string $class Optional CSS class (or classes as space-separated list)
2435 * @param array $attributes Optional other attributes as array
2436 * @return string HTML code for open div tag
2438 public static function start_div($class = '', array $attributes = null) {
2439 return self
::start_tag('div', self
::add_class($class, $attributes));
2443 * Ends a <div> tag. (Shortcut function.)
2445 * @return string HTML code for close div tag
2447 public static function end_div() {
2448 return self
::end_tag('div');
2452 * Creates a <span> tag. (Shortcut function.)
2454 * @param string $content HTML content of tag
2455 * @param string $class Optional CSS class (or classes as space-separated list)
2456 * @param array $attributes Optional other attributes as array
2457 * @return string HTML code for span
2459 public static function span($content, $class = '', array $attributes = null) {
2460 return self
::tag('span', $content, self
::add_class($class, $attributes));
2464 * Starts a <span> tag. (Shortcut function.)
2466 * @param string $class Optional CSS class (or classes as space-separated list)
2467 * @param array $attributes Optional other attributes as array
2468 * @return string HTML code for open span tag
2470 public static function start_span($class = '', array $attributes = null) {
2471 return self
::start_tag('span', self
::add_class($class, $attributes));
2475 * Ends a <span> tag. (Shortcut function.)
2477 * @return string HTML code for close span tag
2479 public static function end_span() {
2480 return self
::end_tag('span');
2485 * Simple javascript output class
2487 * @copyright 2010 Petr Skoda
2488 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2496 * Returns javascript code calling the function
2498 * @param string $function function name, can be complex like Y.Event.purgeElement
2499 * @param array $arguments parameters
2500 * @param int $delay execution delay in seconds
2501 * @return string JS code fragment
2503 public static function function_call($function, array $arguments = null, $delay=0) {
2505 $arguments = array_map('json_encode', convert_to_array($arguments));
2506 $arguments = implode(', ', $arguments);
2510 $js = "$function($arguments);";
2513 $delay = $delay * 1000; // in miliseconds
2514 $js = "setTimeout(function() { $js }, $delay);";
2520 * Special function which adds Y as first argument of function call.
2522 * @param string $function The function to call
2523 * @param array $extraarguments Any arguments to pass to it
2524 * @return string Some JS code
2526 public static function function_call_with_Y($function, array $extraarguments = null) {
2527 if ($extraarguments) {
2528 $extraarguments = array_map('json_encode', convert_to_array($extraarguments));
2529 $arguments = 'Y, ' . implode(', ', $extraarguments);
2533 return "$function($arguments);\n";
2537 * Returns JavaScript code to initialise a new object
2539 * @param string $var If it is null then no var is assigned the new object.
2540 * @param string $class The class to initialise an object for.
2541 * @param array $arguments An array of args to pass to the init method.
2542 * @param array $requirements Any modules required for this class.
2543 * @param int $delay The delay before initialisation. 0 = no delay.
2544 * @return string Some JS code
2546 public static function object_init($var, $class, array $arguments = null, array $requirements = null, $delay=0) {
2547 if (is_array($arguments)) {
2548 $arguments = array_map('json_encode', convert_to_array($arguments));
2549 $arguments = implode(', ', $arguments);
2552 if ($var === null) {
2553 $js = "new $class(Y, $arguments);";
2554 } else if (strpos($var, '.')!==false) {
2555 $js = "$var = new $class(Y, $arguments);";
2557 $js = "var $var = new $class(Y, $arguments);";
2561 $delay = $delay * 1000; // in miliseconds
2562 $js = "setTimeout(function() { $js }, $delay);";
2565 if (count($requirements) > 0) {
2566 $requirements = implode("', '", $requirements);
2567 $js = "Y.use('$requirements', function(Y){ $js });";
2573 * Returns code setting value to variable
2575 * @param string $name
2576 * @param mixed $value json serialised value
2577 * @param bool $usevar add var definition, ignored for nested properties
2578 * @return string JS code fragment
2580 public static function set_variable($name, $value, $usevar = true) {
2584 if (strpos($name, '.')) {
2591 $output .= "$name = ".json_encode($value).";";
2597 * Writes event handler attaching code
2599 * @param array|string $selector standard YUI selector for elements, may be
2600 * array or string, element id is in the form "#idvalue"
2601 * @param string $event A valid DOM event (click, mousedown, change etc.)
2602 * @param string $function The name of the function to call
2603 * @param array $arguments An optional array of argument parameters to pass to the function
2604 * @return string JS code fragment
2606 public static function event_handler($selector, $event, $function, array $arguments = null) {
2607 $selector = json_encode($selector);
2608 $output = "Y.on('$event', $function, $selector, null";
2609 if (!empty($arguments)) {
2610 $output .= ', ' . json_encode($arguments);
2612 return $output . ");\n";
2617 * Holds all the information required to render a <table> by {@link core_renderer::table()}
2620 * $t = new html_table();
2621 * ... // set various properties of the object $t as described below
2622 * echo html_writer::table($t);
2624 * @copyright 2009 David Mudrak <david.mudrak@gmail.com>
2625 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2633 * @var string Value to use for the id attribute of the table
2638 * @var array Attributes of HTML attributes for the <table> element
2640 public $attributes = array();
2643 * @var array An array of headings. The n-th array item is used as a heading of the n-th column.
2644 * For more control over the rendering of the headers, an array of html_table_cell objects
2645 * can be passed instead of an array of strings.
2648 * $t->head = array('Student', 'Grade');
2653 * @var array An array that can be used to make a heading span multiple columns.
2654 * In this example, {@link html_table:$data} is supposed to have three columns. For the first two columns,
2655 * the same heading is used. Therefore, {@link html_table::$head} should consist of two items.
2658 * $t->headspan = array(2,1);
2663 * @var array An array of column alignments.
2664 * The value is used as CSS 'text-align' property. Therefore, possible
2665 * values are 'left', 'right', 'center' and 'justify'. Specify 'right' or 'left' from the perspective
2666 * of a left-to-right (LTR) language. For RTL, the values are flipped automatically.
2668 * Examples of usage:
2669 * $t->align = array(null, 'right');
2671 * $t->align[1] = 'right';
2676 * @var array The value is used as CSS 'size' property.
2678 * Examples of usage:
2679 * $t->size = array('50%', '50%');
2681 * $t->size[1] = '120px';
2686 * @var array An array of wrapping information.
2687 * The only possible value is 'nowrap' that sets the
2688 * CSS property 'white-space' to the value 'nowrap' in the given column.
2691 * $t->wrap = array(null, 'nowrap');
2696 * @var array Array of arrays or html_table_row objects containing the data. Alternatively, if you have
2697 * $head specified, the string 'hr' (for horizontal ruler) can be used
2698 * instead of an array of cells data resulting in a divider rendered.
2700 * Example of usage with array of arrays:
2701 * $row1 = array('Harry Potter', '76 %');
2702 * $row2 = array('Hermione Granger', '100 %');
2703 * $t->data = array($row1, $row2);
2705 * Example with array of html_table_row objects: (used for more fine-grained control)
2706 * $cell1 = new html_table_cell();
2707 * $cell1->text = 'Harry Potter';
2708 * $cell1->colspan = 2;
2709 * $row1 = new html_table_row();
2710 * $row1->cells[] = $cell1;
2711 * $cell2 = new html_table_cell();
2712 * $cell2->text = 'Hermione Granger';
2713 * $cell3 = new html_table_cell();
2714 * $cell3->text = '100 %';
2715 * $row2 = new html_table_row();
2716 * $row2->cells = array($cell2, $cell3);
2717 * $t->data = array($row1, $row2);
2722 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2723 * @var string Width of the table, percentage of the page preferred.
2725 public $width = null;
2728 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2729 * @var string Alignment for the whole table. Can be 'right', 'left' or 'center' (default).
2731 public $tablealign = null;
2734 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2735 * @var int Padding on each cell, in pixels
2737 public $cellpadding = null;
2740 * @var int Spacing between cells, in pixels
2741 * @deprecated since Moodle 2.0. Styling should be in the CSS.
2743 public $cellspacing = null;
2746 * @var array Array of classes to add to particular rows, space-separated string.
2747 * Class 'lastrow' is added automatically for the last row in the table.
2750 * $t->rowclasses[9] = 'tenth'
2755 * @var array An array of classes to add to every cell in a particular column,
2756 * space-separated string. Class 'cell' is added automatically by the renderer.
2757 * Classes 'c0' or 'c1' are added automatically for every odd or even column,
2758 * respectively. Class 'lastcol' is added automatically for all last cells
2762 * $t->colclasses = array(null, 'grade');
2767 * @var string Description of the contents for screen readers.
2769 * The "summary" attribute on the "table" element is not supported in HTML5.
2770 * Consider describing the structure of the table in a "caption" element or in a "figure" element containing the table;
2771 * or, simplify the structure of the table so that no description is needed.
2773 * @deprecated since Moodle 3.9.
2778 * @var string Caption for the table, typically a title.
2781 * $t->caption = "TV Guide";
2786 * @var bool Whether to hide the table's caption from sighted users.
2789 * $t->caption = "TV Guide";
2790 * $t->captionhide = true;
2792 public $captionhide = false;
2797 public function __construct() {
2798 $this->attributes
['class'] = '';
2803 * Component representing a table row.
2805 * @copyright 2009 Nicolas Connault
2806 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2811 class html_table_row
{
2814 * @var string Value to use for the id attribute of the row.
2819 * @var array Array of html_table_cell objects
2821 public $cells = array();
2824 * @var string Value to use for the style attribute of the table row
2826 public $style = null;
2829 * @var array Attributes of additional HTML attributes for the <tr> element
2831 public $attributes = array();
2835 * @param array $cells
2837 public function __construct(array $cells=null) {
2838 $this->attributes
['class'] = '';
2839 $cells = (array)$cells;
2840 foreach ($cells as $cell) {
2841 if ($cell instanceof html_table_cell
) {
2842 $this->cells
[] = $cell;
2844 $this->cells
[] = new html_table_cell($cell);
2851 * Component representing a table cell.
2853 * @copyright 2009 Nicolas Connault
2854 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2859 class html_table_cell
{
2862 * @var string Value to use for the id attribute of the cell.
2867 * @var string The contents of the cell.
2872 * @var string Abbreviated version of the contents of the cell.
2874 public $abbr = null;
2877 * @var int Number of columns this cell should span.
2879 public $colspan = null;
2882 * @var int Number of rows this cell should span.
2884 public $rowspan = null;
2887 * @var string Defines a way to associate header cells and data cells in a table.
2889 public $scope = null;
2892 * @var bool Whether or not this cell is a header cell.
2894 public $header = null;
2897 * @var string Value to use for the style attribute of the table cell
2899 public $style = null;
2902 * @var array Attributes of additional HTML attributes for the <td> element
2904 public $attributes = array();
2907 * Constructs a table cell
2909 * @param string $text
2911 public function __construct($text = null) {
2912 $this->text
= $text;
2913 $this->attributes
['class'] = '';
2918 * Component representing a paging bar.
2920 * @copyright 2009 Nicolas Connault
2921 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2926 class paging_bar
implements renderable
, templatable
{
2929 * @var int The maximum number of pagelinks to display.
2931 public $maxdisplay = 18;
2934 * @var int The total number of entries to be pages through..
2939 * @var int The page you are currently viewing.
2944 * @var int The number of entries that should be shown per page.
2949 * @var string|moodle_url If this is a string then it is the url which will be appended with $pagevar,
2950 * an equals sign and the page number.
2951 * If this is a moodle_url object then the pagevar param will be replaced by
2952 * the page no, for each page.
2957 * @var string This is the variable name that you use for the pagenumber in your
2958 * code (ie. 'tablepage', 'blogpage', etc)
2963 * @var string A HTML link representing the "previous" page.
2965 public $previouslink = null;
2968 * @var string A HTML link representing the "next" page.
2970 public $nextlink = null;
2973 * @var string A HTML link representing the first page.
2975 public $firstlink = null;
2978 * @var string A HTML link representing the last page.
2980 public $lastlink = null;
2983 * @var array An array of strings. One of them is just a string: the current page
2985 public $pagelinks = array();
2988 * Constructor paging_bar with only the required params.
2990 * @param int $totalcount The total number of entries available to be paged through
2991 * @param int $page The page you are currently viewing
2992 * @param int $perpage The number of entries that should be shown per page
2993 * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
2994 * @param string $pagevar name of page parameter that holds the page number
2996 public function __construct($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
2997 $this->totalcount
= $totalcount;
2998 $this->page
= $page;
2999 $this->perpage
= $perpage;
3000 $this->baseurl
= $baseurl;
3001 $this->pagevar
= $pagevar;
3005 * Prepares the paging bar for output.
3007 * This method validates the arguments set up for the paging bar and then
3008 * produces fragments of HTML to assist display later on.
3010 * @param renderer_base $output
3011 * @param moodle_page $page
3012 * @param string $target
3013 * @throws coding_exception
3015 public function prepare(renderer_base
$output, moodle_page
$page, $target) {
3016 if (!isset($this->totalcount
) ||
is_null($this->totalcount
)) {
3017 throw new coding_exception('paging_bar requires a totalcount value.');
3019 if (!isset($this->page
) ||
is_null($this->page
)) {
3020 throw new coding_exception('paging_bar requires a page value.');
3022 if (empty($this->perpage
)) {
3023 throw new coding_exception('paging_bar requires a perpage value.');
3025 if (empty($this->baseurl
)) {
3026 throw new coding_exception('paging_bar requires a baseurl value.');
3029 if ($this->totalcount
> $this->perpage
) {
3030 $pagenum = $this->page
- 1;
3032 if ($this->page
> 0) {
3033 $this->previouslink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$pagenum)), get_string('previous'), array('class'=>'previous'));
3036 if ($this->perpage
> 0) {
3037 $lastpage = ceil($this->totalcount
/ $this->perpage
);
3042 if ($this->page
> round(($this->maxdisplay
/3)*2)) {
3043 $currpage = $this->page
- round($this->maxdisplay
/3);
3045 $this->firstlink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>0)), '1', array('class'=>'first'));
3050 $displaycount = $displaypage = 0;
3052 while ($displaycount < $this->maxdisplay
and $currpage < $lastpage) {
3053 $displaypage = $currpage +
1;
3055 if ($this->page
== $currpage) {
3056 $this->pagelinks
[] = html_writer
::span($displaypage, 'current-page');
3058 $pagelink = html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$currpage)), $displaypage);
3059 $this->pagelinks
[] = $pagelink;
3066 if ($currpage < $lastpage) {
3067 $lastpageactual = $lastpage - 1;
3068 $this->lastlink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$lastpageactual)), $lastpage, array('class'=>'last'));
3071 $pagenum = $this->page +
1;
3073 if ($pagenum != $lastpage) {
3074 $this->nextlink
= html_writer
::link(new moodle_url($this->baseurl
, array($this->pagevar
=>$pagenum)), get_string('next'), array('class'=>'next'));
3080 * Export for template.
3082 * @param renderer_base $output The renderer.
3085 public function export_for_template(renderer_base
$output) {
3086 $data = new stdClass();
3087 $data->previous
= null;
3089 $data->first
= null;
3091 $data->label
= get_string('page');
3093 $data->haspages
= $this->totalcount
> $this->perpage
;
3094 $data->pagesize
= $this->perpage
;
3096 if (!$data->haspages
) {
3100 if ($this->page
> 0) {
3102 'page' => $this->page
,
3103 'url' => (new moodle_url($this->baseurl
, [$this->pagevar
=> $this->page
- 1]))->out(false)
3108 if ($this->page
> round(($this->maxdisplay
/ 3) * 2)) {
3109 $currpage = $this->page
- round($this->maxdisplay
/ 3);
3112 'url' => (new moodle_url($this->baseurl
, [$this->pagevar
=> 0]))->out(false)
3117 if ($this->perpage
> 0) {
3118 $lastpage = ceil($this->totalcount
/ $this->perpage
);
3123 while ($displaycount < $this->maxdisplay
and $currpage < $lastpage) {
3124 $displaypage = $currpage +
1;
3126 $iscurrent = $this->page
== $currpage;
3127 $link = new moodle_url($this->baseurl
, [$this->pagevar
=> $currpage]);
3130 'page' => $displaypage,
3131 'active' => $iscurrent,
3132 'url' => $iscurrent ?
null : $link->out(false)
3139 if ($currpage < $lastpage) {
3141 'page' => $lastpage,
3142 'url' => (new moodle_url($this->baseurl
, [$this->pagevar
=> $lastpage - 1]))->out(false)
3146 if ($this->page +
1 != $lastpage) {
3148 'page' => $this->page +
2,
3149 'url' => (new moodle_url($this->baseurl
, [$this->pagevar
=> $this->page +
1]))->out(false)
3158 * Component representing initials bar.
3160 * @copyright 2017 Ilya Tregubov
3161 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3166 class initials_bar
implements renderable
, templatable
{
3169 * @var string Currently selected letter.
3174 * @var string Class name to add to this initial bar.
3179 * @var string The name to put in front of this initial bar.
3184 * @var string URL parameter name for this initial.
3189 * @var string URL object.
3194 * @var array An array of letters in the alphabet.
3199 * Constructor initials_bar with only the required params.
3201 * @param string $current the currently selected letter.
3202 * @param string $class class name to add to this initial bar.
3203 * @param string $title the name to put in front of this initial bar.
3204 * @param string $urlvar URL parameter name for this initial.
3205 * @param string $url URL object.
3206 * @param array $alpha of letters in the alphabet.
3208 public function __construct($current, $class, $title, $urlvar, $url, $alpha = null) {
3209 $this->current
= $current;
3210 $this->class = $class;
3211 $this->title
= $title;
3212 $this->urlvar
= $urlvar;
3214 $this->alpha
= $alpha;
3218 * Export for template.
3220 * @param renderer_base $output The renderer.
3223 public function export_for_template(renderer_base
$output) {
3224 $data = new stdClass();
3226 if ($this->alpha
== null) {
3227 $this->alpha
= explode(',', get_string('alphabet', 'langconfig'));
3230 if ($this->current
== 'all') {
3231 $this->current
= '';
3234 // We want to find a letter grouping size which suits the language so
3235 // find the largest group size which is less than 15 chars.
3236 // The choice of 15 chars is the largest number of chars that reasonably
3237 // fits on the smallest supported screen size. By always using a max number
3238 // of groups which is a factor of 2, we always get nice wrapping, and the
3239 // last row is always the shortest.
3240 $groupsize = count($this->alpha
);
3242 while ($groupsize > 15) {
3244 $groupsize = ceil(count($this->alpha
) / $groups);
3247 $groupsizelimit = 0;
3249 foreach ($this->alpha
as $letter) {
3250 if ($groupsizelimit++
> 0 && $groupsizelimit %
$groupsize == 1) {
3253 $groupletter = new stdClass();
3254 $groupletter->name
= $letter;
3255 $groupletter->url
= $this->url
->out(false, array($this->urlvar
=> $letter));
3256 if ($letter == $this->current
) {
3257 $groupletter->selected
= $this->current
;
3259 if (!isset($data->group
[$groupnumber])) {
3260 $data->group
[$groupnumber] = new stdClass();
3262 $data->group
[$groupnumber]->letter
[] = $groupletter;
3265 $data->class = $this->class;
3266 $data->title
= $this->title
;
3267 $data->url
= $this->url
->out(false, array($this->urlvar
=> ''));
3268 $data->current
= $this->current
;
3269 $data->all
= get_string('all');
3276 * This class represents how a block appears on a page.
3278 * During output, each block instance is asked to return a block_contents object,
3279 * those are then passed to the $OUTPUT->block function for display.
3281 * contents should probably be generated using a moodle_block_..._renderer.
3283 * Other block-like things that need to appear on the page, for example the
3284 * add new block UI, are also represented as block_contents objects.
3286 * @copyright 2009 Tim Hunt
3287 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3292 class block_contents
{
3294 /** Used when the block cannot be collapsed **/
3295 const NOT_HIDEABLE
= 0;
3297 /** Used when the block can be collapsed but currently is not **/
3300 /** Used when the block has been collapsed **/
3304 * @var int Used to set $skipid.
3306 protected static $idcounter = 1;
3309 * @var int All the blocks (or things that look like blocks) printed on
3310 * a page are given a unique number that can be used to construct id="" attributes.
3311 * This is set automatically be the {@link prepare()} method.
3312 * Do not try to set it manually.
3317 * @var int If this is the contents of a real block, this should be set
3318 * to the block_instance.id. Otherwise this should be set to 0.
3320 public $blockinstanceid = 0;
3323 * @var int If this is a real block instance, and there is a corresponding
3324 * block_position.id for the block on this page, this should be set to that id.
3325 * Otherwise it should be 0.
3327 public $blockpositionid = 0;
3330 * @var array An array of attribute => value pairs that are put on the outer div of this
3331 * block. {@link $id} and {@link $classes} attributes should be set separately.
3336 * @var string The title of this block. If this came from user input, it should already
3337 * have had format_string() processing done on it. This will be output inside
3338 * <h2> tags. Please do not cause invalid XHTML.
3343 * @var string The label to use when the block does not, or will not have a visible title.
3344 * You should never set this as well as title... it will just be ignored.
3346 public $arialabel = '';
3349 * @var string HTML for the content
3351 public $content = '';
3354 * @var array An alternative to $content, it you want a list of things with optional icons.
3356 public $footer = '';
3359 * @var string Any small print that should appear under the block to explain
3360 * to the teacher about the block, for example 'This is a sticky block that was
3361 * added in the system context.'
3363 public $annotation = '';
3366 * @var int One of the constants NOT_HIDEABLE, VISIBLE, HIDDEN. Whether
3367 * the user can toggle whether this block is visible.
3369 public $collapsible = self
::NOT_HIDEABLE
;
3372 * Set this to true if the block is dockable.
3375 public $dockable = false;
3378 * @var array A (possibly empty) array of editing controls. Each element of
3379 * this array should be an array('url' => $url, 'icon' => $icon, 'caption' => $caption).
3380 * $icon is the icon name. Fed to $OUTPUT->image_url.
3382 public $controls = array();
3386 * Create new instance of block content
3387 * @param array $attributes
3389 public function __construct(array $attributes = null) {
3390 $this->skipid
= self
::$idcounter;
3391 self
::$idcounter +
= 1;
3395 $this->attributes
= $attributes;
3397 // simple "fake" blocks used in some modules and "Add new block" block
3398 $this->attributes
= array('class'=>'block');
3403 * Add html class to block
3405 * @param string $class
3407 public function add_class($class) {
3408 $this->attributes
['class'] .= ' '.$class;
3414 * This class represents a target for where a block can go when it is being moved.
3416 * This needs to be rendered as a form with the given hidden from fields, and
3417 * clicking anywhere in the form should submit it. The form action should be
3420 * @copyright 2009 Tim Hunt
3421 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3426 class block_move_target
{
3429 * @var moodle_url Move url
3435 * @param moodle_url $url
3437 public function __construct(moodle_url
$url) {
3445 * This class is used to represent one item within a custom menu that may or may
3446 * not have children.
3448 * @copyright 2010 Sam Hemelryk
3449 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3454 class custom_menu_item
implements renderable
, templatable
{
3457 * @var string The text to show for the item
3462 * @var moodle_url The link to give the icon if it has no children
3467 * @var string A title to apply to the item. By default the text
3472 * @var int A sort order for the item, not necessary if you order things in
3478 * @var custom_menu_item A reference to the parent for this item or NULL if
3479 * it is a top level item
3484 * @var array A array in which to store children this item has.
3486 protected $children = array();
3489 * @var int A reference to the sort var of the last child that was added
3491 protected $lastsort = 0;
3494 * Constructs the new custom menu item
3496 * @param string $text
3497 * @param moodle_url $url A moodle url to apply as the link for this item [Optional]
3498 * @param string $title A title to apply to this item [Optional]
3499 * @param int $sort A sort or to use if we need to sort differently [Optional]
3500 * @param custom_menu_item $parent A reference to the parent custom_menu_item this child
3501 * belongs to, only if the child has a parent. [Optional]
3503 public function __construct($text, moodle_url
$url=null, $title=null, $sort = null, custom_menu_item
$parent = null) {
3504 $this->text
= $text;
3506 $this->title
= $title;
3507 $this->sort
= (int)$sort;
3508 $this->parent
= $parent;
3512 * Adds a custom menu item as a child of this node given its properties.
3514 * @param string $text
3515 * @param moodle_url $url
3516 * @param string $title
3518 * @return custom_menu_item
3520 public function add($text, moodle_url
$url = null, $title = null, $sort = null) {
3521 $key = count($this->children
);
3523 $sort = $this->lastsort +
1;
3525 $this->children
[$key] = new custom_menu_item($text, $url, $title, $sort, $this);
3526 $this->lastsort
= (int)$sort;
3527 return $this->children
[$key];
3531 * Removes a custom menu item that is a child or descendant to the current menu.
3533 * Returns true if child was found and removed.
3535 * @param custom_menu_item $menuitem
3538 public function remove_child(custom_menu_item
$menuitem) {
3540 if (($key = array_search($menuitem, $this->children
)) !== false) {
3541 unset($this->children
[$key]);
3542 $this->children
= array_values($this->children
);
3545 foreach ($this->children
as $child) {
3546 if ($removed = $child->remove_child($menuitem)) {
3555 * Returns the text for this item
3558 public function get_text() {
3563 * Returns the url for this item
3564 * @return moodle_url
3566 public function get_url() {
3571 * Returns the title for this item
3574 public function get_title() {
3575 return $this->title
;
3579 * Sorts and returns the children for this item
3582 public function get_children() {
3584 return $this->children
;
3588 * Gets the sort order for this child
3591 public function get_sort_order() {
3596 * Gets the parent this child belong to
3597 * @return custom_menu_item
3599 public function get_parent() {
3600 return $this->parent
;
3604 * Sorts the children this item has
3606 public function sort() {
3607 usort($this->children
, array('custom_menu','sort_custom_menu_items'));
3611 * Returns true if this item has any children
3614 public function has_children() {
3615 return (count($this->children
) > 0);
3619 * Sets the text for the node
3620 * @param string $text
3622 public function set_text($text) {
3623 $this->text
= (string)$text;
3627 * Sets the title for the node
3628 * @param string $title
3630 public function set_title($title) {
3631 $this->title
= (string)$title;
3635 * Sets the url for the node
3636 * @param moodle_url $url
3638 public function set_url(moodle_url
$url) {
3643 * Export this data so it can be used as the context for a mustache template.
3645 * @param renderer_base $output Used to do a final render of any components that need to be rendered for export.
3648 public function export_for_template(renderer_base
$output) {
3651 require_once($CFG->libdir
. '/externallib.php');
3653 $syscontext = context_system
::instance();
3655 $context = new stdClass();
3656 $context->text
= external_format_string($this->text
, $syscontext->id
);
3657 $context->url
= $this->url ?
$this->url
->out() : null;
3658 $context->title
= external_format_string($this->title
, $syscontext->id
);
3659 $context->sort
= $this->sort
;
3660 $context->children
= array();
3661 if (preg_match("/^#+$/", $this->text
)) {
3662 $context->divider
= true;
3664 $context->haschildren
= !empty($this->children
) && (count($this->children
) > 0);
3665 foreach ($this->children
as $child) {
3666 $child = $child->export_for_template($output);
3667 array_push($context->children
, $child);
3677 * This class is used to operate a custom menu that can be rendered for the page.
3678 * The custom menu is built using $CFG->custommenuitems and is a structured collection
3679 * of custom_menu_item nodes that can be rendered by the core renderer.
3681 * To configure the custom menu:
3682 * Settings: Administration > Appearance > Themes > Theme settings
3684 * @copyright 2010 Sam Hemelryk
3685 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3690 class custom_menu
extends custom_menu_item
{
3693 * @var string The language we should render for, null disables multilang support.
3695 protected $currentlanguage = null;
3698 * Creates the custom menu
3700 * @param string $definition the menu items definition in syntax required by {@link convert_text_to_menu_nodes()}
3701 * @param string $currentlanguage the current language code, null disables multilang support
3703 public function __construct($definition = '', $currentlanguage = null) {
3704 $this->currentlanguage
= $currentlanguage;
3705 parent
::__construct('root'); // create virtual root element of the menu
3706 if (!empty($definition)) {
3707 $this->override_children(self
::convert_text_to_menu_nodes($definition, $currentlanguage));
3712 * Overrides the children of this custom menu. Useful when getting children
3713 * from $CFG->custommenuitems
3715 * @param array $children
3717 public function override_children(array $children) {
3718 $this->children
= array();
3719 foreach ($children as $child) {
3720 if ($child instanceof custom_menu_item
) {
3721 $this->children
[] = $child;
3727 * Converts a string into a structured array of custom_menu_items which can
3728 * then be added to a custom menu.
3731 * text|url|title|langs
3732 * The number of hyphens at the start determines the depth of the item. The
3733 * languages are optional, comma separated list of languages the line is for.
3735 * Example structure:
3736 * First level first item|http://www.moodle.com/
3737 * -Second level first item|http://www.moodle.com/partners/
3738 * -Second level second item|http://www.moodle.com/hq/
3739 * --Third level first item|http://www.moodle.com/jobs/
3740 * -Second level third item|http://www.moodle.com/development/
3741 * First level second item|http://www.moodle.com/feedback/
3742 * First level third item
3743 * English only|http://moodle.com|English only item|en
3744 * German only|http://moodle.de|Deutsch|de,de_du,de_kids
3748 * @param string $text the menu items definition
3749 * @param string $language the language code, null disables multilang support
3752 public static function convert_text_to_menu_nodes($text, $language = null) {
3753 $root = new custom_menu();
3756 $hiddenitems = array();
3757 $lines = explode("\n", $text);
3758 foreach ($lines as $linenumber => $line) {
3759 $line = trim($line);
3760 if (strlen($line) == 0) {
3763 // Parse item settings.
3767 $itemvisible = true;
3768 $settings = explode('|', $line);
3769 foreach ($settings as $i => $setting) {
3770 $setting = trim($setting);
3771 if (!empty($setting)) {
3773 case 0: // Menu text.
3774 $itemtext = ltrim($setting, '-');
3778 $itemurl = new moodle_url($setting);
3779 } catch (moodle_exception
$exception) {
3780 // We're not actually worried about this, we don't want to mess up the display
3781 // just for a wrongly entered URL.
3785 case 2: // Title attribute.
3786 $itemtitle = $setting;
3788 case 3: // Language.
3789 if (!empty($language)) {
3790 $itemlanguages = array_map('trim', explode(',', $setting));
3791 $itemvisible &= in_array($language, $itemlanguages);
3797 // Get depth of new item.
3798 preg_match('/^(\-*)/', $line, $match);
3799 $itemdepth = strlen($match[1]) +
1;
3800 // Find parent item for new item.
3801 while (($lastdepth - $itemdepth) >= 0) {
3802 $lastitem = $lastitem->get_parent();
3805 $lastitem = $lastitem->add($itemtext, $itemurl, $itemtitle, $linenumber +
1);
3807 if (!$itemvisible) {
3808 $hiddenitems[] = $lastitem;
3811 foreach ($hiddenitems as $item) {
3812 $item->parent
->remove_child($item);
3814 return $root->get_children();
3818 * Sorts two custom menu items
3820 * This function is designed to be used with the usort method
3821 * usort($this->children, array('custom_menu','sort_custom_menu_items'));
3824 * @param custom_menu_item $itema
3825 * @param custom_menu_item $itemb
3828 public static function sort_custom_menu_items(custom_menu_item
$itema, custom_menu_item
$itemb) {
3829 $itema = $itema->get_sort_order();
3830 $itemb = $itemb->get_sort_order();
3831 if ($itema == $itemb) {
3834 return ($itema > $itemb) ? +
1 : -1;
3841 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3844 class tabobject
implements renderable
, templatable
{
3845 /** @var string unique id of the tab in this tree, it is used to find selected and/or inactive tabs */
3847 /** @var moodle_url|string link */
3849 /** @var string text on the tab */
3851 /** @var string title under the link, by defaul equals to text */
3853 /** @var bool whether to display a link under the tab name when it's selected */
3854 var $linkedwhenselected = false;
3855 /** @var bool whether the tab is inactive */
3856 var $inactive = false;
3857 /** @var bool indicates that this tab's child is selected */
3858 var $activated = false;
3859 /** @var bool indicates that this tab is selected */
3860 var $selected = false;
3861 /** @var array stores children tabobjects */
3862 var $subtree = array();
3863 /** @var int level of tab in the tree, 0 for root (instance of tabtree), 1 for the first row of tabs */
3869 * @param string $id unique id of the tab in this tree, it is used to find selected and/or inactive tabs
3870 * @param string|moodle_url $link
3871 * @param string $text text on the tab
3872 * @param string $title title under the link, by defaul equals to text
3873 * @param bool $linkedwhenselected whether to display a link under the tab name when it's selected
3875 public function __construct($id, $link = null, $text = '', $title = '', $linkedwhenselected = false) {
3877 $this->link
= $link;
3878 $this->text
= $text;
3879 $this->title
= $title ?
$title : $text;
3880 $this->linkedwhenselected
= $linkedwhenselected;
3884 * Travels through tree and finds the tab to mark as selected, all parents are automatically marked as activated
3886 * @param string $selected the id of the selected tab (whatever row it's on),
3887 * if null marks all tabs as unselected
3888 * @return bool whether this tab is selected or contains selected tab in its subtree
3890 protected function set_selected($selected) {
3891 if ((string)$selected === (string)$this->id
) {
3892 $this->selected
= true;
3893 // This tab is selected. No need to travel through subtree.
3896 foreach ($this->subtree
as $subitem) {
3897 if ($subitem->set_selected($selected)) {
3898 // This tab has child that is selected. Mark it as activated. No need to check other children.
3899 $this->activated
= true;
3907 * Travels through tree and finds a tab with specified id
3910 * @return tabtree|null
3912 public function find($id) {
3913 if ((string)$this->id
=== (string)$id) {
3916 foreach ($this->subtree
as $tab) {
3917 if ($obj = $tab->find($id)) {
3925 * Allows to mark each tab's level in the tree before rendering.
3929 protected function set_level($level) {
3930 $this->level
= $level;
3931 foreach ($this->subtree
as $tab) {
3932 $tab->set_level($level +
1);
3937 * Export for template.
3939 * @param renderer_base $output Renderer.
3942 public function export_for_template(renderer_base
$output) {
3943 if ($this->inactive ||
($this->selected
&& !$this->linkedwhenselected
) ||
$this->activated
) {
3946 $link = $this->link
;
3948 $active = $this->activated ||
$this->selected
;
3952 'link' => is_object($link) ?
$link->out(false) : $link,
3953 'text' => $this->text
,
3954 'title' => $this->title
,
3955 'inactive' => !$active && $this->inactive
,
3956 'active' => $active,
3957 'level' => $this->level
,
3964 * Renderable for the main page header.
3969 * @copyright 2015 Adrian Greeve <adrian@moodle.com>
3970 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
3972 class context_header
implements renderable
{
3975 * @var string $heading Main heading.
3979 * @var int $headinglevel Main heading 'h' tag level.
3981 public $headinglevel;
3983 * @var string|null $imagedata HTML code for the picture in the page header.
3987 * @var array $additionalbuttons Additional buttons for the header e.g. Messaging button for the user header.
3988 * array elements - title => alternate text for the image, or if no image is available the button text.
3989 * url => Link for the button to head to. Should be a moodle_url.
3990 * image => location to the image, or name of the image in /pix/t/{image name}.
3991 * linkattributes => additional attributes for the <a href> element.
3992 * page => page object. Don't include if the image is an external image.
3994 public $additionalbuttons;
3999 * @param string $heading Main heading data.
4000 * @param int $headinglevel Main heading 'h' tag level.
4001 * @param string|null $imagedata HTML code for the picture in the page header.
4002 * @param string $additionalbuttons Buttons for the header e.g. Messaging button for the user header.
4004 public function __construct($heading = null, $headinglevel = 1, $imagedata = null, $additionalbuttons = null) {
4006 $this->heading
= $heading;
4007 $this->headinglevel
= $headinglevel;
4008 $this->imagedata
= $imagedata;
4009 $this->additionalbuttons
= $additionalbuttons;
4010 // If we have buttons then format them.
4011 if (isset($this->additionalbuttons
)) {
4012 $this->format_button_images();
4017 * Adds an array element for a formatted image.
4019 protected function format_button_images() {
4021 foreach ($this->additionalbuttons
as $buttontype => $button) {
4022 $page = $button['page'];
4023 // If no image is provided then just use the title.
4024 if (!isset($button['image'])) {
4025 $this->additionalbuttons
[$buttontype]['formattedimage'] = $button['title'];
4027 // Check to see if this is an internal Moodle icon.
4028 $internalimage = $page->theme
->resolve_image_location('t/' . $button['image'], 'moodle');
4029 if ($internalimage) {
4030 $this->additionalbuttons
[$buttontype]['formattedimage'] = 't/' . $button['image'];
4032 // Treat as an external image.
4033 $this->additionalbuttons
[$buttontype]['formattedimage'] = $button['image'];
4037 if (isset($button['linkattributes']['class'])) {
4038 $class = $button['linkattributes']['class'] . ' btn';
4042 // Add the bootstrap 'btn' class for formatting.
4043 $this->additionalbuttons
[$buttontype]['linkattributes'] = array_merge($button['linkattributes'],
4044 array('class' => $class));
4052 * Example how to print a single line tabs:
4054 * new tabobject(...),
4055 * new tabobject(...)
4057 * echo $OUTPUT->tabtree($rows, $selectedid);
4059 * Multiple row tabs may not look good on some devices but if you want to use them
4060 * you can specify ->subtree for the active tabobject.
4062 * @copyright 2013 Marina Glancy
4063 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4068 class tabtree
extends tabobject
{
4072 * It is highly recommended to call constructor when list of tabs is already
4073 * populated, this way you ensure that selected and inactive tabs are located
4074 * and attribute level is set correctly.
4076 * @param array $tabs array of tabs, each of them may have it's own ->subtree
4077 * @param string|null $selected which tab to mark as selected, all parent tabs will
4078 * automatically be marked as activated
4079 * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4080 * their level. Note that you can as weel specify tabobject::$inactive for separate instances
4082 public function __construct($tabs, $selected = null, $inactive = null) {
4083 $this->subtree
= $tabs;
4084 if ($selected !== null) {
4085 $this->set_selected($selected);
4087 if ($inactive !== null) {
4088 if (is_array($inactive)) {
4089 foreach ($inactive as $id) {
4090 if ($tab = $this->find($id)) {
4091 $tab->inactive
= true;
4094 } else if ($tab = $this->find($inactive)) {
4095 $tab->inactive
= true;
4098 $this->set_level(0);
4102 * Export for template.
4104 * @param renderer_base $output Renderer.
4107 public function export_for_template(renderer_base
$output) {
4111 foreach ($this->subtree
as $tab) {
4112 $tabs[] = $tab->export_for_template($output);
4113 if (!empty($tab->subtree
) && ($tab->level
== 0 ||
$tab->selected ||
$tab->activated
)) {
4114 $secondrow = new tabtree($tab->subtree
);
4120 'secondrow' => $secondrow ?
$secondrow->export_for_template($output) : false
4128 * This action menu component takes a series of primary and secondary actions.
4129 * The primary actions are displayed permanently and the secondary attributes are displayed within a drop
4134 * @copyright 2013 Sam Hemelryk
4135 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4137 class action_menu
implements renderable
, templatable
{
4140 * Top right alignment.
4145 * Top right alignment.
4150 * Top right alignment.
4155 * Top right alignment.
4160 * The instance number. This is unique to this instance of the action menu.
4163 protected $instance = 0;
4166 * An array of primary actions. Please use {@link action_menu::add_primary_action()} to add actions.
4169 protected $primaryactions = array();
4172 * An array of secondary actions. Please use {@link action_menu::add_secondary_action()} to add actions.
4175 protected $secondaryactions = array();
4178 * An array of attributes added to the container of the action menu.
4179 * Initialised with defaults during construction.
4182 public $attributes = array();
4184 * An array of attributes added to the container of the primary actions.
4185 * Initialised with defaults during construction.
4188 public $attributesprimary = array();
4190 * An array of attributes added to the container of the secondary actions.
4191 * Initialised with defaults during construction.
4194 public $attributessecondary = array();
4197 * The string to use next to the icon for the action icon relating to the secondary (dropdown) menu.
4200 public $actiontext = null;
4203 * The string to use for the accessible label for the menu.
4206 public $actionlabel = null;
4209 * An icon to use for the toggling the secondary menu (dropdown).
4215 * Any text to use for the toggling the secondary menu (dropdown).
4218 public $menutrigger = '';
4221 * Any extra classes for toggling to the secondary menu.
4224 public $triggerextraclasses = '';
4227 * Place the action menu before all other actions.
4230 public $prioritise = false;
4233 * Constructs the action menu with the given items.
4235 * @param array $actions An array of actions (action_menu_link|pix_icon|string).
4237 public function __construct(array $actions = array()) {
4238 static $initialised = 0;
4239 $this->instance
= $initialised;
4242 $this->attributes
= array(
4243 'id' => 'action-menu-'.$this->instance
,
4244 'class' => 'moodle-actionmenu',
4245 'data-enhance' => 'moodle-core-actionmenu'
4247 $this->attributesprimary
= array(
4248 'id' => 'action-menu-'.$this->instance
.'-menubar',
4249 'class' => 'menubar',
4252 $this->attributessecondary
= array(
4253 'id' => 'action-menu-'.$this->instance
.'-menu',
4255 'data-rel' => 'menu-content',
4256 'aria-labelledby' => 'action-menu-toggle-'.$this->instance
,
4259 $this->set_alignment(self
::TR
, self
::BR
);
4260 foreach ($actions as $action) {
4261 $this->add($action);
4266 * Sets the label for the menu trigger.
4268 * @param string $label The text
4270 public function set_action_label($label) {
4271 $this->actionlabel
= $label;
4275 * Sets the menu trigger text.
4277 * @param string $trigger The text
4278 * @param string $extraclasses Extra classes to style the secondary menu toggle.
4280 public function set_menu_trigger($trigger, $extraclasses = '') {
4281 $this->menutrigger
= $trigger;
4282 $this->triggerextraclasses
= $extraclasses;
4286 * Return true if there is at least one visible link in the menu.
4290 public function is_empty() {
4291 return !count($this->primaryactions
) && !count($this->secondaryactions
);
4295 * Initialises JS required fore the action menu.
4296 * The JS is only required once as it manages all action menu's on the page.
4298 * @param moodle_page $page
4300 public function initialise_js(moodle_page
$page) {
4301 static $initialised = false;
4302 if (!$initialised) {
4303 $page->requires
->yui_module('moodle-core-actionmenu', 'M.core.actionmenu.init');
4304 $initialised = true;
4309 * Adds an action to this action menu.
4311 * @param action_menu_link|pix_icon|string $action
4313 public function add($action) {
4314 if ($action instanceof action_link
) {
4315 if ($action->primary
) {
4316 $this->add_primary_action($action);
4318 $this->add_secondary_action($action);
4320 } else if ($action instanceof pix_icon
) {
4321 $this->add_primary_action($action);
4323 $this->add_secondary_action($action);
4328 * Adds a primary action to the action menu.
4330 * @param action_menu_link|action_link|pix_icon|string $action
4332 public function add_primary_action($action) {
4333 if ($action instanceof action_link ||
$action instanceof pix_icon
) {
4334 $action->attributes
['role'] = 'menuitem';
4335 if ($action instanceof action_menu_link
) {
4336 $action->actionmenu
= $this;
4339 $this->primaryactions
[] = $action;
4343 * Adds a secondary action to the action menu.
4345 * @param action_link|pix_icon|string $action
4347 public function add_secondary_action($action) {
4348 if ($action instanceof action_link ||
$action instanceof pix_icon
) {
4349 $action->attributes
['role'] = 'menuitem';
4350 if ($action instanceof action_menu_link
) {
4351 $action->actionmenu
= $this;
4354 $this->secondaryactions
[] = $action;
4358 * Returns the primary actions ready to be rendered.
4360 * @param core_renderer $output The renderer to use for getting icons.
4363 public function get_primary_actions(core_renderer
$output = null) {
4365 if ($output === null) {
4368 $pixicon = $this->actionicon
;
4369 $linkclasses = array('toggle-display');
4372 if (!empty($this->menutrigger
)) {
4373 $pixicon = '<b class="caret"></b>';
4374 $linkclasses[] = 'textmenu';
4376 $title = new lang_string('actionsmenu', 'moodle');
4377 $this->actionicon
= new pix_icon(
4381 array('class' => 'iconsmall actionmenu', 'title' => '')
4383 $pixicon = $this->actionicon
;
4385 if ($pixicon instanceof renderable
) {
4386 $pixicon = $output->render($pixicon);
4387 if ($pixicon instanceof pix_icon
&& isset($pixicon->attributes
['alt'])) {
4388 $title = $pixicon->attributes
['alt'];
4392 if ($this->actiontext
) {
4393 $string = $this->actiontext
;
4396 if ($this->actionlabel
) {
4397 $label = $this->actionlabel
;
4401 $actions = $this->primaryactions
;
4402 $attributes = array(
4403 'class' => implode(' ', $linkclasses),
4405 'aria-label' => $label,
4406 'id' => 'action-menu-toggle-'.$this->instance
,
4407 'role' => 'menuitem'
4409 $link = html_writer
::link('#', $string . $this->menutrigger
. $pixicon, $attributes);
4410 if ($this->prioritise
) {
4411 array_unshift($actions, $link);
4419 * Returns the secondary actions ready to be rendered.
4422 public function get_secondary_actions() {
4423 return $this->secondaryactions
;
4427 * Sets the selector that should be used to find the owning node of this menu.
4428 * @param string $selector A CSS/YUI selector to identify the owner of the menu.
4430 public function set_owner_selector($selector) {
4431 $this->attributes
['data-owner'] = $selector;
4435 * Sets the alignment of the dialogue in relation to button used to toggle it.
4437 * @param int $dialogue One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4438 * @param int $button One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4440 public function set_alignment($dialogue, $button) {
4441 if (isset($this->attributessecondary
['data-align'])) {
4442 // We've already got one set, lets remove the old class so as to avoid troubles.
4443 $class = $this->attributessecondary
['class'];
4444 $search = 'align-'.$this->attributessecondary
['data-align'];
4445 $this->attributessecondary
['class'] = str_replace($search, '', $class);
4447 $align = $this->get_align_string($dialogue) . '-' . $this->get_align_string($button);
4448 $this->attributessecondary
['data-align'] = $align;
4449 $this->attributessecondary
['class'] .= ' align-'.$align;
4453 * Returns a string to describe the alignment.
4455 * @param int $align One of action_menu::TL, action_menu::TR, action_menu::BL, action_menu::BR.
4458 protected function get_align_string($align) {
4474 * Sets a constraint for the dialogue.
4476 * The constraint is applied when the dialogue is shown and limits the display of the dialogue to within the
4477 * element the constraint identifies.
4479 * This is required whenever the action menu is displayed inside any CSS element with the .no-overflow class
4480 * (flexible_table and any of it's child classes are a likely candidate).
4482 * @param string $ancestorselector A snippet of CSS used to identify the ancestor to contrain the dialogue to.
4484 public function set_constraint($ancestorselector) {
4485 $this->attributessecondary
['data-constraint'] = $ancestorselector;
4489 * If you call this method the action menu will be displayed but will not be enhanced.
4491 * By not displaying the menu enhanced all items will be displayed in a single row.
4493 * @deprecated since Moodle 3.2
4495 public function do_not_enhance() {
4496 debugging('The method action_menu::do_not_enhance() is deprecated, use a list of action_icon instead.', DEBUG_DEVELOPER
);
4500 * Returns true if this action menu will be enhanced.
4504 public function will_be_enhanced() {
4505 return isset($this->attributes
['data-enhance']);
4509 * Sets nowrap on items. If true menu items should not wrap lines if they are longer than the available space.
4511 * This property can be useful when the action menu is displayed within a parent element that is either floated
4512 * or relatively positioned.
4513 * In that situation the width of the menu is determined by the width of the parent element which may not be large
4514 * enough for the menu items without them wrapping.
4515 * This disables the wrapping so that the menu takes on the width of the longest item.
4517 * @param bool $value If true nowrap gets set, if false it gets removed. Defaults to true.
4519 public function set_nowrap_on_items($value = true) {
4520 $class = 'nowrap-items';
4521 if (!empty($this->attributes
['class'])) {
4522 $pos = strpos($this->attributes
['class'], $class);
4523 if ($value === true && $pos === false) {
4524 // The value is true and the class has not been set yet. Add it.
4525 $this->attributes
['class'] .= ' '.$class;
4526 } else if ($value === false && $pos !== false) {
4527 // The value is false and the class has been set. Remove it.
4528 $this->attributes
['class'] = substr($this->attributes
['class'], $pos, strlen($class));
4530 } else if ($value) {
4531 // The value is true and the class has not been set yet. Add it.
4532 $this->attributes
['class'] = $class;
4537 * Export for template.
4539 * @param renderer_base $output The renderer.
4542 public function export_for_template(renderer_base
$output) {
4543 $data = new stdClass();
4544 $attributes = $this->attributes
;
4545 $attributesprimary = $this->attributesprimary
;
4546 $attributessecondary = $this->attributessecondary
;
4548 $data->instance
= $this->instance
;
4550 $data->classes
= isset($attributes['class']) ?
$attributes['class'] : '';
4551 unset($attributes['class']);
4553 $data->attributes
= array_map(function($key, $value) {
4554 return [ 'name' => $key, 'value' => $value ];
4555 }, array_keys($attributes), $attributes);
4557 $primary = new stdClass();
4558 $primary->title
= '';
4559 $primary->prioritise
= $this->prioritise
;
4561 $primary->classes
= isset($attributesprimary['class']) ?
$attributesprimary['class'] : '';
4562 unset($attributesprimary['class']);
4563 $primary->attributes
= array_map(function($key, $value) {
4564 return [ 'name' => $key, 'value' => $value ];
4565 }, array_keys($attributesprimary), $attributesprimary);
4567 $actionicon = $this->actionicon
;
4568 if (!empty($this->menutrigger
)) {
4569 $primary->menutrigger
= $this->menutrigger
;
4570 $primary->triggerextraclasses
= $this->triggerextraclasses
;
4571 if ($this->actionlabel
) {
4572 $primary->title
= $this->actionlabel
;
4573 } else if ($this->actiontext
) {
4574 $primary->title
= $this->actiontext
;
4576 $primary->title
= strip_tags($this->menutrigger
);
4579 $primary->title
= get_string('actionsmenu');
4580 $iconattributes = ['class' => 'iconsmall actionmenu', 'title' => $primary->title
];
4581 $actionicon = new pix_icon('t/edit_menu', '', 'moodle', $iconattributes);
4584 if ($actionicon instanceof pix_icon
) {
4585 $primary->icon
= $actionicon->export_for_pix();
4586 if (!empty($actionicon->attributes
['alt'])) {
4587 $primary->title
= $actionicon->attributes
['alt'];
4590 $primary->iconraw
= $actionicon ?
$output->render($actionicon) : '';
4593 $primary->actiontext
= $this->actiontext ?
(string) $this->actiontext
: '';
4594 $primary->items
= array_map(function($item) use ($output) {
4595 $data = (object) [];
4596 if ($item instanceof action_menu_link
) {
4597 $data->actionmenulink
= $item->export_for_template($output);
4598 } else if ($item instanceof action_menu_filler
) {
4599 $data->actionmenufiller
= $item->export_for_template($output);
4600 } else if ($item instanceof action_link
) {
4601 $data->actionlink
= $item->export_for_template($output);
4602 } else if ($item instanceof pix_icon
) {
4603 $data->pixicon
= $item->export_for_template($output);
4605 $data->rawhtml
= ($item instanceof renderable
) ?
$output->render($item) : $item;
4608 }, $this->primaryactions
);
4610 $secondary = new stdClass();
4611 $secondary->classes
= isset($attributessecondary['class']) ?
$attributessecondary['class'] : '';
4612 unset($attributessecondary['class']);
4613 $secondary->attributes
= array_map(function($key, $value) {
4614 return [ 'name' => $key, 'value' => $value ];
4615 }, array_keys($attributessecondary), $attributessecondary);
4616 $secondary->items
= array_map(function($item) use ($output) {
4617 $data = (object) [];
4618 if ($item instanceof action_menu_link
) {
4619 $data->actionmenulink
= $item->export_for_template($output);
4620 } else if ($item instanceof action_menu_filler
) {
4621 $data->actionmenufiller
= $item->export_for_template($output);
4622 } else if ($item instanceof action_link
) {
4623 $data->actionlink
= $item->export_for_template($output);
4624 } else if ($item instanceof pix_icon
) {
4625 $data->pixicon
= $item->export_for_template($output);
4627 $data->rawhtml
= ($item instanceof renderable
) ?
$output->render($item) : $item;
4630 }, $this->secondaryactions
);
4632 $data->primary
= $primary;
4633 $data->secondary
= $secondary;
4641 * An action menu filler
4645 * @copyright 2013 Andrew Nicols
4646 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4648 class action_menu_filler
extends action_link
implements renderable
{
4651 * True if this is a primary action. False if not.
4654 public $primary = true;
4657 * Constructs the object.
4659 public function __construct() {
4664 * An action menu action
4668 * @copyright 2013 Sam Hemelryk
4669 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4671 class action_menu_link
extends action_link
implements renderable
{
4674 * True if this is a primary action. False if not.
4677 public $primary = true;
4680 * The action menu this link has been added to.
4683 public $actionmenu = null;
4686 * Constructs the object.
4688 * @param moodle_url $url The URL for the action.
4689 * @param pix_icon $icon The icon to represent the action.
4690 * @param string $text The text to represent the action.
4691 * @param bool $primary Whether this is a primary action or not.
4692 * @param array $attributes Any attribtues associated with the action.
4694 public function __construct(moodle_url
$url, pix_icon
$icon = null, $text, $primary = true, array $attributes = array()) {
4695 parent
::__construct($url, $text, null, $attributes, $icon);
4696 $this->primary
= (bool)$primary;
4697 $this->add_class('menu-action');
4698 $this->attributes
['role'] = 'menuitem';
4702 * Export for template.
4704 * @param renderer_base $output The renderer.
4707 public function export_for_template(renderer_base
$output) {
4708 static $instance = 1;
4710 $data = parent
::export_for_template($output);
4711 $data->instance
= $instance++
;
4713 // Ignore what the parent did with the attributes, except for ID and class.
4714 $data->attributes
= [];
4715 $attributes = $this->attributes
;
4716 unset($attributes['id']);
4717 unset($attributes['class']);
4719 // Handle text being a renderable.
4720 if ($this->text
instanceof renderable
) {
4721 $data->text
= $this->render($this->text
);
4724 $data->showtext
= (!$this->icon ||
$this->primary
=== false);
4728 $icon = $this->icon
;
4729 if ($this->primary ||
!$this->actionmenu
->will_be_enhanced()) {
4730 $attributes['title'] = $data->text
;
4732 $data->icon
= $icon ?
$icon->export_for_pix() : null;
4735 $data->disabled
= !empty($attributes['disabled']);
4736 unset($attributes['disabled']);
4738 $data->attributes
= array_map(function($key, $value) {
4743 }, array_keys($attributes), $attributes);
4750 * A primary action menu action
4754 * @copyright 2013 Sam Hemelryk
4755 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4757 class action_menu_link_primary
extends action_menu_link
{
4759 * Constructs the object.
4761 * @param moodle_url $url
4762 * @param pix_icon $icon
4763 * @param string $text
4764 * @param array $attributes
4766 public function __construct(moodle_url
$url, pix_icon
$icon = null, $text, array $attributes = array()) {
4767 parent
::__construct($url, $icon, $text, true, $attributes);
4772 * A secondary action menu action
4776 * @copyright 2013 Sam Hemelryk
4777 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4779 class action_menu_link_secondary
extends action_menu_link
{
4781 * Constructs the object.
4783 * @param moodle_url $url
4784 * @param pix_icon $icon
4785 * @param string $text
4786 * @param array $attributes
4788 public function __construct(moodle_url
$url, pix_icon
$icon = null, $text, array $attributes = array()) {
4789 parent
::__construct($url, $icon, $text, false, $attributes);
4794 * Represents a set of preferences groups.
4798 * @copyright 2015 Frédéric Massart - FMCorz.net
4799 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4801 class preferences_groups
implements renderable
{
4804 * Array of preferences_group.
4811 * @param array $groups of preferences_group
4813 public function __construct($groups) {
4814 $this->groups
= $groups;
4820 * Represents a group of preferences page link.
4824 * @copyright 2015 Frédéric Massart - FMCorz.net
4825 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4827 class preferences_group
implements renderable
{
4830 * Title of the group.
4836 * Array of navigation_node.
4843 * @param string $title The title.
4844 * @param array $nodes of navigation_node.
4846 public function __construct($title, $nodes) {
4847 $this->title
= $title;
4848 $this->nodes
= $nodes;
4853 * Progress bar class.
4855 * Manages the display of a progress bar.
4857 * To use this class.
4859 * - call create (or use the 3rd param to the constructor)
4860 * - call update or update_full() or update() repeatedly
4862 * @copyright 2008 jamiesensei
4863 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4867 class progress_bar
implements renderable
, templatable
{
4868 /** @var string html id */
4870 /** @var int total width */
4872 /** @var int last percentage printed */
4873 private $percent = 0;
4874 /** @var int time when last printed */
4875 private $lastupdate = 0;
4876 /** @var int when did we start printing this */
4877 private $time_start = 0;
4882 * Prints JS code if $autostart true.
4884 * @param string $htmlid The container ID.
4885 * @param int $width The suggested width.
4886 * @param bool $autostart Whether to start the progress bar right away.
4888 public function __construct($htmlid = '', $width = 500, $autostart = false) {
4889 if (!CLI_SCRIPT
&& !NO_OUTPUT_BUFFERING
) {
4890 debugging('progress_bar used in a non-CLI script without setting NO_OUTPUT_BUFFERING.', DEBUG_DEVELOPER
);
4893 if (!empty($htmlid)) {
4894 $this->html_id
= $htmlid;
4896 $this->html_id
= 'pbar_'.uniqid();
4899 $this->width
= $width;
4907 * Create a new progress bar, this function will output html.
4909 * @return void Echo's output
4911 public function create() {
4914 $this->time_start
= microtime(true);
4916 return; // Temporary solution for cli scripts.
4920 echo $OUTPUT->render($this);
4925 * Update the progress bar.
4927 * @param int $percent From 1-100.
4928 * @param string $msg The message.
4929 * @return void Echo's output
4930 * @throws coding_exception
4932 private function _update($percent, $msg) {
4933 if (empty($this->time_start
)) {
4934 throw new coding_exception('You must call create() (or use the $autostart ' .
4935 'argument to the constructor) before you try updating the progress bar.');
4939 return; // Temporary solution for cli scripts.
4942 $estimate = $this->estimate($percent);
4944 if ($estimate === null) {
4945 // Always do the first and last updates.
4946 } else if ($estimate == 0) {
4947 // Always do the last updates.
4948 } else if ($this->lastupdate +
20 < time()) {
4949 // We must update otherwise browser would time out.
4950 } else if (round($this->percent
, 2) === round($percent, 2)) {
4951 // No significant change, no need to update anything.
4955 $estimatemsg = null;
4956 if (is_numeric($estimate)) {
4957 $estimatemsg = get_string('secondsleft', 'moodle', round($estimate, 2));
4960 $this->percent
= round($percent, 2);
4961 $this->lastupdate
= microtime(true);
4963 echo html_writer
::script(js_writer
::function_call('updateProgressBar',
4964 array($this->html_id
, $this->percent
, $msg, $estimatemsg)));
4969 * Estimate how much time it is going to take.
4971 * @param int $pt From 1-100.
4972 * @return mixed Null (unknown), or int.
4974 private function estimate($pt) {
4975 if ($this->lastupdate
== 0) {
4978 if ($pt < 0.00001) {
4979 return null; // We do not know yet how long it will take.
4981 if ($pt > 99.99999) {
4982 return 0; // Nearly done, right?
4984 $consumed = microtime(true) - $this->time_start
;
4985 if ($consumed < 0.001) {
4989 return (100 - $pt) * ($consumed / $pt);
4993 * Update progress bar according percent.
4995 * @param int $percent From 1-100.
4996 * @param string $msg The message needed to be shown.
4998 public function update_full($percent, $msg) {
4999 $percent = max(min($percent, 100), 0);
5000 $this->_update($percent, $msg);
5004 * Update progress bar according the number of tasks.
5006 * @param int $cur Current task number.
5007 * @param int $total Total task number.
5008 * @param string $msg The message needed to be shown.
5010 public function update($cur, $total, $msg) {
5011 $percent = ($cur / $total) * 100;
5012 $this->update_full($percent, $msg);
5016 * Restart the progress bar.
5018 public function restart() {
5020 $this->lastupdate
= 0;
5021 $this->time_start
= 0;
5025 * Export for template.
5027 * @param renderer_base $output The renderer.
5030 public function export_for_template(renderer_base
$output) {
5032 'id' => $this->html_id
,
5033 'width' => $this->width
,