Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.

Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 and 403]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  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/>.
  16  
  17  /**
  18   * Classes for rendering HTML output for Moodle.
  19   *
  20   * Please see {@link http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML}
  21   * for an overview.
  22   *
  23   * Included in this file are the primary renderer classes:
  24   *     - renderer_base:         The renderer outline class that all renderers
  25   *                              should inherit from.
  26   *     - core_renderer:         The standard HTML renderer.
  27   *     - core_renderer_cli:     An adaption of the standard renderer for CLI scripts.
  28   *     - core_renderer_ajax:    An adaption of the standard renderer for AJAX scripts.
  29   *     - plugin_renderer_base:  A renderer class that should be extended by all
  30   *                              plugin renderers.
  31   *
  32   * @package core
  33   * @category output
  34   * @copyright  2009 Tim Hunt
  35   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  36   */
  37  
  38  use core\output\named_templatable;
  39  use core_completion\cm_completion_details;
  40  use core_course\output\activity_information;
  41  
  42  defined('MOODLE_INTERNAL') || die();
  43  
  44  /**
  45   * Simple base class for Moodle renderers.
  46   *
  47   * Tracks the xhtml_container_stack to use, which is passed in in the constructor.
  48   *
  49   * Also has methods to facilitate generating HTML output.
  50   *
  51   * @copyright 2009 Tim Hunt
  52   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  53   * @since Moodle 2.0
  54   * @package core
  55   * @category output
  56   */
  57  class renderer_base {
  58      /**
  59       * @var xhtml_container_stack The xhtml_container_stack to use.
  60       */
  61      protected $opencontainers;
  62  
  63      /**
  64       * @var moodle_page The Moodle page the renderer has been created to assist with.
  65       */
  66      protected $page;
  67  
  68      /**
  69       * @var string The requested rendering target.
  70       */
  71      protected $target;
  72  
  73      /**
  74       * @var Mustache_Engine $mustache The mustache template compiler
  75       */
  76      private $mustache;
  77  
  78      /**
  79       * @var array $templatecache The mustache template cache.
  80       */
  81      protected $templatecache = [];
  82  
  83      /**
  84       * Return an instance of the mustache class.
  85       *
  86       * @since 2.9
  87       * @return Mustache_Engine
  88       */
  89      protected function get_mustache() {
  90          global $CFG;
  91  
  92          if ($this->mustache === null) {
  93              require_once("{$CFG->libdir}/filelib.php");
  94  
  95              $themename = $this->page->theme->name;
  96              $themerev = theme_get_revision();
  97  
  98              // Create new localcache directory.
  99              $cachedir = make_localcache_directory("mustache/$themerev/$themename");
 100  
 101              // Remove old localcache directories.
 102              $mustachecachedirs = glob("{$CFG->localcachedir}/mustache/*", GLOB_ONLYDIR);
 103              foreach ($mustachecachedirs as $localcachedir) {
 104                  $cachedrev = [];
 105                  preg_match("/\/mustache\/([0-9]+)$/", $localcachedir, $cachedrev);
 106                  $cachedrev = isset($cachedrev[1]) ? intval($cachedrev[1]) : 0;
 107                  if ($cachedrev > 0 && $cachedrev < $themerev) {
 108                      fulldelete($localcachedir);
 109                  }
 110              }
 111  
 112              $loader = new \core\output\mustache_filesystem_loader();
 113              $stringhelper = new \core\output\mustache_string_helper();
 114              $cleanstringhelper = new \core\output\mustache_clean_string_helper();
 115              $quotehelper = new \core\output\mustache_quote_helper();
 116              $jshelper = new \core\output\mustache_javascript_helper($this->page);
 117              $pixhelper = new \core\output\mustache_pix_helper($this);
 118              $shortentexthelper = new \core\output\mustache_shorten_text_helper();
 119              $userdatehelper = new \core\output\mustache_user_date_helper();
 120  
 121              // We only expose the variables that are exposed to JS templates.
 122              $safeconfig = $this->page->requires->get_config_for_javascript($this->page, $this);
 123  
 124              $helpers = array('config' => $safeconfig,
 125                               'str' => array($stringhelper, 'str'),
 126                               'cleanstr' => array($cleanstringhelper, 'cleanstr'),
 127                               'quote' => array($quotehelper, 'quote'),
 128                               'js' => array($jshelper, 'help'),
 129                               'pix' => array($pixhelper, 'pix'),
 130                               'shortentext' => array($shortentexthelper, 'shorten'),
 131                               'userdate' => array($userdatehelper, 'transform'),
 132                           );
 133  
 134              $this->mustache = new \core\output\mustache_engine(array(
 135                  'cache' => $cachedir,
 136                  'escape' => 's',
 137                  'loader' => $loader,
 138                  'helpers' => $helpers,
 139                  'pragmas' => [Mustache_Engine::PRAGMA_BLOCKS],
 140                  // Don't allow the JavaScript helper to be executed from within another
 141                  // helper. If it's allowed it can be used by users to inject malicious
 142                  // JS into the page.
 143                  'disallowednestedhelpers' => ['js'],
 144                  // Disable lambda rendering - content in helpers is already rendered, no need to render it again.
 145                  'disable_lambda_rendering' => true,
 146              ));
 147  
 148          }
 149  
 150          return $this->mustache;
 151      }
 152  
 153  
 154      /**
 155       * Constructor
 156       *
 157       * The constructor takes two arguments. The first is the page that the renderer
 158       * has been created to assist with, and the second is the target.
 159       * The target is an additional identifier that can be used to load different
 160       * renderers for different options.
 161       *
 162       * @param moodle_page $page the page we are doing output for.
 163       * @param string $target one of rendering target constants
 164       */
 165      public function __construct(moodle_page $page, $target) {
 166          $this->opencontainers = $page->opencontainers;
 167          $this->page = $page;
 168          $this->target = $target;
 169      }
 170  
 171      /**
 172       * Renders a template by name with the given context.
 173       *
 174       * The provided data needs to be array/stdClass made up of only simple types.
 175       * Simple types are array,stdClass,bool,int,float,string
 176       *
 177       * @since 2.9
 178       * @param array|stdClass $context Context containing data for the template.
 179       * @return string|boolean
 180       */
 181      public function render_from_template($templatename, $context) {
 182          $mustache = $this->get_mustache();
 183  
 184          try {
 185              // Grab a copy of the existing helper to be restored later.
 186              $uniqidhelper = $mustache->getHelper('uniqid');
 187          } catch (Mustache_Exception_UnknownHelperException $e) {
 188              // Helper doesn't exist.
 189              $uniqidhelper = null;
 190          }
 191  
 192          // Provide 1 random value that will not change within a template
 193          // but will be different from template to template. This is useful for
 194          // e.g. aria attributes that only work with id attributes and must be
 195          // unique in a page.
 196          $mustache->addHelper('uniqid', new \core\output\mustache_uniqid_helper());
 197          if (isset($this->templatecache[$templatename])) {
 198              $template = $this->templatecache[$templatename];
 199          } else {
 200              try {
 201                  $template = $mustache->loadTemplate($templatename);
 202                  $this->templatecache[$templatename] = $template;
 203              } catch (Mustache_Exception_UnknownTemplateException $e) {
 204                  throw new moodle_exception('Unknown template: ' . $templatename);
 205              }
 206          }
 207  
 208          $renderedtemplate = trim($template->render($context));
 209  
 210          // If we had an existing uniqid helper then we need to restore it to allow
 211          // handle nested calls of render_from_template.
 212          if ($uniqidhelper) {
 213              $mustache->addHelper('uniqid', $uniqidhelper);
 214          }
 215  
 216          return $renderedtemplate;
 217      }
 218  
 219  
 220      /**
 221       * Returns rendered widget.
 222       *
 223       * The provided widget needs to be an object that extends the renderable
 224       * interface.
 225       * If will then be rendered by a method based upon the classname for the widget.
 226       * For instance a widget of class `crazywidget` will be rendered by a protected
 227       * render_crazywidget method of this renderer.
 228       * If no render_crazywidget method exists and crazywidget implements templatable,
 229       * look for the 'crazywidget' template in the same component and render that.
 230       *
 231       * @param renderable $widget instance with renderable interface
 232       * @return string
 233       */
 234      public function render(renderable $widget) {
 235          $classparts = explode('\\', get_class($widget));
 236          // Strip namespaces.
 237          $classname = array_pop($classparts);
 238          // Remove _renderable suffixes.
 239          $classname = preg_replace('/_renderable$/', '', $classname);
 240  
 241          $rendermethod = "render_{$classname}";
 242          if (method_exists($this, $rendermethod)) {
 243              // Call the render_[widget_name] function.
 244              // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
 245              return $this->$rendermethod($widget);
 246          }
 247  
 248          if ($widget instanceof named_templatable) {
 249              // This is a named templatable.
 250              // Fetch the template name from the get_template_name function instead.
 251              // Note: This has higher priority than the guessed template name.
 252              return $this->render_from_template(
 253                  $widget->get_template_name($this),
 254                  $widget->export_for_template($this)
 255              );
 256          }
 257  
 258          if ($widget instanceof templatable) {
 259              // Guess the templat ename based on the class name.
 260              // Note: There's no benefit to moving this aboved the named_templatable and this approach is more costly.
 261              $component = array_shift($classparts);
 262              if (!$component) {
 263                  $component = 'core';
 264              }
 265              $template = $component . '/' . $classname;
 266              $context = $widget->export_for_template($this);
 267              return $this->render_from_template($template, $context);
 268          }
 269          throw new coding_exception("Can not render widget, renderer method ('{$rendermethod}') not found.");
 270      }
 271  
 272      /**
 273       * Adds a JS action for the element with the provided id.
 274       *
 275       * This method adds a JS event for the provided component action to the page
 276       * and then returns the id that the event has been attached to.
 277       * If no id has been provided then a new ID is generated by {@link html_writer::random_id()}
 278       *
 279       * @param component_action $action
 280       * @param string $id
 281       * @return string id of element, either original submitted or random new if not supplied
 282       */
 283      public function add_action_handler(component_action $action, $id = null) {
 284          if (!$id) {
 285              $id = html_writer::random_id($action->event);
 286          }
 287          $this->page->requires->event_handler("#$id", $action->event, $action->jsfunction, $action->jsfunctionargs);
 288          return $id;
 289      }
 290  
 291      /**
 292       * Returns true is output has already started, and false if not.
 293       *
 294       * @return boolean true if the header has been printed.
 295       */
 296      public function has_started() {
 297          return $this->page->state >= moodle_page::STATE_IN_BODY;
 298      }
 299  
 300      /**
 301       * Given an array or space-separated list of classes, prepares and returns the HTML class attribute value
 302       *
 303       * @param mixed $classes Space-separated string or array of classes
 304       * @return string HTML class attribute value
 305       */
 306      public static function prepare_classes($classes) {
 307          if (is_array($classes)) {
 308              return implode(' ', array_unique($classes));
 309          }
 310          return $classes;
 311      }
 312  
 313      /**
 314       * Return the direct URL for an image from the pix folder.
 315       *
 316       * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template.
 317       *
 318       * @deprecated since Moodle 3.3
 319       * @param string $imagename the name of the icon.
 320       * @param string $component specification of one plugin like in get_string()
 321       * @return moodle_url
 322       */
 323      public function pix_url($imagename, $component = 'moodle') {
 324          debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER);
 325          return $this->page->theme->image_url($imagename, $component);
 326      }
 327  
 328      /**
 329       * Return the moodle_url for an image.
 330       *
 331       * The exact image location and extension is determined
 332       * automatically by searching for gif|png|jpg|jpeg, please
 333       * note there can not be diferent images with the different
 334       * extension. The imagename is for historical reasons
 335       * a relative path name, it may be changed later for core
 336       * images. It is recommended to not use subdirectories
 337       * in plugin and theme pix directories.
 338       *
 339       * There are three types of images:
 340       * 1/ theme images  - stored in theme/mytheme/pix/,
 341       *                    use component 'theme'
 342       * 2/ core images   - stored in /pix/,
 343       *                    overridden via theme/mytheme/pix_core/
 344       * 3/ plugin images - stored in mod/mymodule/pix,
 345       *                    overridden via theme/mytheme/pix_plugins/mod/mymodule/,
 346       *                    example: image_url('comment', 'mod_glossary')
 347       *
 348       * @param string $imagename the pathname of the image
 349       * @param string $component full plugin name (aka component) or 'theme'
 350       * @return moodle_url
 351       */
 352      public function image_url($imagename, $component = 'moodle') {
 353          return $this->page->theme->image_url($imagename, $component);
 354      }
 355  
 356      /**
 357       * Return the site's logo URL, if any.
 358       *
 359       * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
 360       * @param int $maxheight The maximum height, or null when the maximum height does not matter.
 361       * @return moodle_url|false
 362       */
 363      public function get_logo_url($maxwidth = null, $maxheight = 200) {
 364          global $CFG;
 365          $logo = get_config('core_admin', 'logo');
 366          if (empty($logo)) {
 367              return false;
 368          }
 369  
 370          // 200px high is the default image size which should be displayed at 100px in the page to account for retina displays.
 371          // It's not worth the overhead of detecting and serving 2 different images based on the device.
 372  
 373          // Hide the requested size in the file path.
 374          $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
 375  
 376          // Use $CFG->themerev to prevent browser caching when the file changes.
 377          return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logo', $filepath,
 378              theme_get_revision(), $logo);
 379      }
 380  
 381      /**
 382       * Return the site's compact logo URL, if any.
 383       *
 384       * @param int $maxwidth The maximum width, or null when the maximum width does not matter.
 385       * @param int $maxheight The maximum height, or null when the maximum height does not matter.
 386       * @return moodle_url|false
 387       */
 388      public function get_compact_logo_url($maxwidth = 300, $maxheight = 300) {
 389          global $CFG;
 390          $logo = get_config('core_admin', 'logocompact');
 391          if (empty($logo)) {
 392              return false;
 393          }
 394  
 395          // Hide the requested size in the file path.
 396          $filepath = ((int) $maxwidth . 'x' . (int) $maxheight) . '/';
 397  
 398          // Use $CFG->themerev to prevent browser caching when the file changes.
 399          return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'logocompact', $filepath,
 400              theme_get_revision(), $logo);
 401      }
 402  
 403      /**
 404       * Whether we should display the logo in the navbar.
 405       *
 406       * We will when there are no main logos, and we have compact logo.
 407       *
 408       * @return bool
 409       */
 410      public function should_display_navbar_logo() {
 411          $logo = $this->get_compact_logo_url();
 412          return !empty($logo);
 413      }
 414  
 415      /**
 416       * Whether we should display the main logo.
 417       * @deprecated since Moodle 4.0
 418       * @todo final deprecation. To be removed in Moodle 4.4 MDL-73165.
 419       * @param int $headinglevel The heading level we want to check against.
 420       * @return bool
 421       */
 422      public function should_display_main_logo($headinglevel = 1) {
 423          debugging('should_display_main_logo() is deprecated and will be removed in Moodle 4.4.', DEBUG_DEVELOPER);
 424          // Only render the logo if we're on the front page or login page and the we have a logo.
 425          $logo = $this->get_logo_url();
 426          if ($headinglevel == 1 && !empty($logo)) {
 427              if ($this->page->pagelayout == 'frontpage' || $this->page->pagelayout == 'login') {
 428                  return true;
 429              }
 430          }
 431  
 432          return false;
 433      }
 434  
 435  }
 436  
 437  
 438  /**
 439   * Basis for all plugin renderers.
 440   *
 441   * @copyright Petr Skoda (skodak)
 442   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 443   * @since Moodle 2.0
 444   * @package core
 445   * @category output
 446   */
 447  class plugin_renderer_base extends renderer_base {
 448  
 449      /**
 450       * @var renderer_base|core_renderer A reference to the current renderer.
 451       * The renderer provided here will be determined by the page but will in 90%
 452       * of cases by the {@link core_renderer}
 453       */
 454      protected $output;
 455  
 456      /**
 457       * Constructor method, calls the parent constructor
 458       *
 459       * @param moodle_page $page
 460       * @param string $target one of rendering target constants
 461       */
 462      public function __construct(moodle_page $page, $target) {
 463          if (empty($target) && $page->pagelayout === 'maintenance') {
 464              // If the page is using the maintenance layout then we're going to force the target to maintenance.
 465              // This way we'll get a special maintenance renderer that is designed to block access to API's that are likely
 466              // unavailable for this page layout.
 467              $target = RENDERER_TARGET_MAINTENANCE;
 468          }
 469          $this->output = $page->get_renderer('core', null, $target);
 470          parent::__construct($page, $target);
 471      }
 472  
 473      /**
 474       * Renders the provided widget and returns the HTML to display it.
 475       *
 476       * @param renderable $widget instance with renderable interface
 477       * @return string
 478       */
 479      public function render(renderable $widget) {
 480          $classname = get_class($widget);
 481  
 482          // Strip namespaces.
 483          $classname = preg_replace('/^.*\\\/', '', $classname);
 484  
 485          // Keep a copy at this point, we may need to look for a deprecated method.
 486          $deprecatedmethod = "render_{$classname}";
 487  
 488          // Remove _renderable suffixes.
 489          $classname = preg_replace('/_renderable$/', '', $classname);
 490          $rendermethod = "render_{$classname}";
 491  
 492          if (method_exists($this, $rendermethod)) {
 493              // Call the render_[widget_name] function.
 494              // Note: This has a higher priority than the named_templatable to allow the theme to override the template.
 495              return $this->$rendermethod($widget);
 496          }
 497  
 498          if ($widget instanceof named_templatable) {
 499              // This is a named templatable.
 500              // Fetch the template name from the get_template_name function instead.
 501              // Note: This has higher priority than the deprecated method which is not overridable by themes anyway.
 502              return $this->render_from_template(
 503                  $widget->get_template_name($this),
 504                  $widget->export_for_template($this)
 505              );
 506          }
 507  
 508          if ($rendermethod !== $deprecatedmethod && method_exists($this, $deprecatedmethod)) {
 509              // This is exactly where we don't want to be.
 510              // If you have arrived here you have a renderable component within your plugin that has the name
 511              // blah_renderable, and you have a render method render_blah_renderable on your plugin.
 512              // In 2.8 we revamped output, as part of this change we changed slightly how renderables got rendered
 513              // and the _renderable suffix now gets removed when looking for a render method.
 514              // You need to change your renderers render_blah_renderable to render_blah.
 515              // Until you do this it will not be possible for a theme to override the renderer to override your method.
 516              // Please do it ASAP.
 517              static $debugged = [];
 518              if (!isset($debugged[$deprecatedmethod])) {
 519                  debugging(sprintf(
 520                      'Deprecated call. Please rename your renderables render method from %s to %s.',
 521                      $deprecatedmethod,
 522                      $rendermethod
 523                  ), DEBUG_DEVELOPER);
 524                  $debugged[$deprecatedmethod] = true;
 525              }
 526              return $this->$deprecatedmethod($widget);
 527          }
 528  
 529          // Pass to core renderer if method not found here.
 530          // Note: this is not a parent. This is _new_ renderer which respects the requested format, and output type.
 531          return $this->output->render($widget);
 532      }
 533  
 534      /**
 535       * Magic method used to pass calls otherwise meant for the standard renderer
 536       * to it to ensure we don't go causing unnecessary grief.
 537       *
 538       * @param string $method
 539       * @param array $arguments
 540       * @return mixed
 541       */
 542      public function __call($method, $arguments) {
 543          if (method_exists('renderer_base', $method)) {
 544              throw new coding_exception('Protected method called against '.get_class($this).' :: '.$method);
 545          }
 546          if (method_exists($this->output, $method)) {
 547              return call_user_func_array(array($this->output, $method), $arguments);
 548          } else {
 549              throw new coding_exception('Unknown method called against '.get_class($this).' :: '.$method);
 550          }
 551      }
 552  }
 553  
 554  
 555  /**
 556   * The standard implementation of the core_renderer interface.
 557   *
 558   * @copyright 2009 Tim Hunt
 559   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 560   * @since Moodle 2.0
 561   * @package core
 562   * @category output
 563   */
 564  class core_renderer extends renderer_base {
 565      /**
 566       * Do NOT use, please use <?php echo $OUTPUT->main_content() ?>
 567       * in layout files instead.
 568       * @deprecated
 569       * @var string used in {@link core_renderer::header()}.
 570       */
 571      const MAIN_CONTENT_TOKEN = '[MAIN CONTENT GOES HERE]';
 572  
 573      /**
 574       * @var string Used to pass information from {@link core_renderer::doctype()} to
 575       * {@link core_renderer::standard_head_html()}.
 576       */
 577      protected $contenttype;
 578  
 579      /**
 580       * @var string Used by {@link core_renderer::redirect_message()} method to communicate
 581       * with {@link core_renderer::header()}.
 582       */
 583      protected $metarefreshtag = '';
 584  
 585      /**
 586       * @var string Unique token for the closing HTML
 587       */
 588      protected $unique_end_html_token;
 589  
 590      /**
 591       * @var string Unique token for performance information
 592       */
 593      protected $unique_performance_info_token;
 594  
 595      /**
 596       * @var string Unique token for the main content.
 597       */
 598      protected $unique_main_content_token;
 599  
 600      /** @var custom_menu_item language The language menu if created */
 601      protected $language = null;
 602  
 603      /**
 604       * Constructor
 605       *
 606       * @param moodle_page $page the page we are doing output for.
 607       * @param string $target one of rendering target constants
 608       */
 609      public function __construct(moodle_page $page, $target) {
 610          $this->opencontainers = $page->opencontainers;
 611          $this->page = $page;
 612          $this->target = $target;
 613  
 614          $this->unique_end_html_token = '%%ENDHTML-'.sesskey().'%%';
 615          $this->unique_performance_info_token = '%%PERFORMANCEINFO-'.sesskey().'%%';
 616          $this->unique_main_content_token = '[MAIN CONTENT GOES HERE - '.sesskey().']';
 617      }
 618  
 619      /**
 620       * Get the DOCTYPE declaration that should be used with this page. Designed to
 621       * be called in theme layout.php files.
 622       *
 623       * @return string the DOCTYPE declaration that should be used.
 624       */
 625      public function doctype() {
 626          if ($this->page->theme->doctype === 'html5') {
 627              $this->contenttype = 'text/html; charset=utf-8';
 628              return "<!DOCTYPE html>\n";
 629  
 630          } else if ($this->page->theme->doctype === 'xhtml5') {
 631              $this->contenttype = 'application/xhtml+xml; charset=utf-8';
 632              return "<!DOCTYPE html>\n";
 633  
 634          } else {
 635              // legacy xhtml 1.0
 636              $this->contenttype = 'text/html; charset=utf-8';
 637              return ('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . "\n");
 638          }
 639      }
 640  
 641      /**
 642       * The attributes that should be added to the <html> tag. Designed to
 643       * be called in theme layout.php files.
 644       *
 645       * @return string HTML fragment.
 646       */
 647      public function htmlattributes() {
 648          $return = get_html_lang(true);
 649          $attributes = array();
 650          if ($this->page->theme->doctype !== 'html5') {
 651              $attributes['xmlns'] = 'http://www.w3.org/1999/xhtml';
 652          }
 653  
 654          // Give plugins an opportunity to add things like xml namespaces to the html element.
 655          // This function should return an array of html attribute names => values.
 656          $pluginswithfunction = get_plugins_with_function('add_htmlattributes', 'lib.php');
 657          foreach ($pluginswithfunction as $plugins) {
 658              foreach ($plugins as $function) {
 659                  $newattrs = $function();
 660                  unset($newattrs['dir']);
 661                  unset($newattrs['lang']);
 662                  unset($newattrs['xmlns']);
 663                  unset($newattrs['xml:lang']);
 664                  $attributes += $newattrs;
 665              }
 666          }
 667  
 668          foreach ($attributes as $key => $val) {
 669              $val = s($val);
 670              $return .= " $key=\"$val\"";
 671          }
 672  
 673          return $return;
 674      }
 675  
 676      /**
 677       * The standard tags (meta tags, links to stylesheets and JavaScript, etc.)
 678       * that should be included in the <head> tag. Designed to be called in theme
 679       * layout.php files.
 680       *
 681       * @return string HTML fragment.
 682       */
 683      public function standard_head_html() {
 684          global $CFG, $SESSION, $SITE;
 685  
 686          // Before we output any content, we need to ensure that certain
 687          // page components are set up.
 688  
 689          // Blocks must be set up early as they may require javascript which
 690          // has to be included in the page header before output is created.
 691          foreach ($this->page->blocks->get_regions() as $region) {
 692              $this->page->blocks->ensure_content_created($region, $this);
 693          }
 694  
 695          $output = '';
 696  
 697          // Give plugins an opportunity to add any head elements. The callback
 698          // must always return a string containing valid html head content.
 699          $pluginswithfunction = get_plugins_with_function('before_standard_html_head', 'lib.php');
 700          foreach ($pluginswithfunction as $plugins) {
 701              foreach ($plugins as $function) {
 702                  $output .= $function();
 703              }
 704          }
 705  
 706          // Allow a url_rewrite plugin to setup any dynamic head content.
 707          if (isset($CFG->urlrewriteclass) && !isset($CFG->upgraderunning)) {
 708              $class = $CFG->urlrewriteclass;
 709              $output .= $class::html_head_setup();
 710          }
 711  
 712          $output .= '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . "\n";
 713          $output .= '<meta name="keywords" content="moodle, ' . $this->page->title . '" />' . "\n";
 714          // This is only set by the {@link redirect()} method
 715          $output .= $this->metarefreshtag;
 716  
 717          // Check if a periodic refresh delay has been set and make sure we arn't
 718          // already meta refreshing
 719          if ($this->metarefreshtag=='' && $this->page->periodicrefreshdelay!==null) {
 720              $output .= '<meta http-equiv="refresh" content="'.$this->page->periodicrefreshdelay.';url='.$this->page->url->out().'" />';
 721          }
 722  
 723          // Set up help link popups for all links with the helptooltip class
 724          $this->page->requires->js_init_call('M.util.help_popups.setup');
 725  
 726          $focus = $this->page->focuscontrol;
 727          if (!empty($focus)) {
 728              if (preg_match("#forms\['([a-zA-Z0-9]+)'\].elements\['([a-zA-Z0-9]+)'\]#", $focus, $matches)) {
 729                  // This is a horrifically bad way to handle focus but it is passed in
 730                  // through messy formslib::moodleform
 731                  $this->page->requires->js_function_call('old_onload_focus', array($matches[1], $matches[2]));
 732              } else if (strpos($focus, '.')!==false) {
 733                  // Old style of focus, bad way to do it
 734                  debugging('This code is using the old style focus event, Please update this code to focus on an element id or the moodleform focus method.', DEBUG_DEVELOPER);
 735                  $this->page->requires->js_function_call('old_onload_focus', explode('.', $focus, 2));
 736              } else {
 737                  // Focus element with given id
 738                  $this->page->requires->js_function_call('focuscontrol', array($focus));
 739              }
 740          }
 741  
 742          // Get the theme stylesheet - this has to be always first CSS, this loads also styles.css from all plugins;
 743          // any other custom CSS can not be overridden via themes and is highly discouraged
 744          $urls = $this->page->theme->css_urls($this->page);
 745          foreach ($urls as $url) {
 746              $this->page->requires->css_theme($url);
 747          }
 748  
 749          // Get the theme javascript head and footer
 750          if ($jsurl = $this->page->theme->javascript_url(true)) {
 751              $this->page->requires->js($jsurl, true);
 752          }
 753          if ($jsurl = $this->page->theme->javascript_url(false)) {
 754              $this->page->requires->js($jsurl);
 755          }
 756  
 757          // Get any HTML from the page_requirements_manager.
 758          $output .= $this->page->requires->get_head_code($this->page, $this);
 759  
 760          // List alternate versions.
 761          foreach ($this->page->alternateversions as $type => $alt) {
 762              $output .= html_writer::empty_tag('link', array('rel' => 'alternate',
 763                      'type' => $type, 'title' => $alt->title, 'href' => $alt->url));
 764          }
 765  
 766          // Add noindex tag if relevant page and setting applied.
 767          $allowindexing = isset($CFG->allowindexing) ? $CFG->allowindexing : 0;
 768          $loginpages = array('login-index', 'login-signup');
 769          if ($allowindexing == 2 || ($allowindexing == 0 && in_array($this->page->pagetype, $loginpages))) {
 770              if (!isset($CFG->additionalhtmlhead)) {
 771                  $CFG->additionalhtmlhead = '';
 772              }
 773              $CFG->additionalhtmlhead .= '<meta name="robots" content="noindex" />';
 774          }
 775  
 776          if (!empty($CFG->additionalhtmlhead)) {
 777              $output .= "\n".$CFG->additionalhtmlhead;
 778          }
 779  
 780          if ($this->page->pagelayout == 'frontpage') {
 781              $summary = s(strip_tags(format_text($SITE->summary, FORMAT_HTML)));
 782              if (!empty($summary)) {
 783                  $output .= "<meta name=\"description\" content=\"$summary\" />\n";
 784              }
 785          }
 786  
 787          return $output;
 788      }
 789  
 790      /**
 791       * The standard tags (typically skip links) that should be output just inside
 792       * the start of the <body> tag. Designed to be called in theme layout.php files.
 793       *
 794       * @return string HTML fragment.
 795       */
 796      public function standard_top_of_body_html() {
 797          global $CFG;
 798          $output = $this->page->requires->get_top_of_body_code($this);
 799          if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmltopofbody)) {
 800              $output .= "\n".$CFG->additionalhtmltopofbody;
 801          }
 802  
 803          // Give subsystems an opportunity to inject extra html content. The callback
 804          // must always return a string containing valid html.
 805          foreach (\core_component::get_core_subsystems() as $name => $path) {
 806              if ($path) {
 807                  $output .= component_callback($name, 'before_standard_top_of_body_html', [], '');
 808              }
 809          }
 810  
 811          // Give plugins an opportunity to inject extra html content. The callback
 812          // must always return a string containing valid html.
 813          $pluginswithfunction = get_plugins_with_function('before_standard_top_of_body_html', 'lib.php');
 814          foreach ($pluginswithfunction as $plugins) {
 815              foreach ($plugins as $function) {
 816                  $output .= $function();
 817              }
 818          }
 819  
 820          $output .= $this->maintenance_warning();
 821  
 822          return $output;
 823      }
 824  
 825      /**
 826       * Scheduled maintenance warning message.
 827       *
 828       * Note: This is a nasty hack to display maintenance notice, this should be moved
 829       *       to some general notification area once we have it.
 830       *
 831       * @return string
 832       */
 833      public function maintenance_warning() {
 834          global $CFG;
 835  
 836          $output = '';
 837          if (isset($CFG->maintenance_later) and $CFG->maintenance_later > time()) {
 838              $timeleft = $CFG->maintenance_later - time();
 839              // If timeleft less than 30 sec, set the class on block to error to highlight.
 840              $errorclass = ($timeleft < 30) ? 'alert-error alert-danger' : 'alert-warning';
 841              $output .= $this->box_start($errorclass . ' moodle-has-zindex maintenancewarning m-3 alert');
 842              $a = new stdClass();
 843              $a->hour = (int)($timeleft / 3600);
 844              $a->min = (int)(($timeleft / 60) % 60);
 845              $a->sec = (int)($timeleft % 60);
 846              if ($a->hour > 0) {
 847                  $output .= get_string('maintenancemodeisscheduledlong', 'admin', $a);
 848              } else {
 849                  $output .= get_string('maintenancemodeisscheduled', 'admin', $a);
 850              }
 851  
 852              $output .= $this->box_end();
 853              $this->page->requires->yui_module('moodle-core-maintenancemodetimer', 'M.core.maintenancemodetimer',
 854                      array(array('timeleftinsec' => $timeleft)));
 855              $this->page->requires->strings_for_js(
 856                      array('maintenancemodeisscheduled', 'maintenancemodeisscheduledlong', 'sitemaintenance'),
 857                      'admin');
 858          }
 859          return $output;
 860      }
 861  
 862      /**
 863       * content that should be output in the footer area
 864       * of the page. Designed to be called in theme layout.php files.
 865       *
 866       * @return string HTML fragment.
 867       */
 868      public function standard_footer_html() {
 869          global $CFG;
 870  
 871          $output = '';
 872          if (during_initial_install()) {
 873              // Debugging info can not work before install is finished,
 874              // in any case we do not want any links during installation!
 875              return $output;
 876          }
 877  
 878          // Give plugins an opportunity to add any footer elements.
 879          // The callback must always return a string containing valid html footer content.
 880          $pluginswithfunction = get_plugins_with_function('standard_footer_html', 'lib.php');
 881          foreach ($pluginswithfunction as $plugins) {
 882              foreach ($plugins as $function) {
 883                  $output .= $function();
 884              }
 885          }
 886  
 887          if (core_userfeedback::can_give_feedback()) {
 888              $output .= html_writer::div(
 889                  $this->render_from_template('core/userfeedback_footer_link', ['url' => core_userfeedback::make_link()->out(false)])
 890              );
 891          }
 892  
 893          if ($this->page->devicetypeinuse == 'legacy') {
 894              // The legacy theme is in use print the notification
 895              $output .= html_writer::tag('div', get_string('legacythemeinuse'), array('class'=>'legacythemeinuse'));
 896          }
 897  
 898          // Get links to switch device types (only shown for users not on a default device)
 899          $output .= $this->theme_switch_links();
 900  
 901          return $output;
 902      }
 903  
 904      /**
 905       * Performance information and validation links for debugging.
 906       *
 907       * @return string HTML fragment.
 908       */
 909      public function debug_footer_html() {
 910          global $CFG, $SCRIPT;
 911          $output = '';
 912  
 913          if (during_initial_install()) {
 914              // Debugging info can not work before install is finished.
 915              return $output;
 916          }
 917  
 918          // This function is normally called from a layout.php file
 919          // but some of the content won't be known until later, so we return a placeholder
 920          // for now. This will be replaced with the real content in the footer.
 921          $output .= $this->unique_performance_info_token;
 922  
 923          if (!empty($CFG->debugpageinfo)) {
 924              $output .= '<div class="performanceinfo pageinfo">' . get_string('pageinfodebugsummary', 'core_admin',
 925                  $this->page->debug_summary()) . '</div>';
 926          }
 927          if (debugging(null, DEBUG_DEVELOPER) and has_capability('moodle/site:config', context_system::instance())) {  // Only in developer mode
 928  
 929              // Add link to profiling report if necessary
 930              if (function_exists('profiling_is_running') && profiling_is_running()) {
 931                  $txt = get_string('profiledscript', 'admin');
 932                  $title = get_string('profiledscriptview', 'admin');
 933                  $url = $CFG->wwwroot . '/admin/tool/profiling/index.php?script=' . urlencode($SCRIPT);
 934                  $link= '<a title="' . $title . '" href="' . $url . '">' . $txt . '</a>';
 935                  $output .= '<div class="profilingfooter">' . $link . '</div>';
 936              }
 937              $purgeurl = new moodle_url('/admin/purgecaches.php', array('confirm' => 1,
 938                  'sesskey' => sesskey(), 'returnurl' => $this->page->url->out_as_local_url(false)));
 939              $output .= '<div class="purgecaches">' .
 940                      html_writer::link($purgeurl, get_string('purgecaches', 'admin')) . '</div>';
 941  
 942              // Reactive module debug panel.
 943              $output .= $this->render_from_template('core/local/reactive/debugpanel', []);
 944          }
 945          if (!empty($CFG->debugvalidators)) {
 946              $siteurl = qualified_me();
 947              $nuurl = new moodle_url('https://validator.w3.org/nu/', ['doc' => $siteurl, 'showsource' => 'yes']);
 948              $waveurl = new moodle_url('https://wave.webaim.org/report#/' . urlencode($siteurl));
 949              $validatorlinks = [
 950                  html_writer::link($nuurl, get_string('validatehtml')),
 951                  html_writer::link($waveurl, get_string('wcagcheck'))
 952              ];
 953              $validatorlinkslist = html_writer::alist($validatorlinks, ['class' => 'list-unstyled ml-1']);
 954              $output .= html_writer::div($validatorlinkslist, 'validators');
 955          }
 956          return $output;
 957      }
 958  
 959      /**
 960       * Returns standard main content placeholder.
 961       * Designed to be called in theme layout.php files.
 962       *
 963       * @return string HTML fragment.
 964       */
 965      public function main_content() {
 966          // This is here because it is the only place we can inject the "main" role over the entire main content area
 967          // without requiring all theme's to manually do it, and without creating yet another thing people need to
 968          // remember in the theme.
 969          // This is an unfortunate hack. DO NO EVER add anything more here.
 970          // DO NOT add classes.
 971          // DO NOT add an id.
 972          return '<div role="main">'.$this->unique_main_content_token.'</div>';
 973      }
 974  
 975      /**
 976       * Returns information about an activity.
 977       *
 978       * @param cm_info $cminfo The course module information.
 979       * @param cm_completion_details $completiondetails The completion details for this activity module.
 980       * @param array $activitydates The dates for this activity module.
 981       * @return string the activity information HTML.
 982       * @throws coding_exception
 983       */
 984      public function activity_information(cm_info $cminfo, cm_completion_details $completiondetails, array $activitydates): string {
 985          if (!$completiondetails->has_completion() && empty($activitydates)) {
 986              // No need to render the activity information when there's no completion info and activity dates to show.
 987              return '';
 988          }
 989          $activityinfo = new activity_information($cminfo, $completiondetails, $activitydates);
 990          $renderer = $this->page->get_renderer('core', 'course');
 991          return $renderer->render($activityinfo);
 992      }
 993  
 994      /**
 995       * Returns standard navigation between activities in a course.
 996       *
 997       * @return string the navigation HTML.
 998       */
 999      public function activity_navigation() {
1000          // First we should check if we want to add navigation.
1001          $context = $this->page->context;
1002          if (($this->page->pagelayout !== 'incourse' && $this->page->pagelayout !== 'frametop')
1003              || $context->contextlevel != CONTEXT_MODULE) {
1004              return '';
1005          }
1006  
1007          // If the activity is in stealth mode, show no links.
1008          if ($this->page->cm->is_stealth()) {
1009              return '';
1010          }
1011  
1012          $course = $this->page->cm->get_course();
1013          $courseformat = course_get_format($course);
1014  
1015          // If the theme implements course index and the current course format uses course index and the current
1016          // page layout is not 'frametop' (this layout does not support course index), show no links.
1017          if ($this->page->theme->usescourseindex && $courseformat->uses_course_index() &&
1018                  $this->page->pagelayout !== 'frametop') {
1019              return '';
1020          }
1021  
1022          // Get a list of all the activities in the course.
1023          $modules = get_fast_modinfo($course->id)->get_cms();
1024  
1025          // Put the modules into an array in order by the position they are shown in the course.
1026          $mods = [];
1027          $activitylist = [];
1028          foreach ($modules as $module) {
1029              // Only add activities the user can access, aren't in stealth mode and have a url (eg. mod_label does not).
1030              if (!$module->uservisible || $module->is_stealth() || empty($module->url)) {
1031                  continue;
1032              }
1033              $mods[$module->id] = $module;
1034  
1035              // No need to add the current module to the list for the activity dropdown menu.
1036              if ($module->id == $this->page->cm->id) {
1037                  continue;
1038              }
1039              // Module name.
1040              $modname = $module->get_formatted_name();
1041              // Display the hidden text if necessary.
1042              if (!$module->visible) {
1043                  $modname .= ' ' . get_string('hiddenwithbrackets');
1044              }
1045              // Module URL.
1046              $linkurl = new moodle_url($module->url, array('forceview' => 1));
1047              // Add module URL (as key) and name (as value) to the activity list array.
1048              $activitylist[$linkurl->out(false)] = $modname;
1049          }
1050  
1051          $nummods = count($mods);
1052  
1053          // If there is only one mod then do nothing.
1054          if ($nummods == 1) {
1055              return '';
1056          }
1057  
1058          // Get an array of just the course module ids used to get the cmid value based on their position in the course.
1059          $modids = array_keys($mods);
1060  
1061          // Get the position in the array of the course module we are viewing.
1062          $position = array_search($this->page->cm->id, $modids);
1063  
1064          $prevmod = null;
1065          $nextmod = null;
1066  
1067          // Check if we have a previous mod to show.
1068          if ($position > 0) {
1069              $prevmod = $mods[$modids[$position - 1]];
1070          }
1071  
1072          // Check if we have a next mod to show.
1073          if ($position < ($nummods - 1)) {
1074              $nextmod = $mods[$modids[$position + 1]];
1075          }
1076  
1077          $activitynav = new \core_course\output\activity_navigation($prevmod, $nextmod, $activitylist);
1078          $renderer = $this->page->get_renderer('core', 'course');
1079          return $renderer->render($activitynav);
1080      }
1081  
1082      /**
1083       * The standard tags (typically script tags that are not needed earlier) that
1084       * should be output after everything else. Designed to be called in theme layout.php files.
1085       *
1086       * @return string HTML fragment.
1087       */
1088      public function standard_end_of_body_html() {
1089          global $CFG;
1090  
1091          // This function is normally called from a layout.php file in {@link core_renderer::header()}
1092          // but some of the content won't be known until later, so we return a placeholder
1093          // for now. This will be replaced with the real content in {@link core_renderer::footer()}.
1094          $output = '';
1095          if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlfooter)) {
1096              $output .= "\n".$CFG->additionalhtmlfooter;
1097          }
1098          $output .= $this->unique_end_html_token;
1099          return $output;
1100      }
1101  
1102      /**
1103       * The standard HTML that should be output just before the <footer> tag.
1104       * Designed to be called in theme layout.php files.
1105       *
1106       * @return string HTML fragment.
1107       */
1108      public function standard_after_main_region_html() {
1109          global $CFG;
1110          $output = '';
1111          if ($this->page->pagelayout !== 'embedded' && !empty($CFG->additionalhtmlbottomofbody)) {
1112              $output .= "\n".$CFG->additionalhtmlbottomofbody;
1113          }
1114  
1115          // Give subsystems an opportunity to inject extra html content. The callback
1116          // must always return a string containing valid html.
1117          foreach (\core_component::get_core_subsystems() as $name => $path) {
1118              if ($path) {
1119                  $output .= component_callback($name, 'standard_after_main_region_html', [], '');
1120              }
1121          }
1122  
1123          // Give plugins an opportunity to inject extra html content. The callback
1124          // must always return a string containing valid html.
1125          $pluginswithfunction = get_plugins_with_function('standard_after_main_region_html', 'lib.php');
1126          foreach ($pluginswithfunction as $plugins) {
1127              foreach ($plugins as $function) {
1128                  $output .= $function();
1129              }
1130          }
1131  
1132          return $output;
1133      }
1134  
1135      /**
1136       * Return the standard string that says whether you are logged in (and switched
1137       * roles/logged in as another user).
1138       * @param bool $withlinks if false, then don't include any links in the HTML produced.
1139       * If not set, the default is the nologinlinks option from the theme config.php file,
1140       * and if that is not set, then links are included.
1141       * @return string HTML fragment.
1142       */
1143      public function login_info($withlinks = null) {
1144          global $USER, $CFG, $DB, $SESSION;
1145  
1146          if (during_initial_install()) {
1147              return '';
1148          }
1149  
1150          if (is_null($withlinks)) {
1151              $withlinks = empty($this->page->layout_options['nologinlinks']);
1152          }
1153  
1154          $course = $this->page->course;
1155          if (\core\session\manager::is_loggedinas()) {
1156              $realuser = \core\session\manager::get_realuser();
1157              $fullname = fullname($realuser);
1158              if ($withlinks) {
1159                  $loginastitle = get_string('loginas');
1160                  $realuserinfo = " [<a href=\"$CFG->wwwroot/course/loginas.php?id=$course->id&amp;sesskey=".sesskey()."\"";
1161                  $realuserinfo .= "title =\"".$loginastitle."\">$fullname</a>] ";
1162              } else {
1163                  $realuserinfo = " [$fullname] ";
1164              }
1165          } else {
1166              $realuserinfo = '';
1167          }
1168  
1169          $loginpage = $this->is_login_page();
1170          $loginurl = get_login_url();
1171  
1172          if (empty($course->id)) {
1173              // $course->id is not defined during installation
1174              return '';
1175          } else if (isloggedin()) {
1176              $context = context_course::instance($course->id);
1177  
1178              $fullname = fullname($USER);
1179              // Since Moodle 2.0 this link always goes to the public profile page (not the course profile page)
1180              if ($withlinks) {
1181                  $linktitle = get_string('viewprofile');
1182                  $username = "<a href=\"$CFG->wwwroot/user/profile.php?id=$USER->id\" title=\"$linktitle\">$fullname</a>";
1183              } else {
1184                  $username = $fullname;
1185              }
1186              if (is_mnet_remote_user($USER) and $idprovider = $DB->get_record('mnet_host', array('id'=>$USER->mnethostid))) {
1187                  if ($withlinks) {
1188                      $username .= " from <a href=\"{$idprovider->wwwroot}\">{$idprovider->name}</a>";
1189                  } else {
1190                      $username .= " from {$idprovider->name}";
1191                  }
1192              }
1193              if (isguestuser()) {
1194                  $loggedinas = $realuserinfo.get_string('loggedinasguest');
1195                  if (!$loginpage && $withlinks) {
1196                      $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1197                  }
1198              } else if (is_role_switched($course->id)) { // Has switched roles
1199                  $rolename = '';
1200                  if ($role = $DB->get_record('role', array('id'=>$USER->access['rsw'][$context->path]))) {
1201                      $rolename = ': '.role_get_name($role, $context);
1202                  }
1203                  $loggedinas = get_string('loggedinas', 'moodle', $username).$rolename;
1204                  if ($withlinks) {
1205                      $url = new moodle_url('/course/switchrole.php', array('id'=>$course->id,'sesskey'=>sesskey(), 'switchrole'=>0, 'returnurl'=>$this->page->url->out_as_local_url(false)));
1206                      $loggedinas .= ' ('.html_writer::tag('a', get_string('switchrolereturn'), array('href' => $url)).')';
1207                  }
1208              } else {
1209                  $loggedinas = $realuserinfo.get_string('loggedinas', 'moodle', $username);
1210                  if ($withlinks) {
1211                      $loggedinas .= " (<a href=\"$CFG->wwwroot/login/logout.php?sesskey=".sesskey()."\">".get_string('logout').'</a>)';
1212                  }
1213              }
1214          } else {
1215              $loggedinas = get_string('loggedinnot', 'moodle');
1216              if (!$loginpage && $withlinks) {
1217                  $loggedinas .= " (<a href=\"$loginurl\">".get_string('login').'</a>)';
1218              }
1219          }
1220  
1221          $loggedinas = '<div class="logininfo">'.$loggedinas.'</div>';
1222  
1223          if (isset($SESSION->justloggedin)) {
1224              unset($SESSION->justloggedin);
1225              if (!isguestuser()) {
1226                  // Include this file only when required.
1227                  require_once($CFG->dirroot . '/user/lib.php');
1228                  if (($count = user_count_login_failures($USER)) && !empty($CFG->displayloginfailures)) {
1229                      $loggedinas .= '<div class="loginfailures">';
1230                      $a = new stdClass();
1231                      $a->attempts = $count;
1232                      $loggedinas .= get_string('failedloginattempts', '', $a);
1233                      if (file_exists("$CFG->dirroot/report/log/index.php") and has_capability('report/log:view', context_system::instance())) {
1234                          $loggedinas .= ' ('.html_writer::link(new moodle_url('/report/log/index.php', array('chooselog' => 1,
1235                                  'id' => 0 , 'modid' => 'site_errors')), get_string('logs')).')';
1236                      }
1237                      $loggedinas .= '</div>';
1238                  }
1239              }
1240          }
1241  
1242          return $loggedinas;
1243      }
1244  
1245      /**
1246       * Check whether the current page is a login page.
1247       *
1248       * @since Moodle 2.9
1249       * @return bool
1250       */
1251      protected function is_login_page() {
1252          // This is a real bit of a hack, but its a rarety that we need to do something like this.
1253          // In fact the login pages should be only these two pages and as exposing this as an option for all pages
1254          // could lead to abuse (or at least unneedingly complex code) the hack is the way to go.
1255          return in_array(
1256              $this->page->url->out_as_local_url(false, array()),
1257              array(
1258                  '/login/index.php',
1259                  '/login/forgot_password.php',
1260              )
1261          );
1262      }
1263  
1264      /**
1265       * Return the 'back' link that normally appears in the footer.
1266       *
1267       * @return string HTML fragment.
1268       */
1269      public function home_link() {
1270          global $CFG, $SITE;
1271  
1272          if ($this->page->pagetype == 'site-index') {
1273              // Special case for site home page - please do not remove
1274              return '<div class="sitelink">' .
1275                     '<a title="Moodle" class="d-inline-block aalink" href="http://moodle.org/">' .
1276                     '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1277  
1278          } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
1279              // Special case for during install/upgrade.
1280              return '<div class="sitelink">'.
1281                     '<a title="Moodle" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">' .
1282                     '<img src="' . $this->image_url('moodlelogo_grayhat') . '" alt="'.get_string('moodlelogo').'" /></a></div>';
1283  
1284          } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
1285              return '<div class="homelink"><a href="' . $CFG->wwwroot . '/">' .
1286                      get_string('home') . '</a></div>';
1287  
1288          } else {
1289              return '<div class="homelink"><a href="' . $CFG->wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
1290                      format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '</a></div>';
1291          }
1292      }
1293  
1294      /**
1295       * Redirects the user by any means possible given the current state
1296       *
1297       * This function should not be called directly, it should always be called using
1298       * the redirect function in lib/weblib.php
1299       *
1300       * The redirect function should really only be called before page output has started
1301       * however it will allow itself to be called during the state STATE_IN_BODY
1302       *
1303       * @param string $encodedurl The URL to send to encoded if required
1304       * @param string $message The message to display to the user if any
1305       * @param int $delay The delay before redirecting a user, if $message has been
1306       *         set this is a requirement and defaults to 3, set to 0 no delay
1307       * @param boolean $debugdisableredirect this redirect has been disabled for
1308       *         debugging purposes. Display a message that explains, and don't
1309       *         trigger the redirect.
1310       * @param string $messagetype The type of notification to show the message in.
1311       *         See constants on \core\output\notification.
1312       * @return string The HTML to display to the user before dying, may contain
1313       *         meta refresh, javascript refresh, and may have set header redirects
1314       */
1315      public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
1316                                       $messagetype = \core\output\notification::NOTIFY_INFO) {
1317          global $CFG;
1318          $url = str_replace('&amp;', '&', $encodedurl);
1319  
1320          switch ($this->page->state) {
1321              case moodle_page::STATE_BEFORE_HEADER :
1322                  // No output yet it is safe to delivery the full arsenal of redirect methods
1323                  if (!$debugdisableredirect) {
1324                      // Don't use exactly the same time here, it can cause problems when both redirects fire at the same time.
1325                      $this->metarefreshtag = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />'."\n";
1326                      $this->page->requires->js_function_call('document.location.replace', array($url), false, ($delay + 3));
1327                  }
1328                  $output = $this->header();
1329                  break;
1330              case moodle_page::STATE_PRINTING_HEADER :
1331                  // We should hopefully never get here
1332                  throw new coding_exception('You cannot redirect while printing the page header');
1333                  break;
1334              case moodle_page::STATE_IN_BODY :
1335                  // We really shouldn't be here but we can deal with this
1336                  debugging("You should really redirect before you start page output");
1337                  if (!$debugdisableredirect) {
1338                      $this->page->requires->js_function_call('document.location.replace', array($url), false, $delay);
1339                  }
1340                  $output = $this->opencontainers->pop_all_but_last();
1341                  break;
1342              case moodle_page::STATE_DONE :
1343                  // Too late to be calling redirect now
1344                  throw new coding_exception('You cannot redirect after the entire page has been generated');
1345                  break;
1346          }
1347          $output .= $this->notification($message, $messagetype);
1348          $output .= '<div class="continuebutton">(<a href="'. $encodedurl .'">'. get_string('continue') .'</a>)</div>';
1349          if ($debugdisableredirect) {
1350              $output .= '<p><strong>'.get_string('erroroutput', 'error').'</strong></p>';
1351          }
1352          $output .= $this->footer();
1353          return $output;
1354      }
1355  
1356      /**
1357       * Start output by sending the HTTP headers, and printing the HTML <head>
1358       * and the start of the <body>.
1359       *
1360       * To control what is printed, you should set properties on $PAGE.
1361       *
1362       * @return string HTML that you must output this, preferably immediately.
1363       */
1364      public function header() {
1365          global $USER, $CFG, $SESSION;
1366  
1367          // Give plugins an opportunity touch things before the http headers are sent
1368          // such as adding additional headers. The return value is ignored.
1369          $pluginswithfunction = get_plugins_with_function('before_http_headers', 'lib.php');
1370          foreach ($pluginswithfunction as $plugins) {
1371              foreach ($plugins as $function) {
1372                  $function();
1373              }
1374          }
1375  
1376          if (\core\session\manager::is_loggedinas()) {
1377              $this->page->add_body_class('userloggedinas');
1378          }
1379  
1380          if (isset($SESSION->justloggedin) && !empty($CFG->displayloginfailures)) {
1381              require_once($CFG->dirroot . '/user/lib.php');
1382              // Set second parameter to false as we do not want reset the counter, the same message appears on footer.
1383              if ($count = user_count_login_failures($USER, false)) {
1384                  $this->page->add_body_class('loginfailures');
1385              }
1386          }
1387  
1388          // If the user is logged in, and we're not in initial install,
1389          // check to see if the user is role-switched and add the appropriate
1390          // CSS class to the body element.
1391          if (!during_initial_install() && isloggedin() && is_role_switched($this->page->course->id)) {
1392              $this->page->add_body_class('userswitchedrole');
1393          }
1394  
1395          // Give themes a chance to init/alter the page object.
1396          $this->page->theme->init_page($this->page);
1397  
1398          $this->page->set_state(moodle_page::STATE_PRINTING_HEADER);
1399  
1400          // Find the appropriate page layout file, based on $this->page->pagelayout.
1401          $layoutfile = $this->page->theme->layout_file($this->page->pagelayout);
1402          // Render the layout using the layout file.
1403          $rendered = $this->render_page_layout($layoutfile);
1404  
1405          // Slice the rendered output into header and footer.
1406          $cutpos = strpos($rendered, $this->unique_main_content_token);
1407          if ($cutpos === false) {
1408              $cutpos = strpos($rendered, self::MAIN_CONTENT_TOKEN);
1409              $token = self::MAIN_CONTENT_TOKEN;
1410          } else {
1411              $token = $this->unique_main_content_token;
1412          }
1413  
1414          if ($cutpos === false) {
1415              throw new coding_exception('page layout file ' . $layoutfile . ' does not contain the main content placeholder, please include "<?php echo $OUTPUT->main_content() ?>" in theme layout file.');
1416          }
1417          $header = substr($rendered, 0, $cutpos);
1418          $footer = substr($rendered, $cutpos + strlen($token));
1419  
1420          if (empty($this->contenttype)) {
1421              debugging('The page layout file did not call $OUTPUT->doctype()');
1422              $header = $this->doctype() . $header;
1423          }
1424  
1425          // If this theme version is below 2.4 release and this is a course view page
1426          if ((!isset($this->page->theme->settings->version) || $this->page->theme->settings->version < 2012101500) &&
1427                  $this->page->pagelayout === 'course' && $this->page->url->compare(new moodle_url('/course/view.php'), URL_MATCH_BASE)) {
1428              // check if course content header/footer have not been output during render of theme layout
1429              $coursecontentheader = $this->course_content_header(true);
1430              $coursecontentfooter = $this->course_content_footer(true);
1431              if (!empty($coursecontentheader)) {
1432                  // display debug message and add header and footer right above and below main content
1433                  // Please note that course header and footer (to be displayed above and below the whole page)
1434                  // are not displayed in this case at all.
1435                  // Besides the content header and footer are not displayed on any other course page
1436                  debugging('The current theme is not optimised for 2.4, the course-specific header and footer defined in course format will not be output', DEBUG_DEVELOPER);
1437                  $header .= $coursecontentheader;
1438                  $footer = $coursecontentfooter. $footer;
1439              }
1440          }
1441  
1442          send_headers($this->contenttype, $this->page->cacheable);
1443  
1444          $this->opencontainers->push('header/footer', $footer);
1445          $this->page->set_state(moodle_page::STATE_IN_BODY);
1446  
1447          // If an activity record has been set, activity_header will handle this.
1448          if (!$this->page->cm || !empty($this->page->layout_options['noactivityheader'])) {
1449              $header .= $this->skip_link_target('maincontent');
1450          }
1451          return $header;
1452      }
1453  
1454      /**
1455       * Renders and outputs the page layout file.
1456       *
1457       * This is done by preparing the normal globals available to a script, and
1458       * then including the layout file provided by the current theme for the
1459       * requested layout.
1460       *
1461       * @param string $layoutfile The name of the layout file
1462       * @return string HTML code
1463       */
1464      protected function render_page_layout($layoutfile) {
1465          global $CFG, $SITE, $USER;
1466          // The next lines are a bit tricky. The point is, here we are in a method
1467          // of a renderer class, and this object may, or may not, be the same as
1468          // the global $OUTPUT object. When rendering the page layout file, we want to use
1469          // this object. However, people writing Moodle code expect the current
1470          // renderer to be called $OUTPUT, not $this, so define a variable called
1471          // $OUTPUT pointing at $this. The same comment applies to $PAGE and $COURSE.
1472          $OUTPUT = $this;
1473          $PAGE = $this->page;
1474          $COURSE = $this->page->course;
1475  
1476          ob_start();
1477          include($layoutfile);
1478          $rendered = ob_get_contents();
1479          ob_end_clean();
1480          return $rendered;
1481      }
1482  
1483      /**
1484       * Outputs the page's footer
1485       *
1486       * @return string HTML fragment
1487       */
1488      public function footer() {
1489          global $CFG, $DB;
1490  
1491          $output = '';
1492  
1493          // Give plugins an opportunity to touch the page before JS is finalized.
1494          $pluginswithfunction = get_plugins_with_function('before_footer', 'lib.php');
1495          foreach ($pluginswithfunction as $plugins) {
1496              foreach ($plugins as $function) {
1497                  $extrafooter = $function();
1498                  if (is_string($extrafooter)) {
1499                      $output .= $extrafooter;
1500                  }
1501              }
1502          }
1503  
1504          $output .= $this->container_end_all(true);
1505  
1506          $footer = $this->opencontainers->pop('header/footer');
1507  
1508          if (debugging() and $DB and $DB->is_transaction_started()) {
1509              // TODO: MDL-20625 print warning - transaction will be rolled back
1510          }
1511  
1512          // Provide some performance info if required
1513          $performanceinfo = '';
1514          if ((defined('MDL_PERF') && MDL_PERF) || (!empty($CFG->perfdebug) && $CFG->perfdebug > 7)) {
1515              $perf = get_performance_info();
1516              if ((defined('MDL_PERFTOFOOT') && MDL_PERFTOFOOT) || debugging() || $CFG->perfdebug > 7) {
1517                  $performanceinfo = $perf['html'];
1518              }
1519          }
1520  
1521          // We always want performance data when running a performance test, even if the user is redirected to another page.
1522          if (MDL_PERF_TEST && strpos($footer, $this->unique_performance_info_token) === false) {
1523              $footer = $this->unique_performance_info_token . $footer;
1524          }
1525          $footer = str_replace($this->unique_performance_info_token, $performanceinfo, $footer);
1526  
1527          // Only show notifications when the current page has a context id.
1528          if (!empty($this->page->context->id)) {
1529              $this->page->requires->js_call_amd('core/notification', 'init', array(
1530                  $this->page->context->id,
1531                  \core\notification::fetch_as_array($this)
1532              ));
1533          }
1534          $footer = str_replace($this->unique_end_html_token, $this->page->requires->get_end_code(), $footer);
1535  
1536          $this->page->set_state(moodle_page::STATE_DONE);
1537  
1538          return $output . $footer;
1539      }
1540  
1541      /**
1542       * Close all but the last open container. This is useful in places like error
1543       * handling, where you want to close all the open containers (apart from <body>)
1544       * before outputting the error message.
1545       *
1546       * @param bool $shouldbenone assert that the stack should be empty now - causes a
1547       *      developer debug warning if it isn't.
1548       * @return string the HTML required to close any open containers inside <body>.
1549       */
1550      public function container_end_all($shouldbenone = false) {
1551          return $this->opencontainers->pop_all_but_last($shouldbenone);
1552      }
1553  
1554      /**
1555       * Returns course-specific information to be output immediately above content on any course page
1556       * (for the current course)
1557       *
1558       * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1559       * @return string
1560       */
1561      public function course_content_header($onlyifnotcalledbefore = false) {
1562          global $CFG;
1563          static $functioncalled = false;
1564          if ($functioncalled && $onlyifnotcalledbefore) {
1565              // we have already output the content header
1566              return '';
1567          }
1568  
1569          // Output any session notification.
1570          $notifications = \core\notification::fetch();
1571  
1572          $bodynotifications = '';
1573          foreach ($notifications as $notification) {
1574              $bodynotifications .= $this->render_from_template(
1575                      $notification->get_template_name(),
1576                      $notification->export_for_template($this)
1577                  );
1578          }
1579  
1580          $output = html_writer::span($bodynotifications, 'notifications', array('id' => 'user-notifications'));
1581  
1582          if ($this->page->course->id == SITEID) {
1583              // return immediately and do not include /course/lib.php if not necessary
1584              return $output;
1585          }
1586  
1587          require_once($CFG->dirroot.'/course/lib.php');
1588          $functioncalled = true;
1589          $courseformat = course_get_format($this->page->course);
1590          if (($obj = $courseformat->course_content_header()) !== null) {
1591              $output .= html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-header');
1592          }
1593          return $output;
1594      }
1595  
1596      /**
1597       * Returns course-specific information to be output immediately below content on any course page
1598       * (for the current course)
1599       *
1600       * @param bool $onlyifnotcalledbefore output content only if it has not been output before
1601       * @return string
1602       */
1603      public function course_content_footer($onlyifnotcalledbefore = false) {
1604          global $CFG;
1605          if ($this->page->course->id == SITEID) {
1606              // return immediately and do not include /course/lib.php if not necessary
1607              return '';
1608          }
1609          static $functioncalled = false;
1610          if ($functioncalled && $onlyifnotcalledbefore) {
1611              // we have already output the content footer
1612              return '';
1613          }
1614          $functioncalled = true;
1615          require_once($CFG->dirroot.'/course/lib.php');
1616          $courseformat = course_get_format($this->page->course);
1617          if (($obj = $courseformat->course_content_footer()) !== null) {
1618              return html_writer::div($courseformat->get_renderer($this->page)->render($obj), 'course-content-footer');
1619          }
1620          return '';
1621      }
1622  
1623      /**
1624       * Returns course-specific information to be output on any course page in the header area
1625       * (for the current course)
1626       *
1627       * @return string
1628       */
1629      public function course_header() {
1630          global $CFG;
1631          if ($this->page->course->id == SITEID) {
1632              // return immediately and do not include /course/lib.php if not necessary
1633              return '';
1634          }
1635          require_once($CFG->dirroot.'/course/lib.php');
1636          $courseformat = course_get_format($this->page->course);
1637          if (($obj = $courseformat->course_header()) !== null) {
1638              return $courseformat->get_renderer($this->page)->render($obj);
1639          }
1640          return '';
1641      }
1642  
1643      /**
1644       * Returns course-specific information to be output on any course page in the footer area
1645       * (for the current course)
1646       *
1647       * @return string
1648       */
1649      public function course_footer() {
1650          global $CFG;
1651          if ($this->page->course->id == SITEID) {
1652              // return immediately and do not include /course/lib.php if not necessary
1653              return '';
1654          }
1655          require_once($CFG->dirroot.'/course/lib.php');
1656          $courseformat = course_get_format($this->page->course);
1657          if (($obj = $courseformat->course_footer()) !== null) {
1658              return $courseformat->get_renderer($this->page)->render($obj);
1659          }
1660          return '';
1661      }
1662  
1663      /**
1664       * Get the course pattern datauri to show on a course card.
1665       *
1666       * The datauri is an encoded svg that can be passed as a url.
1667       * @param int $id Id to use when generating the pattern
1668       * @return string datauri
1669       */
1670      public function get_generated_image_for_id($id) {
1671          $color = $this->get_generated_color_for_id($id);
1672          $pattern = new \core_geopattern();
1673          $pattern->setColor($color);
1674          $pattern->patternbyid($id);
1675          return $pattern->datauri();
1676      }
1677  
1678      /**
1679       * Get the course color to show on a course card.
1680       *
1681       * @param int $id Id to use when generating the color.
1682       * @return string hex color code.
1683       */
1684      public function get_generated_color_for_id($id) {
1685          $colornumbers = range(1, 10);
1686          $basecolors = [];
1687          foreach ($colornumbers as $number) {
1688              $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1689          }
1690  
1691          $color = $basecolors[$id % 10];
1692          return $color;
1693      }
1694  
1695      /**
1696       * Returns lang menu or '', this method also checks forcing of languages in courses.
1697       *
1698       * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1699       *
1700       * @return string The lang menu HTML or empty string
1701       */
1702      public function lang_menu() {
1703          $languagemenu = new \core\output\language_menu($this->page);
1704          $data = $languagemenu->export_for_single_select($this);
1705          if ($data) {
1706              return $this->render_from_template('core/single_select', $data);
1707          }
1708          return '';
1709      }
1710  
1711      /**
1712       * Output the row of editing icons for a block, as defined by the controls array.
1713       *
1714       * @param array $controls an array like {@link block_contents::$controls}.
1715       * @param string $blockid The ID given to the block.
1716       * @return string HTML fragment.
1717       */
1718      public function block_controls($actions, $blockid = null) {
1719          global $CFG;
1720          if (empty($actions)) {
1721              return '';
1722          }
1723          $menu = new action_menu($actions);
1724          if ($blockid !== null) {
1725              $menu->set_owner_selector('#'.$blockid);
1726          }
1727          $menu->set_constraint('.block-region');
1728          $menu->attributes['class'] .= ' block-control-actions commands';
1729          return $this->render($menu);
1730      }
1731  
1732      /**
1733       * Returns the HTML for a basic textarea field.
1734       *
1735       * @param string $name Name to use for the textarea element
1736       * @param string $id The id to use fort he textarea element
1737       * @param string $value Initial content to display in the textarea
1738       * @param int $rows Number of rows to display
1739       * @param int $cols Number of columns to display
1740       * @return string the HTML to display
1741       */
1742      public function print_textarea($name, $id, $value, $rows, $cols) {
1743          editors_head_setup();
1744          $editor = editors_get_preferred_editor(FORMAT_HTML);
1745          $editor->set_text($value);
1746          $editor->use_editor($id, []);
1747  
1748          $context = [
1749              'id' => $id,
1750              'name' => $name,
1751              'value' => $value,
1752              'rows' => $rows,
1753              'cols' => $cols
1754          ];
1755  
1756          return $this->render_from_template('core_form/editor_textarea', $context);
1757      }
1758  
1759      /**
1760       * Renders an action menu component.
1761       *
1762       * @param action_menu $menu
1763       * @return string HTML
1764       */
1765      public function render_action_menu(action_menu $menu) {
1766  
1767          // We don't want the class icon there!
1768          foreach ($menu->get_secondary_actions() as $action) {
1769              if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1770                  $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1771              }
1772          }
1773  
1774          if ($menu->is_empty()) {
1775              return '';
1776          }
1777          $context = $menu->export_for_template($this);
1778  
1779          return $this->render_from_template('core/action_menu', $context);
1780      }
1781  
1782      /**
1783       * Renders a Check API result
1784       *
1785       * @param result $result
1786       * @return string HTML fragment
1787       */
1788      protected function render_check_result(core\check\result $result) {
1789          return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1790      }
1791  
1792      /**
1793       * Renders a Check API result
1794       *
1795       * @param result $result
1796       * @return string HTML fragment
1797       */
1798      public function check_result(core\check\result $result) {
1799          return $this->render_check_result($result);
1800      }
1801  
1802      /**
1803       * Renders an action_menu_link item.
1804       *
1805       * @param action_menu_link $action
1806       * @return string HTML fragment
1807       */
1808      protected function render_action_menu_link(action_menu_link $action) {
1809          return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1810      }
1811  
1812      /**
1813       * Renders a primary action_menu_filler item.
1814       *
1815       * @param action_menu_link_filler $action
1816       * @return string HTML fragment
1817       */
1818      protected function render_action_menu_filler(action_menu_filler $action) {
1819          return html_writer::span('&nbsp;', 'filler');
1820      }
1821  
1822      /**
1823       * Renders a primary action_menu_link item.
1824       *
1825       * @param action_menu_link_primary $action
1826       * @return string HTML fragment
1827       */
1828      protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1829          return $this->render_action_menu_link($action);
1830      }
1831  
1832      /**
1833       * Renders a secondary action_menu_link item.
1834       *
1835       * @param action_menu_link_secondary $action
1836       * @return string HTML fragment
1837       */
1838      protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1839          return $this->render_action_menu_link($action);
1840      }
1841  
1842      /**
1843       * Prints a nice side block with an optional header.
1844       *
1845       * @param block_contents $bc HTML for the content
1846       * @param string $region the region the block is appearing in.
1847       * @return string the HTML to be output.
1848       */
1849      public function block(block_contents $bc, $region) {
1850          $bc = clone($bc); // Avoid messing up the object passed in.
1851          if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1852              $bc->collapsible = block_contents::NOT_HIDEABLE;
1853          }
1854  
1855          $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1856          $context = new stdClass();
1857          $context->skipid = $bc->skipid;
1858          $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1859          $context->dockable = $bc->dockable;
1860          $context->id = $id;
1861          $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1862          $context->skiptitle = strip_tags($bc->title);
1863          $context->showskiplink = !empty($context->skiptitle);
1864          $context->arialabel = $bc->arialabel;
1865          $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1866          $context->class = $bc->attributes['class'];
1867          $context->type = $bc->attributes['data-block'];
1868          $context->title = $bc->title;
1869          $context->content = $bc->content;
1870          $context->annotation = $bc->annotation;
1871          $context->footer = $bc->footer;
1872          $context->hascontrols = !empty($bc->controls);
1873          if ($context->hascontrols) {
1874              $context->controls = $this->block_controls($bc->controls, $id);
1875          }
1876  
1877          return $this->render_from_template('core/block', $context);
1878      }
1879  
1880      /**
1881       * Render the contents of a block_list.
1882       *
1883       * @param array $icons the icon for each item.
1884       * @param array $items the content of each item.
1885       * @return string HTML
1886       */
1887      public function list_block_contents($icons, $items) {
1888          $row = 0;
1889          $lis = array();
1890          foreach ($items as $key => $string) {
1891              $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1892              if (!empty($icons[$key])) { //test if the content has an assigned icon
1893                  $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1894              }
1895              $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1896              $item .= html_writer::end_tag('li');
1897              $lis[] = $item;
1898              $row = 1 - $row; // Flip even/odd.
1899          }
1900          return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1901      }
1902  
1903      /**
1904       * Output all the blocks in a particular region.
1905       *
1906       * @param string $region the name of a region on this page.
1907       * @param boolean $fakeblocksonly Output fake block only.
1908       * @return string the HTML to be output.
1909       */
1910      public function blocks_for_region($region, $fakeblocksonly = false) {
1911          $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1912          $lastblock = null;
1913          $zones = array();
1914          foreach ($blockcontents as $bc) {
1915              if ($bc instanceof block_contents) {
1916                  $zones[] = $bc->title;
1917              }
1918          }
1919          $output = '';
1920  
1921          foreach ($blockcontents as $bc) {
1922              if ($bc instanceof block_contents) {
1923                  if ($fakeblocksonly && !$bc->is_fake()) {
1924                      // Skip rendering real blocks if we only want to show fake blocks.
1925                      continue;
1926                  }
1927                  $output .= $this->block($bc, $region);
1928                  $lastblock = $bc->title;
1929              } else if ($bc instanceof block_move_target) {
1930                  if (!$fakeblocksonly) {
1931                      $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1932                  }
1933              } else {
1934                  throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1935              }
1936          }
1937          return $output;
1938      }
1939  
1940      /**
1941       * Output a place where the block that is currently being moved can be dropped.
1942       *
1943       * @param block_move_target $target with the necessary details.
1944       * @param array $zones array of areas where the block can be moved to
1945       * @param string $previous the block located before the area currently being rendered.
1946       * @param string $region the name of the region
1947       * @return string the HTML to be output.
1948       */
1949      public function block_move_target($target, $zones, $previous, $region) {
1950          if ($previous == null) {
1951              if (empty($zones)) {
1952                  // There are no zones, probably because there are no blocks.
1953                  $regions = $this->page->theme->get_all_block_regions();
1954                  $position = get_string('moveblockinregion', 'block', $regions[$region]);
1955              } else {
1956                  $position = get_string('moveblockbefore', 'block', $zones[0]);
1957              }
1958          } else {
1959              $position = get_string('moveblockafter', 'block', $previous);
1960          }
1961          return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1962      }
1963  
1964      /**
1965       * Renders a special html link with attached action
1966       *
1967       * Theme developers: DO NOT OVERRIDE! Please override function
1968       * {@link core_renderer::render_action_link()} instead.
1969       *
1970       * @param string|moodle_url $url
1971       * @param string $text HTML fragment
1972       * @param component_action $action
1973       * @param array $attributes associative array of html link attributes + disabled
1974       * @param pix_icon optional pix icon to render with the link
1975       * @return string HTML fragment
1976       */
1977      public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
1978          if (!($url instanceof moodle_url)) {
1979              $url = new moodle_url($url);
1980          }
1981          $link = new action_link($url, $text, $action, $attributes, $icon);
1982  
1983          return $this->render($link);
1984      }
1985  
1986      /**
1987       * Renders an action_link object.
1988       *
1989       * The provided link is renderer and the HTML returned. At the same time the
1990       * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
1991       *
1992       * @param action_link $link
1993       * @return string HTML fragment
1994       */
1995      protected function render_action_link(action_link $link) {
1996          return $this->render_from_template('core/action_link', $link->export_for_template($this));
1997      }
1998  
1999      /**
2000       * Renders an action_icon.
2001       *
2002       * This function uses the {@link core_renderer::action_link()} method for the
2003       * most part. What it does different is prepare the icon as HTML and use it
2004       * as the link text.
2005       *
2006       * Theme developers: If you want to change how action links and/or icons are rendered,
2007       * consider overriding function {@link core_renderer::render_action_link()} and
2008       * {@link core_renderer::render_pix_icon()}.
2009       *
2010       * @param string|moodle_url $url A string URL or moodel_url
2011       * @param pix_icon $pixicon
2012       * @param component_action $action
2013       * @param array $attributes associative array of html link attributes + disabled
2014       * @param bool $linktext show title next to image in link
2015       * @return string HTML fragment
2016       */
2017      public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
2018          if (!($url instanceof moodle_url)) {
2019              $url = new moodle_url($url);
2020          }
2021          $attributes = (array)$attributes;
2022  
2023          if (empty($attributes['class'])) {
2024              // let ppl override the class via $options
2025              $attributes['class'] = 'action-icon';
2026          }
2027  
2028          $icon = $this->render($pixicon);
2029  
2030          if ($linktext) {
2031              $text = $pixicon->attributes['alt'];
2032          } else {
2033              $text = '';
2034          }
2035  
2036          return $this->action_link($url, $text.$icon, $action, $attributes);
2037      }
2038  
2039     /**
2040      * Print a message along with button choices for Continue/Cancel
2041      *
2042      * If a string or moodle_url is given instead of a single_button, method defaults to post.
2043      *
2044      * @param string $message The question to ask the user
2045      * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
2046      * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
2047      * @param array $displayoptions optional extra display options
2048      * @return string HTML fragment
2049      */
2050      public function confirm($message, $continue, $cancel, array $displayoptions = []) {
2051  
2052          // Check existing displayoptions.
2053          $displayoptions['confirmtitle'] = $displayoptions['confirmtitle'] ?? get_string('confirm');
2054          $displayoptions['continuestr'] = $displayoptions['continuestr'] ?? get_string('continue');
2055          $displayoptions['cancelstr'] = $displayoptions['cancelstr'] ?? get_string('cancel');
2056  
2057          if ($continue instanceof single_button) {
2058              // ok
2059              $continue->primary = true;
2060          } else if (is_string($continue)) {
2061              $continue = new single_button(new moodle_url($continue), $displayoptions['continuestr'], 'post', true);
2062          } else if ($continue instanceof moodle_url) {
2063              $continue = new single_button($continue, $displayoptions['continuestr'], 'post', true);
2064          } else {
2065              throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2066          }
2067  
2068          if ($cancel instanceof single_button) {
2069              // ok
2070          } else if (is_string($cancel)) {
2071              $cancel = new single_button(new moodle_url($cancel), $displayoptions['cancelstr'], 'get');
2072          } else if ($cancel instanceof moodle_url) {
2073              $cancel = new single_button($cancel, $displayoptions['cancelstr'], 'get');
2074          } else {
2075              throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2076          }
2077  
2078          $attributes = [
2079              'role'=>'alertdialog',
2080              'aria-labelledby'=>'modal-header',
2081              'aria-describedby'=>'modal-body',
2082              'aria-modal'=>'true'
2083          ];
2084  
2085          $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
2086          $output .= $this->box_start('modal-content', 'modal-content');
2087          $output .= $this->box_start('modal-header px-3', 'modal-header');
2088          $output .= html_writer::tag('h4', $displayoptions['confirmtitle']);
2089          $output .= $this->box_end();
2090          $attributes = [
2091              'role'=>'alert',
2092              'data-aria-autofocus'=>'true'
2093          ];
2094          $output .= $this->box_start('modal-body', 'modal-body', $attributes);
2095          $output .= html_writer::tag('p', $message);
2096          $output .= $this->box_end();
2097          $output .= $this->box_start('modal-footer', 'modal-footer');
2098          $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
2099          $output .= $this->box_end();
2100          $output .= $this->box_end();
2101          $output .= $this->box_end();
2102          return $output;
2103      }
2104  
2105      /**
2106       * Returns a form with a single button.
2107       *
2108       * Theme developers: DO NOT OVERRIDE! Please override function
2109       * {@link core_renderer::render_single_button()} instead.
2110       *
2111       * @param string|moodle_url $url
2112       * @param string $label button text
2113       * @param string $method get or post submit method
2114       * @param array $options associative array {disabled, title, etc.}
2115       * @return string HTML fragment
2116       */
2117      public function single_button($url, $label, $method='post', array $options=null) {
2118          if (!($url instanceof moodle_url)) {
2119              $url = new moodle_url($url);
2120          }
2121          $button = new single_button($url, $label, $method);
2122  
2123          foreach ((array)$options as $key=>$value) {
2124              if (property_exists($button, $key)) {
2125                  $button->$key = $value;
2126              } else {
2127                  $button->set_attribute($key, $value);
2128              }
2129          }
2130  
2131          return $this->render($button);
2132      }
2133  
2134      /**
2135       * Renders a single button widget.
2136       *
2137       * This will return HTML to display a form containing a single button.
2138       *
2139       * @param single_button $button
2140       * @return string HTML fragment
2141       */
2142      protected function render_single_button(single_button $button) {
2143          return $this->render_from_template('core/single_button', $button->export_for_template($this));
2144      }
2145  
2146      /**
2147       * Returns a form with a single select widget.
2148       *
2149       * Theme developers: DO NOT OVERRIDE! Please override function
2150       * {@link core_renderer::render_single_select()} instead.
2151       *
2152       * @param moodle_url $url form action target, includes hidden fields
2153       * @param string $name name of selection field - the changing parameter in url
2154       * @param array $options list of options
2155       * @param string $selected selected element
2156       * @param array $nothing
2157       * @param string $formid
2158       * @param array $attributes other attributes for the single select
2159       * @return string HTML fragment
2160       */
2161      public function single_select($url, $name, array $options, $selected = '',
2162                                  $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2163          if (!($url instanceof moodle_url)) {
2164              $url = new moodle_url($url);
2165          }
2166          $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2167  
2168          if (array_key_exists('label', $attributes)) {
2169              $select->set_label($attributes['label']);
2170              unset($attributes['label']);
2171          }
2172          $select->attributes = $attributes;
2173  
2174          return $this->render($select);
2175      }
2176  
2177      /**
2178       * Returns a dataformat selection and download form
2179       *
2180       * @param string $label A text label
2181       * @param moodle_url|string $base The download page url
2182       * @param string $name The query param which will hold the type of the download
2183       * @param array $params Extra params sent to the download page
2184       * @return string HTML fragment
2185       */
2186      public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2187  
2188          $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2189          $options = array();
2190          foreach ($formats as $format) {
2191              if ($format->is_enabled()) {
2192                  $options[] = array(
2193                      'value' => $format->name,
2194                      'label' => get_string('dataformat', $format->component),
2195                  );
2196              }
2197          }
2198          $hiddenparams = array();
2199          foreach ($params as $key => $value) {
2200              $hiddenparams[] = array(
2201                  'name' => $key,
2202                  'value' => $value,
2203              );
2204          }
2205          $data = array(
2206              'label' => $label,
2207              'base' => $base,
2208              'name' => $name,
2209              'params' => $hiddenparams,
2210              'options' => $options,
2211              'sesskey' => sesskey(),
2212              'submit' => get_string('download'),
2213          );
2214  
2215          return $this->render_from_template('core/dataformat_selector', $data);
2216      }
2217  
2218  
2219      /**
2220       * Internal implementation of single_select rendering
2221       *
2222       * @param single_select $select
2223       * @return string HTML fragment
2224       */
2225      protected function render_single_select(single_select $select) {
2226          return $this->render_from_template('core/single_select', $select->export_for_template($this));
2227      }
2228  
2229      /**
2230       * Returns a form with a url select widget.
2231       *
2232       * Theme developers: DO NOT OVERRIDE! Please override function
2233       * {@link core_renderer::render_url_select()} instead.
2234       *
2235       * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2236       * @param string $selected selected element
2237       * @param array $nothing
2238       * @param string $formid
2239       * @return string HTML fragment
2240       */
2241      public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2242          $select = new url_select($urls, $selected, $nothing, $formid);
2243          return $this->render($select);
2244      }
2245  
2246      /**
2247       * Internal implementation of url_select rendering
2248       *
2249       * @param url_select $select
2250       * @return string HTML fragment
2251       */
2252      protected function render_url_select(url_select $select) {
2253          return $this->render_from_template('core/url_select', $select->export_for_template($this));
2254      }
2255  
2256      /**
2257       * Returns a string containing a link to the user documentation.
2258       * Also contains an icon by default. Shown to teachers and admin only.
2259       *
2260       * @param string $path The page link after doc root and language, no leading slash.
2261       * @param string $text The text to be displayed for the link
2262       * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2263       * @param array $attributes htm attributes
2264       * @return string
2265       */
2266      public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2267          global $CFG;
2268  
2269          $icon = $this->pix_icon('book', '', 'moodle', array('class' => 'iconhelp icon-pre', 'role' => 'presentation'));
2270  
2271          $attributes['href'] = new moodle_url(get_docs_url($path));
2272          $newwindowicon = '';
2273          if (!empty($CFG->doctonewwindow) || $forcepopup) {
2274              $attributes['target'] = '_blank';
2275              $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle',
2276              ['class' => 'fa fa-externallink fa-fw']);
2277          }
2278  
2279          return html_writer::tag('a', $icon . $text . $newwindowicon, $attributes);
2280      }
2281  
2282      /**
2283       * Return HTML for an image_icon.
2284       *
2285       * Theme developers: DO NOT OVERRIDE! Please override function
2286       * {@link core_renderer::render_image_icon()} instead.
2287       *
2288       * @param string $pix short pix name
2289       * @param string $alt mandatory alt attribute
2290       * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2291       * @param array $attributes htm attributes
2292       * @return string HTML fragment
2293       */
2294      public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2295          $icon = new image_icon($pix, $alt, $component, $attributes);
2296          return $this->render($icon);
2297      }
2298  
2299      /**
2300       * Renders a pix_icon widget and returns the HTML to display it.
2301       *
2302       * @param image_icon $icon
2303       * @return string HTML fragment
2304       */
2305      protected function render_image_icon(image_icon $icon) {
2306          $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2307          return $system->render_pix_icon($this, $icon);
2308      }
2309  
2310      /**
2311       * Return HTML for a pix_icon.
2312       *
2313       * Theme developers: DO NOT OVERRIDE! Please override function
2314       * {@link core_renderer::render_pix_icon()} instead.
2315       *
2316       * @param string $pix short pix name
2317       * @param string $alt mandatory alt attribute
2318       * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2319       * @param array $attributes htm lattributes
2320       * @return string HTML fragment
2321       */
2322      public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2323          $icon = new pix_icon($pix, $alt, $component, $attributes);
2324          return $this->render($icon);
2325      }
2326  
2327      /**
2328       * Renders a pix_icon widget and returns the HTML to display it.
2329       *
2330       * @param pix_icon $icon
2331       * @return string HTML fragment
2332       */
2333      protected function render_pix_icon(pix_icon $icon) {
2334          $system = \core\output\icon_system::instance();
2335          return $system->render_pix_icon($this, $icon);
2336      }
2337  
2338      /**
2339       * Return HTML to display an emoticon icon.
2340       *
2341       * @param pix_emoticon $emoticon
2342       * @return string HTML fragment
2343       */
2344      protected function render_pix_emoticon(pix_emoticon $emoticon) {
2345          $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2346          return $system->render_pix_icon($this, $emoticon);
2347      }
2348  
2349      /**
2350       * Produces the html that represents this rating in the UI
2351       *
2352       * @param rating $rating the page object on which this rating will appear
2353       * @return string
2354       */
2355      function render_rating(rating $rating) {
2356          global $CFG, $USER;
2357  
2358          if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2359              return null;//ratings are turned off
2360          }
2361  
2362          $ratingmanager = new rating_manager();
2363          // Initialise the JavaScript so ratings can be done by AJAX.
2364          $ratingmanager->initialise_rating_javascript($this->page);
2365  
2366          $strrate = get_string("rate", "rating");
2367          $ratinghtml = ''; //the string we'll return
2368  
2369          // permissions check - can they view the aggregate?
2370          if ($rating->user_can_view_aggregate()) {
2371  
2372              $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2373              $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2374              $aggregatestr   = $rating->get_aggregate_string();
2375  
2376              $aggregatehtml  = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2377              if ($rating->count > 0) {
2378                  $countstr = "({$rating->count})";
2379              } else {
2380                  $countstr = '-';
2381              }
2382              $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2383  
2384              if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2385  
2386                  $nonpopuplink = $rating->get_view_ratings_url();
2387                  $popuplink = $rating->get_view_ratings_url(true);
2388  
2389                  $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2390                  $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2391              }
2392  
2393              $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2394          }
2395  
2396          $formstart = null;
2397          // if the item doesn't belong to the current user, the user has permission to rate
2398          // and we're within the assessable period
2399          if ($rating->user_can_rate()) {
2400  
2401              $rateurl = $rating->get_rate_url();
2402              $inputs = $rateurl->params();
2403  
2404              //start the rating form
2405              $formattrs = array(
2406                  'id'     => "postrating{$rating->itemid}",
2407                  'class'  => 'postratingform',
2408                  'method' => 'post',
2409                  'action' => $rateurl->out_omit_querystring()
2410              );
2411              $formstart  = html_writer::start_tag('form', $formattrs);
2412              $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2413  
2414              // add the hidden inputs
2415              foreach ($inputs as $name => $value) {
2416                  $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2417                  $formstart .= html_writer::empty_tag('input', $attributes);
2418              }
2419  
2420              if (empty($ratinghtml)) {
2421                  $ratinghtml .= $strrate.': ';
2422              }
2423              $ratinghtml = $formstart.$ratinghtml;
2424  
2425              $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2426              $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2427              $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2428              $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2429  
2430              //output submit button
2431              $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2432  
2433              $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2434              $ratinghtml .= html_writer::empty_tag('input', $attributes);
2435  
2436              if (!$rating->settings->scale->isnumeric) {
2437                  // If a global scale, try to find current course ID from the context
2438                  if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2439                      $courseid = $coursecontext->instanceid;
2440                  } else {
2441                      $courseid = $rating->settings->scale->courseid;
2442                  }
2443                  $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2444              }
2445              $ratinghtml .= html_writer::end_tag('span');
2446              $ratinghtml .= html_writer::end_tag('div');
2447              $ratinghtml .= html_writer::end_tag('form');
2448          }
2449  
2450          return $ratinghtml;
2451      }
2452  
2453      /**
2454       * Centered heading with attached help button (same title text)
2455       * and optional icon attached.
2456       *
2457       * @param string $text A heading text
2458       * @param string $helpidentifier The keyword that defines a help page
2459       * @param string $component component name
2460       * @param string|moodle_url $icon
2461       * @param string $iconalt icon alt text
2462       * @param int $level The level of importance of the heading. Defaulting to 2
2463       * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2464       * @return string HTML fragment
2465       */
2466      public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2467          $image = '';
2468          if ($icon) {
2469              $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2470          }
2471  
2472          $help = '';
2473          if ($helpidentifier) {
2474              $help = $this->help_icon($helpidentifier, $component);
2475          }
2476  
2477          return $this->heading($image.$text.$help, $level, $classnames);
2478      }
2479  
2480      /**
2481       * Returns HTML to display a help icon.
2482       *
2483       * @deprecated since Moodle 2.0
2484       */
2485      public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2486          throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2487      }
2488  
2489      /**
2490       * Returns HTML to display a help icon.
2491       *
2492       * Theme developers: DO NOT OVERRIDE! Please override function
2493       * {@link core_renderer::render_help_icon()} instead.
2494       *
2495       * @param string $identifier The keyword that defines a help page
2496       * @param string $component component name
2497       * @param string|bool $linktext true means use $title as link text, string means link text value
2498       * @return string HTML fragment
2499       */
2500      public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2501          $icon = new help_icon($identifier, $component);
2502          $icon->diag_strings();
2503          if ($linktext === true) {
2504              $icon->linktext = get_string($icon->identifier, $icon->component);
2505          } else if (!empty($linktext)) {
2506              $icon->linktext = $linktext;
2507          }
2508          return $this->render($icon);
2509      }
2510  
2511      /**
2512       * Implementation of user image rendering.
2513       *
2514       * @param help_icon $helpicon A help icon instance
2515       * @return string HTML fragment
2516       */
2517      protected function render_help_icon(help_icon $helpicon) {
2518          $context = $helpicon->export_for_template($this);
2519          return $this->render_from_template('core/help_icon', $context);
2520      }
2521  
2522      /**
2523       * Returns HTML to display a scale help icon.
2524       *
2525       * @param int $courseid
2526       * @param stdClass $scale instance
2527       * @return string HTML fragment
2528       */
2529      public function help_icon_scale($courseid, stdClass $scale) {
2530          global $CFG;
2531  
2532          $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2533  
2534          $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2535  
2536          $scaleid = abs($scale->id);
2537  
2538          $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2539          $action = new popup_action('click', $link, 'ratingscale');
2540  
2541          return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2542      }
2543  
2544      /**
2545       * Creates and returns a spacer image with optional line break.
2546       *
2547       * @param array $attributes Any HTML attributes to add to the spaced.
2548       * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2549       *     laxy do it with CSS which is a much better solution.
2550       * @return string HTML fragment
2551       */
2552      public function spacer(array $attributes = null, $br = false) {
2553          $attributes = (array)$attributes;
2554          if (empty($attributes['width'])) {
2555              $attributes['width'] = 1;
2556          }
2557          if (empty($attributes['height'])) {
2558              $attributes['height'] = 1;
2559          }
2560          $attributes['class'] = 'spacer';
2561  
2562          $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2563  
2564          if (!empty($br)) {
2565              $output .= '<br />';
2566          }
2567  
2568          return $output;
2569      }
2570  
2571      /**
2572       * Returns HTML to display the specified user's avatar.
2573       *
2574       * User avatar may be obtained in two ways:
2575       * <pre>
2576       * // Option 1: (shortcut for simple cases, preferred way)
2577       * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2578       * $OUTPUT->user_picture($user, array('popup'=>true));
2579       *
2580       * // Option 2:
2581       * $userpic = new user_picture($user);
2582       * // Set properties of $userpic
2583       * $userpic->popup = true;
2584       * $OUTPUT->render($userpic);
2585       * </pre>
2586       *
2587       * Theme developers: DO NOT OVERRIDE! Please override function
2588       * {@link core_renderer::render_user_picture()} instead.
2589       *
2590       * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2591       *     If any of these are missing, the database is queried. Avoid this
2592       *     if at all possible, particularly for reports. It is very bad for performance.
2593       * @param array $options associative array with user picture options, used only if not a user_picture object,
2594       *     options are:
2595       *     - courseid=$this->page->course->id (course id of user profile in link)
2596       *     - size=35 (size of image)
2597       *     - link=true (make image clickable - the link leads to user profile)
2598       *     - popup=false (open in popup)
2599       *     - alttext=true (add image alt attribute)
2600       *     - class = image class attribute (default 'userpicture')
2601       *     - visibletoscreenreaders=true (whether to be visible to screen readers)
2602       *     - includefullname=false (whether to include the user's full name together with the user picture)
2603       *     - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2604       * @return string HTML fragment
2605       */
2606      public function user_picture(stdClass $user, array $options = null) {
2607          $userpicture = new user_picture($user);
2608          foreach ((array)$options as $key=>$value) {
2609              if (property_exists($userpicture, $key)) {
2610                  $userpicture->$key = $value;
2611              }
2612          }
2613          return $this->render($userpicture);
2614      }
2615  
2616      /**
2617       * Internal implementation of user image rendering.
2618       *
2619       * @param user_picture $userpicture
2620       * @return string
2621       */
2622      protected function render_user_picture(user_picture $userpicture) {
2623          global $CFG;
2624  
2625          $user = $userpicture->user;
2626          $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2627  
2628          $alt = '';
2629          if ($userpicture->alttext) {
2630              if (!empty($user->imagealt)) {
2631                  $alt = $user->imagealt;
2632              }
2633          }
2634  
2635          if (empty($userpicture->size)) {
2636              $size = 35;
2637          } else if ($userpicture->size === true or $userpicture->size == 1) {
2638              $size = 100;
2639          } else {
2640              $size = $userpicture->size;
2641          }
2642  
2643          $class = $userpicture->class;
2644  
2645          if ($user->picture == 0) {
2646              $class .= ' defaultuserpic';
2647          }
2648  
2649          $src = $userpicture->get_url($this->page, $this);
2650  
2651          $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2652          if (!$userpicture->visibletoscreenreaders) {
2653              $alt = '';
2654          }
2655          $attributes['alt'] = $alt;
2656  
2657          if (!empty($alt)) {
2658              $attributes['title'] = $alt;
2659          }
2660  
2661          // Get the image html output first, auto generated based on initials if one isn't already set.
2662          if ($user->picture == 0 && empty($CFG->enablegravatar) && !defined('BEHAT_SITE_RUNNING')) {
2663              $output = html_writer::tag('span', mb_substr($user->firstname, 0, 1) . mb_substr($user->lastname, 0, 1),
2664                  ['class' => 'userinitials size-' . $size]);
2665          } else {
2666              $output = html_writer::empty_tag('img', $attributes);
2667          }
2668  
2669          // Show fullname together with the picture when desired.
2670          if ($userpicture->includefullname) {
2671              $output .= fullname($userpicture->user, $canviewfullnames);
2672          }
2673  
2674          if (empty($userpicture->courseid)) {
2675              $courseid = $this->page->course->id;
2676          } else {
2677              $courseid = $userpicture->courseid;
2678          }
2679          if ($courseid == SITEID) {
2680              $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2681          } else {
2682              $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2683          }
2684  
2685          // Then wrap it in link if needed. Also we don't wrap it in link if the link redirects to itself.
2686          if (!$userpicture->link ||
2687                  ($this->page->has_set_url() && $this->page->url == $url)) { // Protect against unset page->url.
2688              return $output;
2689          }
2690  
2691          $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2692          if (!$userpicture->visibletoscreenreaders) {
2693              $attributes['tabindex'] = '-1';
2694              $attributes['aria-hidden'] = 'true';
2695          }
2696  
2697          if ($userpicture->popup) {
2698              $id = html_writer::random_id('userpicture');
2699              $attributes['id'] = $id;
2700              $this->add_action_handler(new popup_action('click', $url), $id);
2701          }
2702  
2703          return html_writer::tag('a', $output, $attributes);
2704      }
2705  
2706      /**
2707       * Internal implementation of file tree viewer items rendering.
2708       *
2709       * @param array $dir
2710       * @return string
2711       */
2712      public function htmllize_file_tree($dir) {
2713          if (empty($dir['subdirs']) and empty($dir['files'])) {
2714              return '';
2715          }
2716          $result = '<ul>';
2717          foreach ($dir['subdirs'] as $subdir) {
2718              $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2719          }
2720          foreach ($dir['files'] as $file) {
2721              $filename = $file->get_filename();
2722              $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2723          }
2724          $result .= '</ul>';
2725  
2726          return $result;
2727      }
2728  
2729      /**
2730       * Returns HTML to display the file picker
2731       *
2732       * <pre>
2733       * $OUTPUT->file_picker($options);
2734       * </pre>
2735       *
2736       * Theme developers: DO NOT OVERRIDE! Please override function
2737       * {@link core_renderer::render_file_picker()} instead.
2738       *
2739       * @param array $options associative array with file manager options
2740       *   options are:
2741       *       maxbytes=>-1,
2742       *       itemid=>0,
2743       *       client_id=>uniqid(),
2744       *       acepted_types=>'*',
2745       *       return_types=>FILE_INTERNAL,
2746       *       context=>current page context
2747       * @return string HTML fragment
2748       */
2749      public function file_picker($options) {
2750          $fp = new file_picker($options);
2751          return $this->render($fp);
2752      }
2753  
2754      /**
2755       * Internal implementation of file picker rendering.
2756       *
2757       * @param file_picker $fp
2758       * @return string
2759       */
2760      public function render_file_picker(file_picker $fp) {
2761          $options = $fp->options;
2762          $client_id = $options->client_id;
2763          $strsaved = get_string('filesaved', 'repository');
2764          $straddfile = get_string('openpicker', 'repository');
2765          $strloading  = get_string('loading', 'repository');
2766          $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2767          $strdroptoupload = get_string('droptoupload', 'moodle');
2768          $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2769  
2770          $currentfile = $options->currentfile;
2771          if (empty($currentfile)) {
2772              $currentfile = '';
2773          } else {
2774              $currentfile .= ' - ';
2775          }
2776          if ($options->maxbytes) {
2777              $size = $options->maxbytes;
2778          } else {
2779              $size = get_max_upload_file_size();
2780          }
2781          if ($size == -1) {
2782              $maxsize = '';
2783          } else {
2784              $maxsize = get_string('maxfilesize', 'moodle', display_size($size, 0));
2785          }
2786          if ($options->buttonname) {
2787              $buttonname = ' name="' . $options->buttonname . '"';
2788          } else {
2789              $buttonname = '';
2790          }
2791          $html = <<<EOD
2792  <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2793  $iconprogress
2794  </div>
2795  <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2796      <div>
2797          <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2798          <span> $maxsize </span>
2799      </div>
2800  EOD;
2801          if ($options->env != 'url') {
2802              $html .= <<<EOD
2803      <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2804      <div class="filepicker-filename">
2805          <div class="filepicker-container">$currentfile
2806              <div class="dndupload-message">$strdndenabled <br/>
2807                  <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2808              </div>
2809          </div>
2810          <div class="dndupload-progressbars"></div>
2811      </div>
2812      <div>
2813          <div class="dndupload-target">{$strdroptoupload}<br/>
2814              <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2815          </div>
2816      </div>
2817      </div>
2818  EOD;
2819          }
2820          $html .= '</div>';
2821          return $html;
2822      }
2823  
2824      /**
2825       * @deprecated since Moodle 3.2
2826       */
2827      public function update_module_button() {
2828          throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2829              'modules should not add the edit module button, the link is already available in the Administration block. ' .
2830              'Themes can choose to display the link in the buttons row consistently for all module types.');
2831      }
2832  
2833      /**
2834       * Returns HTML to display a "Turn editing on/off" button in a form.
2835       *
2836       * @param moodle_url $url The URL + params to send through when clicking the button
2837       * @param string $method
2838       * @return string HTML the button
2839       */
2840      public function edit_button(moodle_url $url, string $method = 'post') {
2841  
2842          if ($this->page->theme->haseditswitch == true) {
2843              return;
2844          }
2845          $url->param('sesskey', sesskey());
2846          if ($this->page->user_is_editing()) {
2847              $url->param('edit', 'off');
2848              $editstring = get_string('turneditingoff');
2849          } else {
2850              $url->param('edit', 'on');
2851              $editstring = get_string('turneditingon');
2852          }
2853  
2854          return $this->single_button($url, $editstring, $method);
2855      }
2856  
2857      /**
2858       * Create a navbar switch for toggling editing mode.
2859       *
2860       * @return string Html containing the edit switch
2861       */
2862      public function edit_switch() {
2863          if ($this->page->user_allowed_editing()) {
2864  
2865              $temp = (object) [
2866                  'legacyseturl' => (new moodle_url('/editmode.php'))->out(false),
2867                  'pagecontextid' => $this->page->context->id,
2868                  'pageurl' => $this->page->url,
2869                  'sesskey' => sesskey(),
2870              ];
2871              if ($this->page->user_is_editing()) {
2872                  $temp->checked = true;
2873              }
2874              return $this->render_from_template('core/editswitch', $temp);
2875          }
2876      }
2877  
2878      /**
2879       * Returns HTML to display a simple button to close a window
2880       *
2881       * @param string $text The lang string for the button's label (already output from get_string())
2882       * @return string html fragment
2883       */
2884      public function close_window_button($text='') {
2885          if (empty($text)) {
2886              $text = get_string('closewindow');
2887          }
2888          $button = new single_button(new moodle_url('#'), $text, 'get');
2889          $button->add_action(new component_action('click', 'close_window'));
2890  
2891          return $this->container($this->render($button), 'closewindow');
2892      }
2893  
2894      /**
2895       * Output an error message. By default wraps the error message in <span class="error">.
2896       * If the error message is blank, nothing is output.
2897       *
2898       * @param string $message the error message.
2899       * @return string the HTML to output.
2900       */
2901      public function error_text($message) {
2902          if (empty($message)) {
2903              return '';
2904          }
2905          $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2906          return html_writer::tag('span', $message, array('class' => 'error'));
2907      }
2908  
2909      /**
2910       * Do not call this function directly.
2911       *
2912       * To terminate the current script with a fatal error, call the {@link print_error}
2913       * function, or throw an exception. Doing either of those things will then call this
2914       * function to display the error, before terminating the execution.
2915       *
2916       * @param string $message The message to output
2917       * @param string $moreinfourl URL where more info can be found about the error
2918       * @param string $link Link for the Continue button
2919       * @param array $backtrace The execution backtrace
2920       * @param string $debuginfo Debugging information
2921       * @return string the HTML to output.
2922       */
2923      public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2924          global $CFG;
2925  
2926          $output = '';
2927          $obbuffer = '';
2928  
2929          if ($this->has_started()) {
2930              // we can not always recover properly here, we have problems with output buffering,
2931              // html tables, etc.
2932              $output .= $this->opencontainers->pop_all_but_last();
2933  
2934          } else {
2935              // It is really bad if library code throws exception when output buffering is on,
2936              // because the buffered text would be printed before our start of page.
2937              // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2938              error_reporting(0); // disable notices from gzip compression, etc.
2939              while (ob_get_level() > 0) {
2940                  $buff = ob_get_clean();
2941                  if ($buff === false) {
2942                      break;
2943                  }
2944                  $obbuffer .= $buff;
2945              }
2946              error_reporting($CFG->debug);
2947  
2948              // Output not yet started.
2949              $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2950              if (empty($_SERVER['HTTP_RANGE'])) {
2951                  @header($protocol . ' 404 Not Found');
2952              } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2953                  // Coax iOS 10 into sending the session cookie.
2954                  @header($protocol . ' 403 Forbidden');
2955              } else {
2956                  // Must stop byteserving attempts somehow,
2957                  // this is weird but Chrome PDF viewer can be stopped only with 407!
2958                  @header($protocol . ' 407 Proxy Authentication Required');
2959              }
2960  
2961              $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
2962              $this->page->set_url('/'); // no url
2963              //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
2964              $this->page->set_title(get_string('error'));
2965              $this->page->set_heading($this->page->course->fullname);
2966              // No need to display the activity header when encountering an error.
2967              $this->page->activityheader->disable();
2968              $output .= $this->header();
2969          }
2970  
2971          $message = '<p class="errormessage">' . s($message) . '</p>'.
2972                  '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
2973                  get_string('moreinformation') . '</a></p>';
2974          if (empty($CFG->rolesactive)) {
2975              $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
2976              //It is usually not possible to recover from errors triggered during installation, you may need to create a new database or use a different database prefix for new installation.
2977          }
2978          $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
2979  
2980          if ($CFG->debugdeveloper) {
2981              $labelsep = get_string('labelsep', 'langconfig');
2982              if (!empty($debuginfo)) {
2983                  $debuginfo = s($debuginfo); // removes all nasty JS
2984                  $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2985                  $label = get_string('debuginfo', 'debug') . $labelsep;
2986                  $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
2987              }
2988              if (!empty($backtrace)) {
2989                  $label = get_string('stacktrace', 'debug') . $labelsep;
2990                  $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
2991              }
2992              if ($obbuffer !== '' ) {
2993                  $label = get_string('outputbuffer', 'debug') . $labelsep;
2994                  $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
2995              }
2996          }
2997  
2998          if (empty($CFG->rolesactive)) {
2999              // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
3000          } else if (!empty($link)) {
3001              $output .= $this->continue_button($link);
3002          }
3003  
3004          $output .= $this->footer();
3005  
3006          // Padding to encourage IE to display our error page, rather than its own.
3007          $output .= str_repeat(' ', 512);
3008  
3009          return $output;
3010      }
3011  
3012      /**
3013       * Output a notification (that is, a status message about something that has just happened).
3014       *
3015       * Note: \core\notification::add() may be more suitable for your usage.
3016       *
3017       * @param string $message The message to print out.
3018       * @param ?string $type   The type of notification. See constants on \core\output\notification.
3019       * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
3020       * @return string the HTML to output.
3021       */
3022      public function notification($message, $type = null, $closebutton = true) {
3023          $typemappings = [
3024              // Valid types.
3025              'success'           => \core\output\notification::NOTIFY_SUCCESS,
3026              'info'              => \core\output\notification::NOTIFY_INFO,
3027              'warning'           => \core\output\notification::NOTIFY_WARNING,
3028              'error'             => \core\output\notification::NOTIFY_ERROR,
3029  
3030              // Legacy types mapped to current types.
3031              'notifyproblem'     => \core\output\notification::NOTIFY_ERROR,
3032              'notifytiny'        => \core\output\notification::NOTIFY_ERROR,
3033              'notifyerror'       => \core\output\notification::NOTIFY_ERROR,
3034              'notifysuccess'     => \core\output\notification::NOTIFY_SUCCESS,
3035              'notifymessage'     => \core\output\notification::NOTIFY_INFO,
3036              'notifyredirect'    => \core\output\notification::NOTIFY_INFO,
3037              'redirectmessage'   => \core\output\notification::NOTIFY_INFO,
3038          ];
3039  
3040          $extraclasses = [];
3041  
3042          if ($type) {
3043              if (strpos($type, ' ') === false) {
3044                  // No spaces in the list of classes, therefore no need to loop over and determine the class.
3045                  if (isset($typemappings[$type])) {
3046                      $type = $typemappings[$type];
3047                  } else {
3048                      // The value provided did not match a known type. It must be an extra class.
3049                      $extraclasses = [$type];
3050                  }
3051              } else {
3052                  // Identify what type of notification this is.
3053                  $classarray = explode(' ', self::prepare_classes($type));
3054  
3055                  // Separate out the type of notification from the extra classes.
3056                  foreach ($classarray as $class) {
3057                      if (isset($typemappings[$class])) {
3058                          $type = $typemappings[$class];
3059                      } else {
3060                          $extraclasses[] = $class;
3061                      }
3062                  }
3063              }
3064          }
3065  
3066          $notification = new \core\output\notification($message, $type, $closebutton);
3067          if (count($extraclasses)) {
3068              $notification->set_extra_classes($extraclasses);
3069          }
3070  
3071          // Return the rendered template.
3072          return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3073      }
3074  
3075      /**
3076       * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3077       */
3078      public function notify_problem() {
3079          throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
3080              'please use \core\notification::add(), or \core\output\notification as required.');
3081      }
3082  
3083      /**
3084       * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3085       */
3086      public function notify_success() {
3087          throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
3088              'please use \core\notification::add(), or \core\output\notification as required.');
3089      }
3090  
3091      /**
3092       * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3093       */
3094      public function notify_message() {
3095          throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
3096              'please use \core\notification::add(), or \core\output\notification as required.');
3097      }
3098  
3099      /**
3100       * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3101       */
3102      public function notify_redirect() {
3103          throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
3104              'please use \core\notification::add(), or \core\output\notification as required.');
3105      }
3106  
3107      /**
3108       * Render a notification (that is, a status message about something that has
3109       * just happened).
3110       *
3111       * @param \core\output\notification $notification the notification to print out
3112       * @return string the HTML to output.
3113       */
3114      protected function render_notification(\core\output\notification $notification) {
3115          return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3116      }
3117  
3118      /**
3119       * Returns HTML to display a continue button that goes to a particular URL.
3120       *
3121       * @param string|moodle_url $url The url the button goes to.
3122       * @return string the HTML to output.
3123       */
3124      public function continue_button($url) {
3125          if (!($url instanceof moodle_url)) {
3126              $url = new moodle_url($url);
3127          }
3128          $button = new single_button($url, get_string('continue'), 'get', true);
3129          $button->class = 'continuebutton';
3130  
3131          return $this->render($button);
3132      }
3133  
3134      /**
3135       * Returns HTML to display a single paging bar to provide access to other pages  (usually in a search)
3136       *
3137       * Theme developers: DO NOT OVERRIDE! Please override function
3138       * {@link core_renderer::render_paging_bar()} instead.
3139       *
3140       * @param int $totalcount The total number of entries available to be paged through
3141       * @param int $page The page you are currently viewing
3142       * @param int $perpage The number of entries that should be shown per page
3143       * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3144       * @param string $pagevar name of page parameter that holds the page number
3145       * @return string the HTML to output.
3146       */
3147      public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3148          $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3149          return $this->render($pb);
3150      }
3151  
3152      /**
3153       * Returns HTML to display the paging bar.
3154       *
3155       * @param paging_bar $pagingbar
3156       * @return string the HTML to output.
3157       */
3158      protected function render_paging_bar(paging_bar $pagingbar) {
3159          // Any more than 10 is not usable and causes weird wrapping of the pagination.
3160          $pagingbar->maxdisplay = 10;
3161          return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3162      }
3163  
3164      /**
3165       * Returns HTML to display initials bar to provide access to other pages  (usually in a search)
3166       *
3167       * @param string $current the currently selected letter.
3168       * @param string $class class name to add to this initial bar.
3169       * @param string $title the name to put in front of this initial bar.
3170       * @param string $urlvar URL parameter name for this initial.
3171       * @param string $url URL object.
3172       * @param array $alpha of letters in the alphabet.
3173       * @return string the HTML to output.
3174       */
3175      public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null) {
3176          $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha);
3177          return $this->render($ib);
3178      }
3179  
3180      /**
3181       * Internal implementation of initials bar rendering.
3182       *
3183       * @param initials_bar $initialsbar
3184       * @return string
3185       */
3186      protected function render_initials_bar(initials_bar $initialsbar) {
3187          return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3188      }
3189  
3190      /**
3191       * Output the place a skip link goes to.
3192       *
3193       * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3194       * @return string the HTML to output.
3195       */
3196      public function skip_link_target($id = null) {
3197          return html_writer::span('', '', array('id' => $id));
3198      }
3199  
3200      /**
3201       * Outputs a heading
3202       *
3203       * @param string $text The text of the heading
3204       * @param int $level The level of importance of the heading. Defaulting to 2
3205       * @param string $classes A space-separated list of CSS classes. Defaulting to null
3206       * @param string $id An optional ID
3207       * @return string the HTML to output.
3208       */
3209      public function heading($text, $level = 2, $classes = null, $id = null) {
3210          $level = (integer) $level;
3211          if ($level < 1 or $level > 6) {
3212              throw new coding_exception('Heading level must be an integer between 1 and 6.');
3213          }
3214          return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3215      }
3216  
3217      /**
3218       * Outputs a box.
3219       *
3220       * @param string $contents The contents of the box
3221       * @param string $classes A space-separated list of CSS classes
3222       * @param string $id An optional ID
3223       * @param array $attributes An array of other attributes to give the box.
3224       * @return string the HTML to output.
3225       */
3226      public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3227          return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3228      }
3229  
3230      /**
3231       * Outputs the opening section of a box.
3232       *
3233       * @param string $classes A space-separated list of CSS classes
3234       * @param string $id An optional ID
3235       * @param array $attributes An array of other attributes to give the box.
3236       * @return string the HTML to output.
3237       */
3238      public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3239          $this->opencontainers->push('box', html_writer::end_tag('div'));
3240          $attributes['id'] = $id;
3241          $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3242          return html_writer::start_tag('div', $attributes);
3243      }
3244  
3245      /**
3246       * Outputs the closing section of a box.
3247       *
3248       * @return string the HTML to output.
3249       */
3250      public function box_end() {
3251          return $this->opencontainers->pop('box');
3252      }
3253  
3254      /**
3255       * Outputs a container.
3256       *
3257       * @param string $contents The contents of the box
3258       * @param string $classes A space-separated list of CSS classes
3259       * @param string $id An optional ID
3260       * @return string the HTML to output.
3261       */
3262      public function container($contents, $classes = null, $id = null) {
3263          return $this->container_start($classes, $id) . $contents . $this->container_end();
3264      }
3265  
3266      /**
3267       * Outputs the opening section of a container.
3268       *
3269       * @param string $classes A space-separated list of CSS classes
3270       * @param string $id An optional ID
3271       * @return string the HTML to output.
3272       */
3273      public function container_start($classes = null, $id = null) {
3274          $this->opencontainers->push('container', html_writer::end_tag('div'));
3275          return html_writer::start_tag('div', array('id' => $id,
3276                  'class' => renderer_base::prepare_classes($classes)));
3277      }
3278  
3279      /**
3280       * Outputs the closing section of a container.
3281       *
3282       * @return string the HTML to output.
3283       */
3284      public function container_end() {
3285          return $this->opencontainers->pop('container');
3286      }
3287  
3288      /**
3289       * Make nested HTML lists out of the items
3290       *
3291       * The resulting list will look something like this:
3292       *
3293       * <pre>
3294       * <<ul>>
3295       * <<li>><div class='tree_item parent'>(item contents)</div>
3296       *      <<ul>
3297       *      <<li>><div class='tree_item'>(item contents)</div><</li>>
3298       *      <</ul>>
3299       * <</li>>
3300       * <</ul>>
3301       * </pre>
3302       *
3303       * @param array $items
3304       * @param array $attrs html attributes passed to the top ofs the list
3305       * @return string HTML
3306       */
3307      public function tree_block_contents($items, $attrs = array()) {
3308          // exit if empty, we don't want an empty ul element
3309          if (empty($items)) {
3310              return '';
3311          }
3312          // array of nested li elements
3313          $lis = array();
3314          foreach ($items as $item) {
3315              // this applies to the li item which contains all child lists too
3316              $content = $item->content($this);
3317              $liclasses = array($item->get_css_type());
3318              if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0  && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3319                  $liclasses[] = 'collapsed';
3320              }
3321              if ($item->isactive === true) {
3322                  $liclasses[] = 'current_branch';
3323              }
3324              $liattr = array('class'=>join(' ',$liclasses));
3325              // class attribute on the div item which only contains the item content
3326              $divclasses = array('tree_item');
3327              if ($item->children->count()>0  || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3328                  $divclasses[] = 'branch';
3329              } else {
3330                  $divclasses[] = 'leaf';
3331              }
3332              if (!empty($item->classes) && count($item->classes)>0) {
3333                  $divclasses[] = join(' ', $item->classes);
3334              }
3335              $divattr = array('class'=>join(' ', $divclasses));
3336              if (!empty($item->id)) {
3337                  $divattr['id'] = $item->id;
3338              }
3339              $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3340              if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3341                  $content = html_writer::empty_tag('hr') . $content;
3342              }
3343              $content = html_writer::tag('li', $content, $liattr);
3344              $lis[] = $content;
3345          }
3346          return html_writer::tag('ul', implode("\n", $lis), $attrs);
3347      }
3348  
3349      /**
3350       * Returns a search box.
3351       *
3352       * @param  string $id     The search box wrapper div id, defaults to an autogenerated one.
3353       * @return string         HTML with the search form hidden by default.
3354       */
3355      public function search_box($id = false) {
3356          global $CFG;
3357  
3358          // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3359          // result in an extra included file for each site, even the ones where global search
3360          // is disabled.
3361          if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3362              return '';
3363          }
3364  
3365          $data = [
3366              'action' => new moodle_url('/search/index.php'),
3367              'hiddenfields' => (object) ['name' => 'context', 'value' => $this->page->context->id],
3368              'inputname' => 'q',
3369              'searchstring' => get_string('search'),
3370              ];
3371          return $this->render_from_template('core/search_input_navbar', $data);
3372      }
3373  
3374      /**
3375       * Allow plugins to provide some content to be rendered in the navbar.
3376       * The plugin must define a PLUGIN_render_navbar_output function that returns
3377       * the HTML they wish to add to the navbar.
3378       *
3379       * @return string HTML for the navbar
3380       */
3381      public function navbar_plugin_output() {
3382          $output = '';
3383  
3384          // Give subsystems an opportunity to inject extra html content. The callback
3385          // must always return a string containing valid html.
3386          foreach (\core_component::get_core_subsystems() as $name => $path) {
3387              if ($path) {
3388                  $output .= component_callback($name, 'render_navbar_output', [$this], '');
3389              }
3390          }
3391  
3392          if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3393              foreach ($pluginsfunction as $plugintype => $plugins) {
3394                  foreach ($plugins as $pluginfunction) {
3395                      $output .= $pluginfunction($this);
3396                  }
3397              }
3398          }
3399  
3400          return $output;
3401      }
3402  
3403      /**
3404       * Construct a user menu, returning HTML that can be echoed out by a
3405       * layout file.
3406       *
3407       * @param stdClass $user A user object, usually $USER.
3408       * @param bool $withlinks true if a dropdown should be built.
3409       * @return string HTML fragment.
3410       */
3411      public function user_menu($user = null, $withlinks = null) {
3412          global $USER, $CFG;
3413          require_once($CFG->dirroot . '/user/lib.php');
3414  
3415          if (is_null($user)) {
3416              $user = $USER;
3417          }
3418  
3419          // Note: this behaviour is intended to match that of core_renderer::login_info,
3420          // but should not be considered to be good practice; layout options are
3421          // intended to be theme-specific. Please don't copy this snippet anywhere else.
3422          if (is_null($withlinks)) {
3423              $withlinks = empty($this->page->layout_options['nologinlinks']);
3424          }
3425  
3426          // Add a class for when $withlinks is false.
3427          $usermenuclasses = 'usermenu';
3428          if (!$withlinks) {
3429              $usermenuclasses .= ' withoutlinks';
3430          }
3431  
3432          $returnstr = "";
3433  
3434          // If during initial install, return the empty return string.
3435          if (during_initial_install()) {
3436              return $returnstr;
3437          }
3438  
3439          $loginpage = $this->is_login_page();
3440          $loginurl = get_login_url();
3441  
3442          // Get some navigation opts.
3443          $opts = user_get_user_navigation_info($user, $this->page);
3444  
3445          if (!empty($opts->unauthenticateduser)) {
3446              $returnstr = get_string($opts->unauthenticateduser['content'], 'moodle');
3447              // If not logged in, show the typical not-logged-in string.
3448              if (!$loginpage && (!$opts->unauthenticateduser['guest'] || $withlinks)) {
3449                  $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3450              }
3451  
3452              return html_writer::div(
3453                  html_writer::span(
3454                      $returnstr,
3455                      'login nav-link'
3456                  ),
3457                  $usermenuclasses
3458              );
3459          }
3460  
3461          $avatarclasses = "avatars";
3462          $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3463          $usertextcontents = $opts->metadata['userfullname'];
3464  
3465          // Other user.
3466          if (!empty($opts->metadata['asotheruser'])) {
3467              $avatarcontents .= html_writer::span(
3468                  $opts->metadata['realuseravatar'],
3469                  'avatar realuser'
3470              );
3471              $usertextcontents = $opts->metadata['realuserfullname'];
3472              $usertextcontents .= html_writer::tag(
3473                  'span',
3474                  get_string(
3475                      'loggedinas',
3476                      'moodle',
3477                      html_writer::span(
3478                          $opts->metadata['userfullname'],
3479                          'value'
3480                      )
3481                  ),
3482                  array('class' => 'meta viewingas')
3483              );
3484          }
3485  
3486          // Role.
3487          if (!empty($opts->metadata['asotherrole'])) {
3488              $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3489              $usertextcontents .= html_writer::span(
3490                  $opts->metadata['rolename'],
3491                  'meta role role-' . $role
3492              );
3493          }
3494  
3495          // User login failures.
3496          if (!empty($opts->metadata['userloginfail'])) {
3497              $usertextcontents .= html_writer::span(
3498                  $opts->metadata['userloginfail'],
3499                  'meta loginfailures'
3500              );
3501          }
3502  
3503          // MNet.
3504          if (!empty($opts->metadata['asmnetuser'])) {
3505              $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3506              $usertextcontents .= html_writer::span(
3507                  $opts->metadata['mnetidprovidername'],
3508                  'meta mnet mnet-' . $mnet
3509              );
3510          }
3511  
3512          $returnstr .= html_writer::span(
3513              html_writer::span($usertextcontents, 'usertext mr-1') .
3514              html_writer::span($avatarcontents, $avatarclasses),
3515              'userbutton'
3516          );
3517  
3518          // Create a divider (well, a filler).
3519          $divider = new action_menu_filler();
3520          $divider->primary = false;
3521  
3522          $am = new action_menu();
3523          $am->set_menu_trigger(
3524              $returnstr,
3525              'nav-link'
3526          );
3527          $am->set_action_label(get_string('usermenu'));
3528          $am->set_nowrap_on_items();
3529          if ($withlinks) {
3530              $navitemcount = count($opts->navitems);
3531              $idx = 0;
3532              foreach ($opts->navitems as $key => $value) {
3533  
3534                  switch ($value->itemtype) {
3535                      case 'divider':
3536                          // If the nav item is a divider, add one and skip link processing.
3537                          $am->add($divider);
3538                          break;
3539  
3540                      case 'invalid':
3541                          // Silently skip invalid entries (should we post a notification?).
3542                          break;
3543  
3544                      case 'link':
3545                          // Process this as a link item.
3546                          $pix = null;
3547                          if (isset($value->pix) && !empty($value->pix)) {
3548                              $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3549                          } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3550                              $value->title = html_writer::img(
3551                                  $value->imgsrc,
3552                                  $value->title,
3553                                  array('class' => 'iconsmall')
3554                              ) . $value->title;
3555                          }
3556  
3557                          $al = new action_menu_link_secondary(
3558                              $value->url,
3559                              $pix,
3560                              $value->title,
3561                              array('class' => 'icon')
3562                          );
3563                          if (!empty($value->titleidentifier)) {
3564                              $al->attributes['data-title'] = $value->titleidentifier;
3565                          }
3566                          $am->add($al);
3567                          break;
3568                  }
3569  
3570                  $idx++;
3571  
3572                  // Add dividers after the first item and before the last item.
3573                  if ($idx == 1 || $idx == $navitemcount - 1) {
3574                      $am->add($divider);
3575                  }
3576              }
3577          }
3578  
3579          return html_writer::div(
3580              $this->render($am),
3581              $usermenuclasses
3582          );
3583      }
3584  
3585      /**
3586       * Secure layout login info.
3587       *
3588       * @return string
3589       */
3590      public function secure_layout_login_info() {
3591          if (get_config('core', 'logininfoinsecurelayout')) {
3592              return $this->login_info(false);
3593          } else {
3594              return '';
3595          }
3596      }
3597  
3598      /**
3599       * Returns the language menu in the secure layout.
3600       *
3601       * No custom menu items are passed though, such that it will render only the language selection.
3602       *
3603       * @return string
3604       */
3605      public function secure_layout_language_menu() {
3606          if (get_config('core', 'langmenuinsecurelayout')) {
3607              $custommenu = new custom_menu('', current_language());
3608              return $this->render_custom_menu($custommenu);
3609          } else {
3610              return '';
3611          }
3612      }
3613  
3614      /**
3615       * This renders the navbar.
3616       * Uses bootstrap compatible html.
3617       */
3618      public function navbar() {
3619          return $this->render_from_template('core/navbar', $this->page->navbar);
3620      }
3621  
3622      /**
3623       * Renders a breadcrumb navigation node object.
3624       *
3625       * @param breadcrumb_navigation_node $item The navigation node to render.
3626       * @return string HTML fragment
3627       */
3628      protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3629  
3630          if ($item->action instanceof moodle_url) {
3631              $content = $item->get_content();
3632              $title = $item->get_title();
3633              $attributes = array();
3634              $attributes['itemprop'] = 'url';
3635              if ($title !== '') {
3636                  $attributes['title'] = $title;
3637              }
3638              if ($item->hidden) {
3639                  $attributes['class'] = 'dimmed_text';
3640              }
3641              if ($item->is_last()) {
3642                  $attributes['aria-current'] = 'page';
3643              }
3644              $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3645              $content = html_writer::link($item->action, $content, $attributes);
3646  
3647              $attributes = array();
3648              $attributes['itemscope'] = '';
3649              $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3650              $content = html_writer::tag('span', $content, $attributes);
3651  
3652          } else {
3653              $content = $this->render_navigation_node($item);
3654          }
3655          return $content;
3656      }
3657  
3658      /**
3659       * Renders a navigation node object.
3660       *
3661       * @param navigation_node $item The navigation node to render.
3662       * @return string HTML fragment
3663       */
3664      protected function render_navigation_node(navigation_node $item) {
3665          $content = $item->get_content();
3666          $title = $item->get_title();
3667          if ($item->icon instanceof renderable && !$item->hideicon) {
3668              $icon = $this->render($item->icon);
3669              $content = $icon.$content; // use CSS for spacing of icons
3670          }
3671          if ($item->helpbutton !== null) {
3672              $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3673          }
3674          if ($content === '') {
3675              return '';
3676          }
3677          if ($item->action instanceof action_link) {
3678              $link = $item->action;
3679              if ($item->hidden) {
3680                  $link->add_class('dimmed');
3681              }
3682              if (!empty($content)) {
3683                  // Providing there is content we will use that for the link content.
3684                  $link->text = $content;
3685              }
3686              $content = $this->render($link);
3687          } else if ($item->action instanceof moodle_url) {
3688              $attributes = array();
3689              if ($title !== '') {
3690                  $attributes['title'] = $title;
3691              }
3692              if ($item->hidden) {
3693                  $attributes['class'] = 'dimmed_text';
3694              }
3695              $content = html_writer::link($item->action, $content, $attributes);
3696  
3697          } else if (is_string($item->action) || empty($item->action)) {
3698              $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3699              if ($title !== '') {
3700                  $attributes['title'] = $title;
3701              }
3702              if ($item->hidden) {
3703                  $attributes['class'] = 'dimmed_text';
3704              }
3705              $content = html_writer::tag('span', $content, $attributes);
3706          }
3707          return $content;
3708      }
3709  
3710      /**
3711       * Accessibility: Right arrow-like character is
3712       * used in the breadcrumb trail, course navigation menu
3713       * (previous/next activity), calendar, and search forum block.
3714       * If the theme does not set characters, appropriate defaults
3715       * are set automatically. Please DO NOT
3716       * use &lt; &gt; &raquo; - these are confusing for blind users.
3717       *
3718       * @return string
3719       */
3720      public function rarrow() {
3721          return $this->page->theme->rarrow;
3722      }
3723  
3724      /**
3725       * Accessibility: Left arrow-like character is
3726       * used in the breadcrumb trail, course navigation menu
3727       * (previous/next activity), calendar, and search forum block.
3728       * If the theme does not set characters, appropriate defaults
3729       * are set automatically. Please DO NOT
3730       * use &lt; &gt; &raquo; - these are confusing for blind users.
3731       *
3732       * @return string
3733       */
3734      public function larrow() {
3735          return $this->page->theme->larrow;
3736      }
3737  
3738      /**
3739       * Accessibility: Up arrow-like character is used in
3740       * the book heirarchical navigation.
3741       * If the theme does not set characters, appropriate defaults
3742       * are set automatically. Please DO NOT
3743       * use ^ - this is confusing for blind users.
3744       *
3745       * @return string
3746       */
3747      public function uarrow() {
3748          return $this->page->theme->uarrow;
3749      }
3750  
3751      /**
3752       * Accessibility: Down arrow-like character.
3753       * If the theme does not set characters, appropriate defaults
3754       * are set automatically.
3755       *
3756       * @return string
3757       */
3758      public function darrow() {
3759          return $this->page->theme->darrow;
3760      }
3761  
3762      /**
3763       * Returns the custom menu if one has been set
3764       *
3765       * A custom menu can be configured by browsing to
3766       *    Settings: Administration > Appearance > Themes > Theme settings
3767       * and then configuring the custommenu config setting as described.
3768       *
3769       * Theme developers: DO NOT OVERRIDE! Please override function
3770       * {@link core_renderer::render_custom_menu()} instead.
3771       *
3772       * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3773       * @return string
3774       */
3775      public function custom_menu($custommenuitems = '') {
3776          global $CFG;
3777  
3778          if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3779              $custommenuitems = $CFG->custommenuitems;
3780          }
3781          $custommenu = new custom_menu($custommenuitems, current_language());
3782          return $this->render_custom_menu($custommenu);
3783      }
3784  
3785      /**
3786       * We want to show the custom menus as a list of links in the footer on small screens.
3787       * Just return the menu object exported so we can render it differently.
3788       */
3789      public function custom_menu_flat() {
3790          global $CFG;
3791          $custommenuitems = '';
3792  
3793          if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3794              $custommenuitems = $CFG->custommenuitems;
3795          }
3796          $custommenu = new custom_menu($custommenuitems, current_language());
3797          $langs = get_string_manager()->get_list_of_translations();
3798          $haslangmenu = $this->lang_menu() != '';
3799  
3800          if ($haslangmenu) {
3801              $strlang = get_string('language');
3802              $currentlang = current_language();
3803              if (isset($langs[$currentlang])) {
3804                  $currentlang = $langs[$currentlang];
3805              } else {
3806                  $currentlang = $strlang;
3807              }
3808              $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3809              foreach ($langs as $langtype => $langname) {
3810                  $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3811              }
3812          }
3813  
3814          return $custommenu->export_for_template($this);
3815      }
3816  
3817      /**
3818       * Renders a custom menu object (located in outputcomponents.php)
3819       *
3820       * The custom menu this method produces makes use of the YUI3 menunav widget
3821       * and requires very specific html elements and classes.
3822       *
3823       * @staticvar int $menucount
3824       * @param custom_menu $menu
3825       * @return string
3826       */
3827      protected function render_custom_menu(custom_menu $menu) {
3828          global $CFG;
3829  
3830          $langs = get_string_manager()->get_list_of_translations();
3831          $haslangmenu = $this->lang_menu() != '';
3832  
3833          if (!$menu->has_children() && !$haslangmenu) {
3834              return '';
3835          }
3836  
3837          if ($haslangmenu) {
3838              $strlang = get_string('language');
3839              $currentlang = current_language();
3840              if (isset($langs[$currentlang])) {
3841                  $currentlangstr = $langs[$currentlang];
3842              } else {
3843                  $currentlangstr = $strlang;
3844              }
3845              $this->language = $menu->add($currentlangstr, new moodle_url('#'), $strlang, 10000);
3846              foreach ($langs as $langtype => $langname) {
3847                  $attributes = [];
3848                  // Set the lang attribute for languages different from the page's current language.
3849                  if ($langtype !== $currentlang) {
3850                      $attributes[] = [
3851                          'key' => 'lang',
3852                          'value' => str_replace('_', '-', $langtype),
3853                      ];
3854                  }
3855                  $this->language->add($langname, new moodle_url($this->page->url, ['lang' => $langtype]), null, null, $attributes);
3856              }
3857          }
3858  
3859          $content = '';
3860          foreach ($menu->get_children() as $item) {
3861              $context = $item->export_for_template($this);
3862              $content .= $this->render_from_template('core/custom_menu_item', $context);
3863          }
3864  
3865          return $content;
3866      }
3867  
3868      /**
3869       * Renders a custom menu node as part of a submenu
3870       *
3871       * The custom menu this method produces makes use of the YUI3 menunav widget
3872       * and requires very specific html elements and classes.
3873       *
3874       * @see core:renderer::render_custom_menu()
3875       *
3876       * @staticvar int $submenucount
3877       * @param custom_menu_item $menunode
3878       * @return string
3879       */
3880      protected function render_custom_menu_item(custom_menu_item $menunode) {
3881          // Required to ensure we get unique trackable id's
3882          static $submenucount = 0;
3883          if ($menunode->has_children()) {
3884              // If the child has menus render it as a sub menu
3885              $submenucount++;
3886              $content = html_writer::start_tag('li');
3887              if ($menunode->get_url() !== null) {
3888                  $url = $menunode->get_url();
3889              } else {
3890                  $url = '#cm_submenu_'.$submenucount;
3891              }
3892              $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3893              $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3894              $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3895              $content .= html_writer::start_tag('ul');
3896              foreach ($menunode->get_children() as $menunode) {
3897                  $content .= $this->render_custom_menu_item($menunode);
3898              }
3899              $content .= html_writer::end_tag('ul');
3900              $content .= html_writer::end_tag('div');
3901              $content .= html_writer::end_tag('div');
3902              $content .= html_writer::end_tag('li');
3903          } else {
3904              // The node doesn't have children so produce a final menuitem.
3905              // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3906              $content = '';
3907              if (preg_match("/^#+$/", $menunode->get_text())) {
3908  
3909                  // This is a divider.
3910                  $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3911              } else {
3912                  $content = html_writer::start_tag(
3913                      'li',
3914                      array(
3915                          'class' => 'yui3-menuitem'
3916                      )
3917                  );
3918                  if ($menunode->get_url() !== null) {
3919                      $url = $menunode->get_url();
3920                  } else {
3921                      $url = '#';
3922                  }
3923                  $content .= html_writer::link(
3924                      $url,
3925                      $menunode->get_text(),
3926                      array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3927                  );
3928              }
3929              $content .= html_writer::end_tag('li');
3930          }
3931          // Return the sub menu
3932          return $content;
3933      }
3934  
3935      /**
3936       * Renders theme links for switching between default and other themes.
3937       *
3938       * @return string
3939       */
3940      protected function theme_switch_links() {
3941  
3942          $actualdevice = core_useragent::get_device_type();
3943          $currentdevice = $this->page->devicetypeinuse;
3944          $switched = ($actualdevice != $currentdevice);
3945  
3946          if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3947              // The user is using the a default device and hasn't switched so don't shown the switch
3948              // device links.
3949              return '';
3950          }
3951  
3952          if ($switched) {
3953              $linktext = get_string('switchdevicerecommended');
3954              $devicetype = $actualdevice;
3955          } else {
3956              $linktext = get_string('switchdevicedefault');
3957              $devicetype = 'default';
3958          }
3959          $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
3960  
3961          $content  = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
3962          $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
3963          $content .= html_writer::end_tag('div');
3964  
3965          return $content;
3966      }
3967  
3968      /**
3969       * Renders tabs
3970       *
3971       * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
3972       *
3973       * Theme developers: In order to change how tabs are displayed please override functions
3974       * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
3975       *
3976       * @param array $tabs array of tabs, each of them may have it's own ->subtree
3977       * @param string|null $selected which tab to mark as selected, all parent tabs will
3978       *     automatically be marked as activated
3979       * @param array|string|null $inactive list of ids of inactive tabs, regardless of
3980       *     their level. Note that you can as weel specify tabobject::$inactive for separate instances
3981       * @return string
3982       */
3983      public final function tabtree($tabs, $selected = null, $inactive = null) {
3984          return $this->render(new tabtree($tabs, $selected, $inactive));
3985      }
3986  
3987      /**
3988       * Renders tabtree
3989       *
3990       * @param tabtree $tabtree
3991       * @return string
3992       */
3993      protected function render_tabtree(tabtree $tabtree) {
3994          if (empty($tabtree->subtree)) {
3995              return '';
3996          }
3997          $data = $tabtree->export_for_template($this);
3998          return $this->render_from_template('core/tabtree', $data);
3999      }
4000  
4001      /**
4002       * Renders tabobject (part of tabtree)
4003       *
4004       * This function is called from {@link core_renderer::render_tabtree()}
4005       * and also it calls itself when printing the $tabobject subtree recursively.
4006       *
4007       * Property $tabobject->level indicates the number of row of tabs.
4008       *
4009       * @param tabobject $tabobject
4010       * @return string HTML fragment
4011       */
4012      protected function render_tabobject(tabobject $tabobject) {
4013          $str = '';
4014  
4015          // Print name of the current tab.
4016          if ($tabobject instanceof tabtree) {
4017              // No name for tabtree root.
4018          } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
4019              // Tab name without a link. The <a> tag is used for styling.
4020              $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
4021          } else {
4022              // Tab name with a link.
4023              if (!($tabobject->link instanceof moodle_url)) {
4024                  // backward compartibility when link was passed as quoted string
4025                  $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
4026              } else {
4027                  $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
4028              }
4029          }
4030  
4031          if (empty($tabobject->subtree)) {
4032              if ($tabobject->selected) {
4033                  $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
4034              }
4035              return $str;
4036          }
4037  
4038          // Print subtree.
4039          if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
4040              $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
4041              $cnt = 0;
4042              foreach ($tabobject->subtree as $tab) {
4043                  $liclass = '';
4044                  if (!$cnt) {
4045                      $liclass .= ' first';
4046                  }
4047                  if ($cnt == count($tabobject->subtree) - 1) {
4048                      $liclass .= ' last';
4049                  }
4050                  if ((empty($tab->subtree)) && (!empty($tab->selected))) {
4051                      $liclass .= ' onerow';
4052                  }
4053  
4054                  if ($tab->selected) {
4055                      $liclass .= ' here selected';
4056                  } else if ($tab->activated) {
4057                      $liclass .= ' here active';
4058                  }
4059  
4060                  // This will recursively call function render_tabobject() for each item in subtree.
4061                  $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
4062                  $cnt++;
4063              }
4064              $str .= html_writer::end_tag('ul');
4065          }
4066  
4067          return $str;
4068      }
4069  
4070      /**
4071       * Get the HTML for blocks in the given region.
4072       *
4073       * @since Moodle 2.5.1 2.6
4074       * @param string $region The region to get HTML for.
4075       * @param array $classes Wrapping tag classes.
4076       * @param string $tag Wrapping tag.
4077       * @param boolean $fakeblocksonly Include fake blocks only.
4078       * @return string HTML.
4079       */
4080      public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
4081          $displayregion = $this->page->apply_theme_region_manipulations($region);
4082          $classes = (array)$classes;
4083          $classes[] = 'block-region';
4084          $attributes = array(
4085              'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
4086              'class' => join(' ', $classes),
4087              'data-blockregion' => $displayregion,
4088              'data-droptarget' => '1'
4089          );
4090          if ($this->page->blocks->region_has_content($displayregion, $this)) {
4091              $content = $this->blocks_for_region($displayregion, $fakeblocksonly);
4092          } else {
4093              $content = '';
4094          }
4095          return html_writer::tag($tag, $content, $attributes);
4096      }
4097  
4098      /**
4099       * Renders a custom block region.
4100       *
4101       * Use this method if you want to add an additional block region to the content of the page.
4102       * Please note this should only be used in special situations.
4103       * We want to leave the theme is control where ever possible!
4104       *
4105       * This method must use the same method that the theme uses within its layout file.
4106       * As such it asks the theme what method it is using.
4107       * It can be one of two values, blocks or blocks_for_region (deprecated).
4108       *
4109       * @param string $regionname The name of the custom region to add.
4110       * @return string HTML for the block region.
4111       */
4112      public function custom_block_region($regionname) {
4113          if ($this->page->theme->get_block_render_method() === 'blocks') {
4114              return $this->blocks($regionname);
4115          } else {
4116              return $this->blocks_for_region($regionname);
4117          }
4118      }
4119  
4120      /**
4121       * Returns the CSS classes to apply to the body tag.
4122       *
4123       * @since Moodle 2.5.1 2.6
4124       * @param array $additionalclasses Any additional classes to apply.
4125       * @return string
4126       */
4127      public function body_css_classes(array $additionalclasses = array()) {
4128          return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
4129      }
4130  
4131      /**
4132       * The ID attribute to apply to the body tag.
4133       *
4134       * @since Moodle 2.5.1 2.6
4135       * @return string
4136       */
4137      public function body_id() {
4138          return $this->page->bodyid;
4139      }
4140  
4141      /**
4142       * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4143       *
4144       * @since Moodle 2.5.1 2.6
4145       * @param string|array $additionalclasses Any additional classes to give the body tag,
4146       * @return string
4147       */
4148      public function body_attributes($additionalclasses = array()) {
4149          if (!is_array($additionalclasses)) {
4150              $additionalclasses = explode(' ', $additionalclasses);
4151          }
4152          return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4153      }
4154  
4155      /**
4156       * Gets HTML for the page heading.
4157       *
4158       * @since Moodle 2.5.1 2.6
4159       * @param string $tag The tag to encase the heading in. h1 by default.
4160       * @return string HTML.
4161       */
4162      public function page_heading($tag = 'h1') {
4163          return html_writer::tag($tag, $this->page->heading);
4164      }
4165  
4166      /**
4167       * Gets the HTML for the page heading button.
4168       *
4169       * @since Moodle 2.5.1 2.6
4170       * @return string HTML.
4171       */
4172      public function page_heading_button() {
4173          return $this->page->button;
4174      }
4175  
4176      /**
4177       * Returns the Moodle docs link to use for this page.
4178       *
4179       * @since Moodle 2.5.1 2.6
4180       * @param string $text
4181       * @return string
4182       */
4183      public function page_doc_link($text = null) {
4184          if ($text === null) {
4185              $text = get_string('moodledocslink');
4186          }
4187          $path = page_get_doc_link_path($this->page);
4188          if (!$path) {
4189              return '';
4190          }
4191          return $this->doc_link($path, $text);
4192      }
4193  
4194      /**
4195       * Returns the HTML for the site support email link
4196       *
4197       * @param array $customattribs Array of custom attributes for the support email anchor tag.
4198       * @return string The html code for the support email link.
4199       */
4200      public function supportemail(array $customattribs = []): string {
4201          global $CFG;
4202  
4203          $label = get_string('contactsitesupport', 'admin');
4204          $icon = $this->pix_icon('t/email', '');
4205          $content = $icon . $label;
4206  
4207          if (!empty($CFG->supportpage)) {
4208              $attributes = ['href' => $CFG->supportpage, 'target' => 'blank'];
4209              $content .= $this->pix_icon('i/externallink', '', 'moodle', ['class' => 'ml-1']);
4210          } else {
4211              $attributes = ['href' => $CFG->wwwroot . '/user/contactsitesupport.php'];
4212          }
4213  
4214          $attributes += $customattribs;
4215  
4216          return html_writer::tag('a', $content, $attributes);
4217      }
4218  
4219      /**
4220       * Returns the services and support link for the help pop-up.
4221       *
4222       * @return string
4223       */
4224      public function services_support_link(): string {
4225          global $CFG;
4226  
4227          if (during_initial_install() ||
4228              (isset($CFG->showservicesandsupportcontent) && $CFG->showservicesandsupportcontent == false) ||
4229              !is_siteadmin()) {
4230              return '';
4231          }
4232  
4233          $liferingicon = $this->pix_icon('t/life-ring', '', 'moodle', ['class' => 'fa fa-life-ring']);
4234          $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle', ['class' => 'ml-1']);
4235          $link = 'https://moodle.com/help/?utm_source=CTA-banner&utm_medium=platform&utm_campaign=name~Moodle4+cat~lms+mp~no';
4236          $content = $liferingicon . get_string('moodleservicesandsupport') . $newwindowicon;
4237  
4238          return html_writer::tag('a', $content, ['target' => '_blank', 'href' => $link]);
4239      }
4240  
4241      /**
4242       * Helper function to decide whether to show the help popover header or not.
4243       *
4244       * @return bool
4245       */
4246      public function has_popover_links(): bool {
4247          return !empty($this->services_support_link()) || !empty($this->page_doc_link()) || !empty($this->supportemail());
4248      }
4249  
4250      /**
4251       * Returns the page heading menu.
4252       *
4253       * @since Moodle 2.5.1 2.6
4254       * @return string HTML.
4255       */
4256      public function page_heading_menu() {
4257          return $this->page->headingmenu;
4258      }
4259  
4260      /**
4261       * Returns the title to use on the page.
4262       *
4263       * @since Moodle 2.5.1 2.6
4264       * @return string
4265       */
4266      public function page_title() {
4267          return $this->page->title;
4268      }
4269  
4270      /**
4271       * Returns the moodle_url for the favicon.
4272       *
4273       * @since Moodle 2.5.1 2.6
4274       * @return moodle_url The moodle_url for the favicon
4275       */
4276      public function favicon() {
4277          return $this->image_url('favicon', 'theme');
4278      }
4279  
4280      /**
4281       * Renders preferences groups.
4282       *
4283       * @param  preferences_groups $renderable The renderable
4284       * @return string The output.
4285       */
4286      public function render_preferences_groups(preferences_groups $renderable) {
4287          return $this->render_from_template('core/preferences_groups', $renderable);
4288      }
4289  
4290      /**
4291       * Renders preferences group.
4292       *
4293       * @param  preferences_group $renderable The renderable
4294       * @return string The output.
4295       */
4296      public function render_preferences_group(preferences_group $renderable) {
4297          $html = '';
4298          $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4299          $html .= $this->heading($renderable->title, 3);
4300          $html .= html_writer::start_tag('ul');
4301          foreach ($renderable->nodes as $node) {
4302              if ($node->has_children()) {
4303                  debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4304              }
4305              $html .= html_writer::tag('li', $this->render($node));
4306          }
4307          $html .= html_writer::end_tag('ul');
4308          $html .= html_writer::end_tag('div');
4309          return $html;
4310      }
4311  
4312      public function context_header($headerinfo = null, $headinglevel = 1) {
4313          global $DB, $USER, $CFG, $SITE;
4314          require_once($CFG->dirroot . '/user/lib.php');
4315          $context = $this->page->context;
4316          $heading = null;
4317          $imagedata = null;
4318          $subheader = null;
4319          $userbuttons = null;
4320  
4321          // Make sure to use the heading if it has been set.
4322          if (isset($headerinfo['heading'])) {
4323              $heading = $headerinfo['heading'];
4324          } else {
4325              $heading = $this->page->heading;
4326          }
4327  
4328          // The user context currently has images and buttons. Other contexts may follow.
4329          if ((isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) && $this->page->pagetype !== 'my-index') {
4330              if (isset($headerinfo['user'])) {
4331                  $user = $headerinfo['user'];
4332              } else {
4333                  // Look up the user information if it is not supplied.
4334                  $user = $DB->get_record('user', array('id' => $context->instanceid));
4335              }
4336  
4337              // If the user context is set, then use that for capability checks.
4338              if (isset($headerinfo['usercontext'])) {
4339                  $context = $headerinfo['usercontext'];
4340              }
4341  
4342              // Only provide user information if the user is the current user, or a user which the current user can view.
4343              // When checking user_can_view_profile(), either:
4344              // If the page context is course, check the course context (from the page object) or;
4345              // If page context is NOT course, then check across all courses.
4346              $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4347  
4348              if (user_can_view_profile($user, $course)) {
4349                  // Use the user's full name if the heading isn't set.
4350                  if (empty($heading)) {
4351                      $heading = fullname($user);
4352                  }
4353  
4354                  $imagedata = $this->user_picture($user, array('size' => 100));
4355  
4356                  // Check to see if we should be displaying a message button.
4357                  if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4358                      $userbuttons = array(
4359                          'messages' => array(
4360                              'buttontype' => 'message',
4361                              'title' => get_string('message', 'message'),
4362                              'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4363                              'image' => 'message',
4364                              'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4365                              'page' => $this->page
4366                          )
4367                      );
4368  
4369                      if ($USER->id != $user->id) {
4370                          $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4371                          $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4372                          $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4373                          $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4374                          $userbuttons['togglecontact'] = array(
4375                                  'buttontype' => 'togglecontact',
4376                                  'title' => get_string($contacttitle, 'message'),
4377                                  'url' => new moodle_url('/message/index.php', array(
4378                                          'user1' => $USER->id,
4379                                          'user2' => $user->id,
4380                                          $contacturlaction => $user->id,
4381                                          'sesskey' => sesskey())
4382                                  ),
4383                                  'image' => $contactimage,
4384                                  'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4385                                  'page' => $this->page
4386                              );
4387                      }
4388                  }
4389              } else {
4390                  $heading = null;
4391              }
4392          }
4393  
4394  
4395          $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4396          return $this->render_context_header($contextheader);
4397      }
4398  
4399      /**
4400       * Renders the skip links for the page.
4401       *
4402       * @param array $links List of skip links.
4403       * @return string HTML for the skip links.
4404       */
4405      public function render_skip_links($links) {
4406          $context = [ 'links' => []];
4407  
4408          foreach ($links as $url => $text) {
4409              $context['links'][] = [ 'url' => $url, 'text' => $text];
4410          }
4411  
4412          return $this->render_from_template('core/skip_links', $context);
4413      }
4414  
4415       /**
4416        * Renders the header bar.
4417        *
4418        * @param context_header $contextheader Header bar object.
4419        * @return string HTML for the header bar.
4420        */
4421      protected function render_context_header(context_header $contextheader) {
4422  
4423          // Generate the heading first and before everything else as we might have to do an early return.
4424          if (!isset($contextheader->heading)) {
4425              $heading = $this->heading($this->page->heading, $contextheader->headinglevel);
4426          } else {
4427              $heading = $this->heading($contextheader->heading, $contextheader->headinglevel);
4428          }
4429  
4430          $showheader = empty($this->page->layout_options['nocontextheader']);
4431          if (!$showheader) {
4432              // Return the heading wrapped in an sr-only element so it is only visible to screen-readers.
4433              return html_writer::div($heading, 'sr-only');
4434          }
4435  
4436          // All the html stuff goes here.
4437          $html = html_writer::start_div('page-context-header');
4438  
4439          // Image data.
4440          if (isset($contextheader->imagedata)) {
4441              // Header specific image.
4442              $html .= html_writer::div($contextheader->imagedata, 'page-header-image icon-size-7');
4443          }
4444  
4445          // Headings.
4446          if (isset($contextheader->prefix)) {
4447              $prefix = html_writer::div($contextheader->prefix, 'text-muted');
4448              $heading = $prefix . $heading;
4449          }
4450          $html .= html_writer::tag('div', $heading, array('class' => 'page-header-headings'));
4451  
4452          // Buttons.
4453          if (isset($contextheader->additionalbuttons)) {
4454              $html .= html_writer::start_div('btn-group header-button-group');
4455              foreach ($contextheader->additionalbuttons as $button) {
4456                  if (!isset($button->page)) {
4457                      // Include js for messaging.
4458                      if ($button['buttontype'] === 'togglecontact') {
4459                          \core_message\helper::togglecontact_requirejs();
4460                      }
4461                      if ($button['buttontype'] === 'message') {
4462                          \core_message\helper::messageuser_requirejs();
4463                      }
4464                      $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4465                          'class' => 'iconsmall',
4466                          'role' => 'presentation'
4467                      ));
4468                      $image .= html_writer::span($button['title'], 'header-button-title');
4469                  } else {
4470                      $image = html_writer::empty_tag('img', array(
4471                          'src' => $button['formattedimage'],
4472                          'role' => 'presentation'
4473                      ));
4474                  }
4475                  $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4476              }
4477              $html .= html_writer::end_div();
4478          }
4479          $html .= html_writer::end_div();
4480  
4481          return $html;
4482      }
4483  
4484      /**
4485       * Wrapper for header elements.
4486       *
4487       * @return string HTML to display the main header.
4488       */
4489      public function full_header() {
4490          $pagetype = $this->page->pagetype;
4491          $homepage = get_home_page();
4492          $homepagetype = null;
4493          // Add a special case since /my/courses is a part of the /my subsystem.
4494          if ($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES) {
4495              $homepagetype = 'my-index';
4496          } else if ($homepage == HOMEPAGE_SITE) {
4497              $homepagetype = 'site-index';
4498          }
4499          if ($this->page->include_region_main_settings_in_header_actions() &&
4500                  !$this->page->blocks->is_block_present('settings')) {
4501              // Only include the region main settings if the page has requested it and it doesn't already have
4502              // the settings block on it. The region main settings are included in the settings block and
4503              // duplicating the content causes behat failures.
4504              $this->page->add_header_action(html_writer::div(
4505                  $this->region_main_settings_menu(),
4506                  'd-print-none',
4507                  ['id' => 'region-main-settings-menu']
4508              ));
4509          }
4510  
4511          $header = new stdClass();
4512          $header->settingsmenu = $this->context_header_settings_menu();
4513          $header->contextheader = $this->context_header();
4514          $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4515          $header->navbar = $this->navbar();
4516          $header->pageheadingbutton = $this->page_heading_button();
4517          $header->courseheader = $this->course_header();
4518          $header->headeractions = $this->page->get_header_actions();
4519          if (!empty($pagetype) && !empty($homepagetype) && $pagetype == $homepagetype) {
4520              $header->welcomemessage = \core_user::welcome_message();
4521          }
4522          return $this->render_from_template('core/full_header', $header);
4523      }
4524  
4525      /**
4526       * This is an optional menu that can be added to a layout by a theme. It contains the
4527       * menu for the course administration, only on the course main page.
4528       *
4529       * @return string
4530       */
4531      public function context_header_settings_menu() {
4532          $context = $this->page->context;
4533          $menu = new action_menu();
4534  
4535          $items = $this->page->navbar->get_items();
4536          $currentnode = end($items);
4537  
4538          $showcoursemenu = false;
4539          $showfrontpagemenu = false;
4540          $showusermenu = false;
4541  
4542          // We are on the course home page.
4543          if (($context->contextlevel == CONTEXT_COURSE) &&
4544                  !empty($currentnode) &&
4545                  ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4546              $showcoursemenu = true;
4547          }
4548  
4549          $courseformat = course_get_format($this->page->course);
4550          // This is a single activity course format, always show the course menu on the activity main page.
4551          if ($context->contextlevel == CONTEXT_MODULE &&
4552                  !$courseformat->has_view_page()) {
4553  
4554              $this->page->navigation->initialise();
4555              $activenode = $this->page->navigation->find_active_node();
4556              // If the settings menu has been forced then show the menu.
4557              if ($this->page->is_settings_menu_forced()) {
4558                  $showcoursemenu = true;
4559              } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4560                              $activenode->type == navigation_node::TYPE_RESOURCE)) {
4561  
4562                  // We only want to show the menu on the first page of the activity. This means
4563                  // the breadcrumb has no additional nodes.
4564                  if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4565                      $showcoursemenu = true;
4566                  }
4567              }
4568          }
4569  
4570          // This is the site front page.
4571          if ($context->contextlevel == CONTEXT_COURSE &&
4572                  !empty($currentnode) &&
4573                  $currentnode->key === 'home') {
4574              $showfrontpagemenu = true;
4575          }
4576  
4577          // This is the user profile page.
4578          if ($context->contextlevel == CONTEXT_USER &&
4579                  !empty($currentnode) &&
4580                  ($currentnode->key === 'myprofile')) {
4581              $showusermenu = true;
4582          }
4583  
4584          if ($showfrontpagemenu) {
4585              $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4586              if ($settingsnode) {
4587                  // Build an action menu based on the visible nodes from this navigation tree.
4588                  $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4589  
4590                  // We only add a list to the full settings menu if we didn't include every node in the short menu.
4591                  if ($skipped) {
4592                      $text = get_string('morenavigationlinks');
4593                      $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4594                      $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4595                      $menu->add_secondary_action($link);
4596                  }
4597              }
4598          } else if ($showcoursemenu) {
4599              $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4600              if ($settingsnode) {
4601                  // Build an action menu based on the visible nodes from this navigation tree.
4602                  $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4603  
4604                  // We only add a list to the full settings menu if we didn't include every node in the short menu.
4605                  if ($skipped) {
4606                      $text = get_string('morenavigationlinks');
4607                      $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4608                      $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4609                      $menu->add_secondary_action($link);
4610                  }
4611              }
4612          } else if ($showusermenu) {
4613              // Get the course admin node from the settings navigation.
4614              $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4615              if ($settingsnode) {
4616                  // Build an action menu based on the visible nodes from this navigation tree.
4617                  $this->build_action_menu_from_navigation($menu, $settingsnode);
4618              }
4619          }
4620  
4621          return $this->render($menu);
4622      }
4623  
4624      /**
4625       * Take a node in the nav tree and make an action menu out of it.
4626       * The links are injected in the action menu.
4627       *
4628       * @param action_menu $menu
4629       * @param navigation_node $node
4630       * @param boolean $indent
4631       * @param boolean $onlytopleafnodes
4632       * @return boolean nodesskipped - True if nodes were skipped in building the menu
4633       */
4634      protected function build_action_menu_from_navigation(action_menu $menu,
4635              navigation_node $node,
4636              $indent = false,
4637              $onlytopleafnodes = false) {
4638          $skipped = false;
4639          // Build an action menu based on the visible nodes from this navigation tree.
4640          foreach ($node->children as $menuitem) {
4641              if ($menuitem->display) {
4642                  if ($onlytopleafnodes && $menuitem->children->count()) {
4643                      $skipped = true;
4644                      continue;
4645                  }
4646                  if ($menuitem->action) {
4647                      if ($menuitem->action instanceof action_link) {
4648                          $link = $menuitem->action;
4649                          // Give preference to setting icon over action icon.
4650                          if (!empty($menuitem->icon)) {
4651                              $link->icon = $menuitem->icon;
4652                          }
4653                      } else {
4654                          $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4655                      }
4656                  } else {
4657                      if ($onlytopleafnodes) {
4658                          $skipped = true;
4659                          continue;
4660                      }
4661                      $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4662                  }
4663                  if ($indent) {
4664                      $link->add_class('ml-4');
4665                  }
4666                  if (!empty($menuitem->classes)) {
4667                      $link->add_class(implode(" ", $menuitem->classes));
4668                  }
4669  
4670                  $menu->add_secondary_action($link);
4671                  $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4672              }
4673          }
4674          return $skipped;
4675      }
4676  
4677      /**
4678       * This is an optional menu that can be added to a layout by a theme. It contains the
4679       * menu for the most specific thing from the settings block. E.g. Module administration.
4680       *
4681       * @return string
4682       */
4683      public function region_main_settings_menu() {
4684          $context = $this->page->context;
4685          $menu = new action_menu();
4686  
4687          if ($context->contextlevel == CONTEXT_MODULE) {
4688  
4689              $this->page->navigation->initialise();
4690              $node = $this->page->navigation->find_active_node();
4691              $buildmenu = false;
4692              // If the settings menu has been forced then show the menu.
4693              if ($this->page->is_settings_menu_forced()) {
4694                  $buildmenu = true;
4695              } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4696                              $node->type == navigation_node::TYPE_RESOURCE)) {
4697  
4698                  $items = $this->page->navbar->get_items();
4699                  $navbarnode = end($items);
4700                  // We only want to show the menu on the first page of the activity. This means
4701                  // the breadcrumb has no additional nodes.
4702                  if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4703                      $buildmenu = true;
4704                  }
4705              }
4706              if ($buildmenu) {
4707                  // Get the course admin node from the settings navigation.
4708                  $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4709                  if ($node) {
4710                      // Build an action menu based on the visible nodes from this navigation tree.
4711                      $this->build_action_menu_from_navigation($menu, $node);
4712                  }
4713              }
4714  
4715          } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4716              // For course category context, show category settings menu, if we're on the course category page.
4717              if ($this->page->pagetype === 'course-index-category') {
4718                  $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4719                  if ($node) {
4720                      // Build an action menu based on the visible nodes from this navigation tree.
4721                      $this->build_action_menu_from_navigation($menu, $node);
4722                  }
4723              }
4724  
4725          } else {
4726              $items = $this->page->navbar->get_items();
4727              $navbarnode = end($items);
4728  
4729              if ($navbarnode && ($navbarnode->key === 'participants')) {
4730                  $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4731                  if ($node) {
4732                      // Build an action menu based on the visible nodes from this navigation tree.
4733                      $this->build_action_menu_from_navigation($menu, $node);
4734                  }
4735  
4736              }
4737          }
4738          return $this->render($menu);
4739      }
4740  
4741      /**
4742       * Displays the list of tags associated with an entry
4743       *
4744       * @param array $tags list of instances of core_tag or stdClass
4745       * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4746       *               to use default, set to '' (empty string) to omit the label completely
4747       * @param string $classes additional classes for the enclosing div element
4748       * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4749       *               will be appended to the end, JS will toggle the rest of the tags
4750       * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4751       * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4752       * @return string
4753       */
4754      public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4755              $pagecontext = null, $accesshidelabel = false) {
4756          $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4757          return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4758      }
4759  
4760      /**
4761       * Renders element for inline editing of any value
4762       *
4763       * @param \core\output\inplace_editable $element
4764       * @return string
4765       */
4766      public function render_inplace_editable(\core\output\inplace_editable $element) {
4767          return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4768      }
4769  
4770      /**
4771       * Renders a bar chart.
4772       *
4773       * @param \core\chart_bar $chart The chart.
4774       * @return string.
4775       */
4776      public function render_chart_bar(\core\chart_bar $chart) {
4777          return $this->render_chart($chart);
4778      }
4779  
4780      /**
4781       * Renders a line chart.
4782       *
4783       * @param \core\chart_line $chart The chart.
4784       * @return string.
4785       */
4786      public function render_chart_line(\core\chart_line $chart) {
4787          return $this->render_chart($chart);
4788      }
4789  
4790      /**
4791       * Renders a pie chart.
4792       *
4793       * @param \core\chart_pie $chart The chart.
4794       * @return string.
4795       */
4796      public function render_chart_pie(\core\chart_pie $chart) {
4797          return $this->render_chart($chart);
4798      }
4799  
4800      /**
4801       * Renders a chart.
4802       *
4803       * @param \core\chart_base $chart The chart.
4804       * @param bool $withtable Whether to include a data table with the chart.
4805       * @return string.
4806       */
4807      public function render_chart(\core\chart_base $chart, $withtable = true) {
4808          $chartdata = json_encode($chart);
4809          return $this->render_from_template('core/chart', (object) [
4810              'chartdata' => $chartdata,
4811              'withtable' => $withtable
4812          ]);
4813      }
4814  
4815      /**
4816       * Renders the login form.
4817       *
4818       * @param \core_auth\output\login $form The renderable.
4819       * @return string
4820       */
4821      public function render_login(\core_auth\output\login $form) {
4822          global $CFG, $SITE;
4823  
4824          $context = $form->export_for_template($this);
4825  
4826          $context->errorformatted = $this->error_text($context->error);
4827          $url = $this->get_logo_url();
4828          if ($url) {
4829              $url = $url->out(false);
4830          }
4831          $context->logourl = $url;
4832          $context->sitename = format_string($SITE->fullname, true,
4833                  ['context' => context_course::instance(SITEID), "escape" => false]);
4834  
4835          return $this->render_from_template('core/loginform', $context);
4836      }
4837  
4838      /**
4839       * Renders an mform element from a template.
4840       *
4841       * @param HTML_QuickForm_element $element element
4842       * @param bool $required if input is required field
4843       * @param bool $advanced if input is an advanced field
4844       * @param string $error error message to display
4845       * @param bool $ingroup True if this element is rendered as part of a group
4846       * @return mixed string|bool
4847       */
4848      public function mform_element($element, $required, $advanced, $error, $ingroup) {
4849          $templatename = 'core_form/element-' . $element->getType();
4850          if ($ingroup) {
4851              $templatename .= "-inline";
4852          }
4853          try {
4854              // We call this to generate a file not found exception if there is no template.
4855              // We don't want to call export_for_template if there is no template.
4856              core\output\mustache_template_finder::get_template_filepath($templatename);
4857  
4858              if ($element instanceof templatable) {
4859                  $elementcontext = $element->export_for_template($this);
4860  
4861                  $helpbutton = '';
4862                  if (method_exists($element, 'getHelpButton')) {
4863                      $helpbutton = $element->getHelpButton();
4864                  }
4865                  $label = $element->getLabel();
4866                  $text = '';
4867                  if (method_exists($element, 'getText')) {
4868                      // There currently exists code that adds a form element with an empty label.
4869                      // If this is the case then set the label to the description.
4870                      if (empty($label)) {
4871                          $label = $element->getText();
4872                      } else {
4873                          $text = $element->getText();
4874                      }
4875                  }
4876  
4877                  // Generate the form element wrapper ids and names to pass to the template.
4878                  // This differs between group and non-group elements.
4879                  if ($element->getType() === 'group') {
4880                      // Group element.
4881                      // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4882                      $elementcontext['wrapperid'] = $elementcontext['id'];
4883  
4884                      // Ensure group elements pass through the group name as the element name.
4885                      $elementcontext['name'] = $elementcontext['groupname'];
4886                  } else {
4887                      // Non grouped element.
4888                      // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4889                      $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4890                  }
4891  
4892                  $context = array(
4893                      'element' => $elementcontext,
4894                      'label' => $label,
4895                      'text' => $text,
4896                      'required' => $required,
4897                      'advanced' => $advanced,
4898                      'helpbutton' => $helpbutton,
4899                      'error' => $error
4900                  );
4901                  return $this->render_from_template($templatename, $context);
4902              }
4903          } catch (Exception $e) {
4904              // No template for this element.
4905              return false;
4906          }
4907      }
4908  
4909      /**
4910       * Render the login signup form into a nice template for the theme.
4911       *
4912       * @param mform $form
4913       * @return string
4914       */
4915      public function render_login_signup_form($form) {
4916          global $SITE;
4917  
4918          $context = $form->export_for_template($this);
4919          $url = $this->get_logo_url();
4920          if ($url) {
4921              $url = $url->out(false);
4922          }
4923          $context['logourl'] = $url;
4924          $context['sitename'] = format_string($SITE->fullname, true,
4925                  ['context' => context_course::instance(SITEID), "escape" => false]);
4926  
4927          return $this->render_from_template('core/signup_form_layout', $context);
4928      }
4929  
4930      /**
4931       * Render the verify age and location page into a nice template for the theme.
4932       *
4933       * @param \core_auth\output\verify_age_location_page $page The renderable
4934       * @return string
4935       */
4936      protected function render_verify_age_location_page($page) {
4937          $context = $page->export_for_template($this);
4938  
4939          return $this->render_from_template('core/auth_verify_age_location_page', $context);
4940      }
4941  
4942      /**
4943       * Render the digital minor contact information page into a nice template for the theme.
4944       *
4945       * @param \core_auth\output\digital_minor_page $page The renderable
4946       * @return string
4947       */
4948      protected function render_digital_minor_page($page) {
4949          $context = $page->export_for_template($this);
4950  
4951          return $this->render_from_template('core/auth_digital_minor_page', $context);
4952      }
4953  
4954      /**
4955       * Renders a progress bar.
4956       *
4957       * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
4958       *
4959       * @param  progress_bar $bar The bar.
4960       * @return string HTML fragment
4961       */
4962      public function render_progress_bar(progress_bar $bar) {
4963          $data = $bar->export_for_template($this);
4964          return $this->render_from_template('core/progress_bar', $data);
4965      }
4966  
4967      /**
4968       * Renders an update to a progress bar.
4969       *
4970       * Note: This does not cleanly map to a renderable class and should
4971       * never be used directly.
4972       *
4973       * @param  string $id
4974       * @param  float $percent
4975       * @param  string $msg Message
4976       * @param  string $estimate time remaining message
4977       * @return string ascii fragment
4978       */
4979      public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
4980          return html_writer::script(js_writer::function_call('updateProgressBar', [$id, $percent, $msg, $estimate]));
4981      }
4982  
4983      /**
4984       * Renders element for a toggle-all checkbox.
4985       *
4986       * @param \core\output\checkbox_toggleall $element
4987       * @return string
4988       */
4989      public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
4990          return $this->render_from_template($element->get_template(), $element->export_for_template($this));
4991      }
4992  
4993      /**
4994       * Renders the tertiary nav for the participants page
4995       *
4996       * @param object $course The course we are operating within
4997       * @param string|null $renderedbuttons Any additional buttons/content to be displayed in line with the nav
4998       * @return string
4999       */
5000      public function render_participants_tertiary_nav(object $course, ?string $renderedbuttons = null) {
5001          $actionbar = new \core\output\participants_action_bar($course, $this->page, $renderedbuttons);
5002          $content = $this->render_from_template('core_course/participants_actionbar', $actionbar->export_for_template($this));
5003          return $content ?: "";
5004      }
5005  
5006      /**
5007       * Renders release information in the footer popup
5008       * @return string Moodle release info.
5009       */
5010      public function moodle_release() {
5011          global $CFG;
5012          if (!during_initial_install() && is_siteadmin()) {
5013              return $CFG->release;
5014          }
5015      }
5016  
5017      /**
5018       * Generate the add block button when editing mode is turned on and the user can edit blocks.
5019       *
5020       * @param string $region where new blocks should be added.
5021       * @return string html for the add block button.
5022       */
5023      public function addblockbutton($region = ''): string {
5024          $addblockbutton = '';
5025          $regions = $this->page->blocks->get_regions();
5026          if (count($regions) == 0) {
5027              return '';
5028          }
5029          if (isset($this->page->theme->addblockposition) &&
5030                  $this->page->user_is_editing() &&
5031                  $this->page->user_can_edit_blocks() &&
5032                  $this->page->pagelayout !== 'mycourses'
5033          ) {
5034              $params = ['bui_addblock' => '', 'sesskey' => sesskey()];
5035              if (!empty($region)) {
5036                  $params['bui_blockregion'] = $region;
5037              }
5038              $url = new moodle_url($this->page->url, $params);
5039              $addblockbutton = $this->render_from_template('core/add_block_button',
5040                  [
5041                      'link' => $url->out(false),
5042                      'escapedlink' => "?{$url->get_query_string(false)}",
5043                      'pageType' => $this->page->pagetype,
5044                      'pageLayout' => $this->page->pagelayout,
5045                      'subPage' => $this->page->subpage,
5046                  ]
5047              );
5048          }
5049          return $addblockbutton;
5050      }
5051  }
5052  
5053  /**
5054   * A renderer that generates output for command-line scripts.
5055   *
5056   * The implementation of this renderer is probably incomplete.
5057   *
5058   * @copyright 2009 Tim Hunt
5059   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5060   * @since Moodle 2.0
5061   * @package core
5062   * @category output
5063   */
5064  class core_renderer_cli extends core_renderer {
5065  
5066      /**
5067       * @var array $progressmaximums stores the largest percentage for a progress bar.
5068       * @return string ascii fragment
5069       */
5070      private $progressmaximums = [];
5071  
5072      /**
5073       * Returns the page header.
5074       *
5075       * @return string HTML fragment
5076       */
5077      public function header() {
5078          return $this->page->heading . "\n";
5079      }
5080  
5081      /**
5082       * Renders a Check API result
5083       *
5084       * To aid in CLI consistency this status is NOT translated and the visual
5085       * width is always exactly 10 chars.
5086       *
5087       * @param core\check\result $result
5088       * @return string HTML fragment
5089       */
5090      protected function render_check_result(core\check\result $result) {
5091          $status = $result->get_status();
5092  
5093          $labels = [
5094              core\check\result::NA        => '      ' . cli_ansi_format('<colour:darkGray>' ) . ' NA ',
5095              core\check\result::OK        => '      ' . cli_ansi_format('<colour:green>') . ' OK ',
5096              core\check\result::INFO      => '    '   . cli_ansi_format('<colour:blue>' ) . ' INFO ',
5097              core\check\result::UNKNOWN   => ' '      . cli_ansi_format('<colour:darkGray>' ) . ' UNKNOWN ',
5098              core\check\result::WARNING   => ' '      . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
5099              core\check\result::ERROR     => '   '    . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
5100              core\check\result::CRITICAL  => ''       . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
5101          ];
5102          $string = $labels[$status] . cli_ansi_format('<colour:normal>');
5103          return $string;
5104      }
5105  
5106      /**
5107       * Renders a Check API result
5108       *
5109       * @param result $result
5110       * @return string fragment
5111       */
5112      public function check_result(core\check\result $result) {
5113          return $this->render_check_result($result);
5114      }
5115  
5116      /**
5117       * Renders a progress bar.
5118       *
5119       * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5120       *
5121       * @param  progress_bar $bar The bar.
5122       * @return string ascii fragment
5123       */
5124      public function render_progress_bar(progress_bar $bar) {
5125          global $CFG;
5126  
5127          $size = 55; // The width of the progress bar in chars.
5128          $ascii = "\n";
5129  
5130          if (stream_isatty(STDOUT)) {
5131              require_once($CFG->libdir.'/clilib.php');
5132  
5133              $ascii .= "[" . str_repeat(' ', $size) . "] 0% \n";
5134              return cli_ansi_format($ascii);
5135          }
5136  
5137          $this->progressmaximums[$bar->get_id()] = 0;
5138          $ascii .= '[';
5139          return $ascii;
5140      }
5141  
5142      /**
5143       * Renders an update to a progress bar.
5144       *
5145       * Note: This does not cleanly map to a renderable class and should
5146       * never be used directly.
5147       *
5148       * @param  string $id
5149       * @param  float $percent
5150       * @param  string $msg Message
5151       * @param  string $estimate time remaining message
5152       * @return string ascii fragment
5153       */
5154      public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
5155          $size = 55; // The width of the progress bar in chars.
5156          $ascii = '';
5157  
5158          // If we are rendering to a terminal then we can safely use ansii codes
5159          // to move the cursor and redraw the complete progress bar each time
5160          // it is updated.
5161          if (stream_isatty(STDOUT)) {
5162              $colour = $percent == 100 ? 'green' : 'blue';
5163  
5164              $done = $percent * $size * 0.01;
5165              $whole = floor($done);
5166              $bar = "<colour:$colour>";
5167              $bar .= str_repeat('█', $whole);
5168  
5169              if ($whole < $size) {
5170                  // By using unicode chars for partial blocks we can have higher
5171                  // precision progress bar.
5172                  $fraction = floor(($done - $whole) * 8);
5173                  $bar .= core_text::substr(' ▏▎▍▌▋▊▉', $fraction, 1);
5174  
5175                  // Fill the rest of the empty bar.
5176                  $bar .= str_repeat(' ', $size - $whole - 1);
5177              }
5178  
5179              $bar .= '<colour:normal>';
5180  
5181              if ($estimate) {
5182                  $estimate = "- $estimate";
5183              }
5184  
5185              $ascii .= '<cursor:up>';
5186              $ascii .= '<cursor:up>';
5187              $ascii .= sprintf("[$bar] %3.1f%% %-22s\n", $percent, $estimate);
5188              $ascii .= sprintf("%-80s\n", $msg);
5189              return cli_ansi_format($ascii);
5190          }
5191  
5192          // If we are not rendering to a tty, ie when piped to another command
5193          // or on windows we need to progressively render the progress bar
5194          // which can only ever go forwards.
5195          $done = round($percent * $size * 0.01);
5196          $delta = max(0, $done - $this->progressmaximums[$id]);
5197  
5198          $ascii .= str_repeat('#', $delta);
5199          if ($percent >= 100 && $delta > 0) {
5200              $ascii .= sprintf("] %3.1f%%\n$msg\n", $percent);
5201          }
5202          $this->progressmaximums[$id] += $delta;
5203          return $ascii;
5204      }
5205  
5206      /**
5207       * Returns a template fragment representing a Heading.
5208       *
5209       * @param string $text The text of the heading
5210       * @param int $level The level of importance of the heading
5211       * @param string $classes A space-separated list of CSS classes
5212       * @param string $id An optional ID
5213       * @return string A template fragment for a heading
5214       */
5215      public function heading($text, $level = 2, $classes = 'main', $id = null) {
5216          $text .= "\n";
5217          switch ($level) {
5218              case 1:
5219                  return '=>' . $text;
5220              case 2:
5221                  return '-->' . $text;
5222              default:
5223                  return $text;
5224          }
5225      }
5226  
5227      /**
5228       * Returns a template fragment representing a fatal error.
5229       *
5230       * @param string $message The message to output
5231       * @param string $moreinfourl URL where more info can be found about the error
5232       * @param string $link Link for the Continue button
5233       * @param array $backtrace The execution backtrace
5234       * @param string $debuginfo Debugging information
5235       * @return string A template fragment for a fatal error
5236       */
5237      public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5238          global $CFG;
5239  
5240          $output = "!!! $message !!!\n";
5241  
5242          if ($CFG->debugdeveloper) {
5243              if (!empty($debuginfo)) {
5244                  $output .= $this->notification($debuginfo, 'notifytiny');
5245              }
5246              if (!empty($backtrace)) {
5247                  $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
5248              }
5249          }
5250  
5251          return $output;
5252      }
5253  
5254      /**
5255       * Returns a template fragment representing a notification.
5256       *
5257       * @param string $message The message to print out.
5258       * @param string $type    The type of notification. See constants on \core\output\notification.
5259       * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5260       * @return string A template fragment for a notification
5261       */
5262      public function notification($message, $type = null, $closebutton = true) {
5263          $message = clean_text($message);
5264          if ($type === 'notifysuccess' || $type === 'success') {
5265              return "++ $message ++\n";
5266          }
5267          return "!! $message !!\n";
5268      }
5269  
5270      /**
5271       * There is no footer for a cli request, however we must override the
5272       * footer method to prevent the default footer.
5273       */
5274      public function footer() {}
5275  
5276      /**
5277       * Render a notification (that is, a status message about something that has
5278       * just happened).
5279       *
5280       * @param \core\output\notification $notification the notification to print out
5281       * @return string plain text output
5282       */
5283      public function render_notification(\core\output\notification $notification) {
5284          return $this->notification($notification->get_message(), $notification->get_message_type());
5285      }
5286  }
5287  
5288  
5289  /**
5290   * A renderer that generates output for ajax scripts.
5291   *
5292   * This renderer prevents accidental sends back only json
5293   * encoded error messages, all other output is ignored.
5294   *
5295   * @copyright 2010 Petr Skoda
5296   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5297   * @since Moodle 2.0
5298   * @package core
5299   * @category output
5300   */
5301  class core_renderer_ajax extends core_renderer {
5302  
5303      /**
5304       * Returns a template fragment representing a fatal error.
5305       *
5306       * @param string $message The message to output
5307       * @param string $moreinfourl URL where more info can be found about the error
5308       * @param string $link Link for the Continue button
5309       * @param array $backtrace The execution backtrace
5310       * @param string $debuginfo Debugging information
5311       * @return string A template fragment for a fatal error
5312       */
5313      public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5314          global $CFG;
5315  
5316          $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
5317  
5318          $e = new stdClass();
5319          $e->error      = $message;
5320          $e->errorcode  = $errorcode;
5321          $e->stacktrace = NULL;
5322          $e->debuginfo  = NULL;
5323          $e->reproductionlink = NULL;
5324          if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
5325              $link = (string) $link;
5326              if ($link) {
5327                  $e->reproductionlink = $link;
5328              }
5329              if (!empty($debuginfo)) {
5330                  $e->debuginfo = $debuginfo;
5331              }
5332              if (!empty($backtrace)) {
5333                  $e->stacktrace = format_backtrace($backtrace, true);
5334              }
5335          }
5336          $this->header();
5337          return json_encode($e);
5338      }
5339  
5340      /**
5341       * Used to display a notification.
5342       * For the AJAX notifications are discarded.
5343       *
5344       * @param string $message The message to print out.
5345       * @param string $type    The type of notification. See constants on \core\output\notification.
5346       * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5347       */
5348      public function notification($message, $type = null, $closebutton = true) {
5349      }
5350  
5351      /**
5352       * Used to display a redirection message.
5353       * AJAX redirections should not occur and as such redirection messages
5354       * are discarded.
5355       *
5356       * @param moodle_url|string $encodedurl
5357       * @param string $message
5358       * @param int $delay
5359       * @param bool $debugdisableredirect
5360       * @param string $messagetype The type of notification to show the message in.
5361       *         See constants on \core\output\notification.
5362       */
5363      public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5364                                       $messagetype = \core\output\notification::NOTIFY_INFO) {}
5365  
5366      /**
5367       * Prepares the start of an AJAX output.
5368       */
5369      public function header() {
5370          // unfortunately YUI iframe upload does not support application/json
5371          if (!empty($_FILES)) {
5372              @header('Content-type: text/plain; charset=utf-8');
5373              if (!core_useragent::supports_json_contenttype()) {
5374                  @header('X-Content-Type-Options: nosniff');
5375              }
5376          } else if (!core_useragent::supports_json_contenttype()) {
5377              @header('Content-type: text/plain; charset=utf-8');
5378              @header('X-Content-Type-Options: nosniff');
5379          } else {
5380              @header('Content-type: application/json; charset=utf-8');
5381          }
5382  
5383          // Headers to make it not cacheable and json
5384          @header('Cache-Control: no-store, no-cache, must-revalidate');
5385          @header('Cache-Control: post-check=0, pre-check=0', false);
5386          @header('Pragma: no-cache');
5387          @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5388          @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5389          @header('Accept-Ranges: none');
5390      }
5391  
5392      /**
5393       * There is no footer for an AJAX request, however we must override the
5394       * footer method to prevent the default footer.
5395       */
5396      public function footer() {}
5397  
5398      /**
5399       * No need for headers in an AJAX request... this should never happen.
5400       * @param string $text
5401       * @param int $level
5402       * @param string $classes
5403       * @param string $id
5404       */
5405      public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5406  }
5407  
5408  
5409  
5410  /**
5411   * The maintenance renderer.
5412   *
5413   * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5414   * is running a maintenance related task.
5415   * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5416   *
5417   * @since Moodle 2.6
5418   * @package core
5419   * @category output
5420   * @copyright 2013 Sam Hemelryk
5421   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5422   */
5423  class core_renderer_maintenance extends core_renderer {
5424  
5425      /**
5426       * Initialises the renderer instance.
5427       *
5428       * @param moodle_page $page
5429       * @param string $target
5430       * @throws coding_exception
5431       */
5432      public function __construct(moodle_page $page, $target) {
5433          if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5434              throw new coding_exception('Invalid request for the maintenance renderer.');
5435          }
5436          parent::__construct($page, $target);
5437      }
5438  
5439      /**
5440       * Does nothing. The maintenance renderer cannot produce blocks.
5441       *
5442       * @param block_contents $bc
5443       * @param string $region
5444       * @return string
5445       */
5446      public function block(block_contents $bc, $region) {
5447          return '';
5448      }
5449  
5450      /**
5451       * Does nothing. The maintenance renderer cannot produce blocks.
5452       *
5453       * @param string $region
5454       * @param array $classes
5455       * @param string $tag
5456       * @param boolean $fakeblocksonly
5457       * @return string
5458       */
5459      public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
5460          return '';
5461      }
5462  
5463      /**
5464       * Does nothing. The maintenance renderer cannot produce blocks.
5465       *
5466       * @param string $region
5467       * @param boolean $fakeblocksonly Output fake block only.
5468       * @return string
5469       */
5470      public function blocks_for_region($region, $fakeblocksonly = false) {
5471          return '';
5472      }
5473  
5474      /**
5475       * Does nothing. The maintenance renderer cannot produce a course content header.
5476       *
5477       * @param bool $onlyifnotcalledbefore
5478       * @return string
5479       */
5480      public function course_content_header($onlyifnotcalledbefore = false) {
5481          return '';
5482      }
5483  
5484      /**
5485       * Does nothing. The maintenance renderer cannot produce a course content footer.
5486       *
5487       * @param bool $onlyifnotcalledbefore
5488       * @return string
5489       */
5490      public function course_content_footer($onlyifnotcalledbefore = false) {
5491          return '';
5492      }
5493  
5494      /**
5495       * Does nothing. The maintenance renderer cannot produce a course header.
5496       *
5497       * @return string
5498       */
5499      public function course_header() {
5500          return '';
5501      }
5502  
5503      /**
5504       * Does nothing. The maintenance renderer cannot produce a course footer.
5505       *
5506       * @return string
5507       */
5508      public function course_footer() {
5509          return '';
5510      }
5511  
5512      /**
5513       * Does nothing. The maintenance renderer cannot produce a custom menu.
5514       *
5515       * @param string $custommenuitems
5516       * @return string
5517       */
5518      public function custom_menu($custommenuitems = '') {
5519          return '';
5520      }
5521  
5522      /**
5523       * Does nothing. The maintenance renderer cannot produce a file picker.
5524       *
5525       * @param array $options
5526       * @return string
5527       */
5528      public function file_picker($options) {
5529          return '';
5530      }
5531  
5532      /**
5533       * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5534       *
5535       * @param array $dir
5536       * @return string
5537       */
5538      public function htmllize_file_tree($dir) {
5539          return '';
5540  
5541      }
5542  
5543      /**
5544       * Overridden confirm message for upgrades.
5545       *
5546       * @param string $message The question to ask the user
5547       * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5548       * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5549       * @param array $displayoptions optional extra display options
5550       * @return string HTML fragment
5551       */
5552      public function confirm($message, $continue, $cancel, array $displayoptions = []) {
5553          // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5554          // from any previous version of Moodle).
5555          if ($continue instanceof single_button) {
5556              $continue->primary = true;
5557          } else if (is_string($continue)) {
5558              $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post', true);
5559          } else if ($continue instanceof moodle_url) {
5560              $continue = new single_button($continue, get_string('continue'), 'post', true);
5561          } else {
5562              throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5563                                         ' (string/moodle_url) or a single_button instance.');
5564          }
5565  
5566          if ($cancel instanceof single_button) {
5567              $output = '';
5568          } else if (is_string($cancel)) {
5569              $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5570          } else if ($cancel instanceof moodle_url) {
5571              $cancel = new single_button($cancel, get_string('cancel'), 'get');
5572          } else {
5573              throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5574                                         ' (string/moodle_url) or a single_button instance.');
5575          }
5576  
5577          $output = $this->box_start('generalbox', 'notice');
5578          $output .= html_writer::tag('h4', get_string('confirm'));
5579          $output .= html_writer::tag('p', $message);
5580          $output .= html_writer::tag('div', $this->render($continue) . $this->render($cancel), array('class' => 'buttons'));
5581          $output .= $this->box_end();
5582          return $output;
5583      }
5584  
5585      /**
5586       * Does nothing. The maintenance renderer does not support JS.
5587       *
5588       * @param block_contents $bc
5589       */
5590      public function init_block_hider_js(block_contents $bc) {
5591          // Does nothing.
5592      }
5593  
5594      /**
5595       * Does nothing. The maintenance renderer cannot produce language menus.
5596       *
5597       * @return string
5598       */
5599      public function lang_menu() {
5600          return '';
5601      }
5602  
5603      /**
5604       * Does nothing. The maintenance renderer has no need for login information.
5605       *
5606       * @param null $withlinks
5607       * @return string
5608       */
5609      public function login_info($withlinks = null) {
5610          return '';
5611      }
5612  
5613      /**
5614       * Secure login info.
5615       *
5616       * @return string
5617       */
5618      public function secure_login_info() {
5619          return $this->login_info(false);
5620      }
5621  
5622      /**
5623       * Does nothing. The maintenance renderer cannot produce user pictures.
5624       *
5625       * @param stdClass $user
5626       * @param array $options
5627       * @return string
5628       */
5629      public function user_picture(stdClass $user, array $options = null) {
5630          return '';
5631      }
5632  }