Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402] [Versions 400 and 402] [Versions 401 and 402] [Versions 402 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)(floor($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 pattern image URL.
1680       *
1681       * @param context_course $context course context object
1682       * @return string URL of the course pattern image in SVG format
1683       */
1684      public function get_generated_url_for_course(context_course $context): string {
1685          return moodle_url::make_pluginfile_url($context->id, 'course', 'generated', null, '/', 'course.svg')->out();
1686      }
1687  
1688      /**
1689       * Get the course pattern in SVG format to show on a course card.
1690       *
1691       * @param int $id id to use when generating the pattern
1692       * @return string SVG file contents
1693       */
1694      public function get_generated_svg_for_id(int $id): string {
1695          $color = $this->get_generated_color_for_id($id);
1696          $pattern = new \core_geopattern();
1697          $pattern->setColor($color);
1698          $pattern->patternbyid($id);
1699          return $pattern->toSVG();
1700      }
1701  
1702      /**
1703       * Get the course color to show on a course card.
1704       *
1705       * @param int $id Id to use when generating the color.
1706       * @return string hex color code.
1707       */
1708      public function get_generated_color_for_id($id) {
1709          $colornumbers = range(1, 10);
1710          $basecolors = [];
1711          foreach ($colornumbers as $number) {
1712              $basecolors[] = get_config('core_admin', 'coursecolor' . $number);
1713          }
1714  
1715          $color = $basecolors[$id % 10];
1716          return $color;
1717      }
1718  
1719      /**
1720       * Returns lang menu or '', this method also checks forcing of languages in courses.
1721       *
1722       * This function calls {@link core_renderer::render_single_select()} to actually display the language menu.
1723       *
1724       * @return string The lang menu HTML or empty string
1725       */
1726      public function lang_menu() {
1727          $languagemenu = new \core\output\language_menu($this->page);
1728          $data = $languagemenu->export_for_single_select($this);
1729          if ($data) {
1730              return $this->render_from_template('core/single_select', $data);
1731          }
1732          return '';
1733      }
1734  
1735      /**
1736       * Output the row of editing icons for a block, as defined by the controls array.
1737       *
1738       * @param array $controls an array like {@link block_contents::$controls}.
1739       * @param string $blockid The ID given to the block.
1740       * @return string HTML fragment.
1741       */
1742      public function block_controls($actions, $blockid = null) {
1743          global $CFG;
1744          if (empty($actions)) {
1745              return '';
1746          }
1747          $menu = new action_menu($actions);
1748          if ($blockid !== null) {
1749              $menu->set_owner_selector('#'.$blockid);
1750          }
1751          $menu->set_constraint('.block-region');
1752          $menu->attributes['class'] .= ' block-control-actions commands';
1753          return $this->render($menu);
1754      }
1755  
1756      /**
1757       * Returns the HTML for a basic textarea field.
1758       *
1759       * @param string $name Name to use for the textarea element
1760       * @param string $id The id to use fort he textarea element
1761       * @param string $value Initial content to display in the textarea
1762       * @param int $rows Number of rows to display
1763       * @param int $cols Number of columns to display
1764       * @return string the HTML to display
1765       */
1766      public function print_textarea($name, $id, $value, $rows, $cols) {
1767          editors_head_setup();
1768          $editor = editors_get_preferred_editor(FORMAT_HTML);
1769          $editor->set_text($value);
1770          $editor->use_editor($id, []);
1771  
1772          $context = [
1773              'id' => $id,
1774              'name' => $name,
1775              'value' => $value,
1776              'rows' => $rows,
1777              'cols' => $cols
1778          ];
1779  
1780          return $this->render_from_template('core_form/editor_textarea', $context);
1781      }
1782  
1783      /**
1784       * Renders an action menu component.
1785       *
1786       * @param action_menu $menu
1787       * @return string HTML
1788       */
1789      public function render_action_menu(action_menu $menu) {
1790  
1791          // We don't want the class icon there!
1792          foreach ($menu->get_secondary_actions() as $action) {
1793              if ($action instanceof \action_menu_link && $action->has_class('icon')) {
1794                  $action->attributes['class'] = preg_replace('/(^|\s+)icon(\s+|$)/i', '', $action->attributes['class']);
1795              }
1796          }
1797  
1798          if ($menu->is_empty()) {
1799              return '';
1800          }
1801          $context = $menu->export_for_template($this);
1802  
1803          return $this->render_from_template('core/action_menu', $context);
1804      }
1805  
1806      /**
1807       * Renders a Check API result
1808       *
1809       * @param core\check\result $result
1810       * @return string HTML fragment
1811       */
1812      protected function render_check_result(core\check\result $result) {
1813          return $this->render_from_template($result->get_template_name(), $result->export_for_template($this));
1814      }
1815  
1816      /**
1817       * Renders a Check API result
1818       *
1819       * @param core\check\result $result
1820       * @return string HTML fragment
1821       */
1822      public function check_result(core\check\result $result) {
1823          return $this->render_check_result($result);
1824      }
1825  
1826      /**
1827       * Renders an action_menu_link item.
1828       *
1829       * @param action_menu_link $action
1830       * @return string HTML fragment
1831       */
1832      protected function render_action_menu_link(action_menu_link $action) {
1833          return $this->render_from_template('core/action_menu_link', $action->export_for_template($this));
1834      }
1835  
1836      /**
1837       * Renders a primary action_menu_filler item.
1838       *
1839       * @param action_menu_link_filler $action
1840       * @return string HTML fragment
1841       */
1842      protected function render_action_menu_filler(action_menu_filler $action) {
1843          return html_writer::span('&nbsp;', 'filler');
1844      }
1845  
1846      /**
1847       * Renders a primary action_menu_link item.
1848       *
1849       * @param action_menu_link_primary $action
1850       * @return string HTML fragment
1851       */
1852      protected function render_action_menu_link_primary(action_menu_link_primary $action) {
1853          return $this->render_action_menu_link($action);
1854      }
1855  
1856      /**
1857       * Renders a secondary action_menu_link item.
1858       *
1859       * @param action_menu_link_secondary $action
1860       * @return string HTML fragment
1861       */
1862      protected function render_action_menu_link_secondary(action_menu_link_secondary $action) {
1863          return $this->render_action_menu_link($action);
1864      }
1865  
1866      /**
1867       * Prints a nice side block with an optional header.
1868       *
1869       * @param block_contents $bc HTML for the content
1870       * @param string $region the region the block is appearing in.
1871       * @return string the HTML to be output.
1872       */
1873      public function block(block_contents $bc, $region) {
1874          $bc = clone($bc); // Avoid messing up the object passed in.
1875          if (empty($bc->blockinstanceid) || !strip_tags($bc->title)) {
1876              $bc->collapsible = block_contents::NOT_HIDEABLE;
1877          }
1878  
1879          $id = !empty($bc->attributes['id']) ? $bc->attributes['id'] : uniqid('block-');
1880          $context = new stdClass();
1881          $context->skipid = $bc->skipid;
1882          $context->blockinstanceid = $bc->blockinstanceid ?: uniqid('fakeid-');
1883          $context->dockable = $bc->dockable;
1884          $context->id = $id;
1885          $context->hidden = $bc->collapsible == block_contents::HIDDEN;
1886          $context->skiptitle = strip_tags($bc->title);
1887          $context->showskiplink = !empty($context->skiptitle);
1888          $context->arialabel = $bc->arialabel;
1889          $context->ariarole = !empty($bc->attributes['role']) ? $bc->attributes['role'] : 'complementary';
1890          $context->class = $bc->attributes['class'];
1891          $context->type = $bc->attributes['data-block'];
1892          $context->title = $bc->title;
1893          $context->content = $bc->content;
1894          $context->annotation = $bc->annotation;
1895          $context->footer = $bc->footer;
1896          $context->hascontrols = !empty($bc->controls);
1897          if ($context->hascontrols) {
1898              $context->controls = $this->block_controls($bc->controls, $id);
1899          }
1900  
1901          return $this->render_from_template('core/block', $context);
1902      }
1903  
1904      /**
1905       * Render the contents of a block_list.
1906       *
1907       * @param array $icons the icon for each item.
1908       * @param array $items the content of each item.
1909       * @return string HTML
1910       */
1911      public function list_block_contents($icons, $items) {
1912          $row = 0;
1913          $lis = array();
1914          foreach ($items as $key => $string) {
1915              $item = html_writer::start_tag('li', array('class' => 'r' . $row));
1916              if (!empty($icons[$key])) { //test if the content has an assigned icon
1917                  $item .= html_writer::tag('div', $icons[$key], array('class' => 'icon column c0'));
1918              }
1919              $item .= html_writer::tag('div', $string, array('class' => 'column c1'));
1920              $item .= html_writer::end_tag('li');
1921              $lis[] = $item;
1922              $row = 1 - $row; // Flip even/odd.
1923          }
1924          return html_writer::tag('ul', implode("\n", $lis), array('class' => 'unlist'));
1925      }
1926  
1927      /**
1928       * Output all the blocks in a particular region.
1929       *
1930       * @param string $region the name of a region on this page.
1931       * @param boolean $fakeblocksonly Output fake block only.
1932       * @return string the HTML to be output.
1933       */
1934      public function blocks_for_region($region, $fakeblocksonly = false) {
1935          $blockcontents = $this->page->blocks->get_content_for_region($region, $this);
1936          $lastblock = null;
1937          $zones = array();
1938          foreach ($blockcontents as $bc) {
1939              if ($bc instanceof block_contents) {
1940                  $zones[] = $bc->title;
1941              }
1942          }
1943          $output = '';
1944  
1945          foreach ($blockcontents as $bc) {
1946              if ($bc instanceof block_contents) {
1947                  if ($fakeblocksonly && !$bc->is_fake()) {
1948                      // Skip rendering real blocks if we only want to show fake blocks.
1949                      continue;
1950                  }
1951                  $output .= $this->block($bc, $region);
1952                  $lastblock = $bc->title;
1953              } else if ($bc instanceof block_move_target) {
1954                  if (!$fakeblocksonly) {
1955                      $output .= $this->block_move_target($bc, $zones, $lastblock, $region);
1956                  }
1957              } else {
1958                  throw new coding_exception('Unexpected type of thing (' . get_class($bc) . ') found in list of block contents.');
1959              }
1960          }
1961          return $output;
1962      }
1963  
1964      /**
1965       * Output a place where the block that is currently being moved can be dropped.
1966       *
1967       * @param block_move_target $target with the necessary details.
1968       * @param array $zones array of areas where the block can be moved to
1969       * @param string $previous the block located before the area currently being rendered.
1970       * @param string $region the name of the region
1971       * @return string the HTML to be output.
1972       */
1973      public function block_move_target($target, $zones, $previous, $region) {
1974          if ($previous == null) {
1975              if (empty($zones)) {
1976                  // There are no zones, probably because there are no blocks.
1977                  $regions = $this->page->theme->get_all_block_regions();
1978                  $position = get_string('moveblockinregion', 'block', $regions[$region]);
1979              } else {
1980                  $position = get_string('moveblockbefore', 'block', $zones[0]);
1981              }
1982          } else {
1983              $position = get_string('moveblockafter', 'block', $previous);
1984          }
1985          return html_writer::tag('a', html_writer::tag('span', $position, array('class' => 'accesshide')), array('href' => $target->url, 'class' => 'blockmovetarget'));
1986      }
1987  
1988      /**
1989       * Renders a special html link with attached action
1990       *
1991       * Theme developers: DO NOT OVERRIDE! Please override function
1992       * {@link core_renderer::render_action_link()} instead.
1993       *
1994       * @param string|moodle_url $url
1995       * @param string $text HTML fragment
1996       * @param component_action $action
1997       * @param array $attributes associative array of html link attributes + disabled
1998       * @param pix_icon optional pix icon to render with the link
1999       * @return string HTML fragment
2000       */
2001      public function action_link($url, $text, component_action $action = null, array $attributes = null, $icon = null) {
2002          if (!($url instanceof moodle_url)) {
2003              $url = new moodle_url($url);
2004          }
2005          $link = new action_link($url, $text, $action, $attributes, $icon);
2006  
2007          return $this->render($link);
2008      }
2009  
2010      /**
2011       * Renders an action_link object.
2012       *
2013       * The provided link is renderer and the HTML returned. At the same time the
2014       * associated actions are setup in JS by {@link core_renderer::add_action_handler()}
2015       *
2016       * @param action_link $link
2017       * @return string HTML fragment
2018       */
2019      protected function render_action_link(action_link $link) {
2020          return $this->render_from_template('core/action_link', $link->export_for_template($this));
2021      }
2022  
2023      /**
2024       * Renders an action_icon.
2025       *
2026       * This function uses the {@link core_renderer::action_link()} method for the
2027       * most part. What it does different is prepare the icon as HTML and use it
2028       * as the link text.
2029       *
2030       * Theme developers: If you want to change how action links and/or icons are rendered,
2031       * consider overriding function {@link core_renderer::render_action_link()} and
2032       * {@link core_renderer::render_pix_icon()}.
2033       *
2034       * @param string|moodle_url $url A string URL or moodel_url
2035       * @param pix_icon $pixicon
2036       * @param component_action $action
2037       * @param array $attributes associative array of html link attributes + disabled
2038       * @param bool $linktext show title next to image in link
2039       * @return string HTML fragment
2040       */
2041      public function action_icon($url, pix_icon $pixicon, component_action $action = null, array $attributes = null, $linktext=false) {
2042          if (!($url instanceof moodle_url)) {
2043              $url = new moodle_url($url);
2044          }
2045          $attributes = (array)$attributes;
2046  
2047          if (empty($attributes['class'])) {
2048              // let ppl override the class via $options
2049              $attributes['class'] = 'action-icon';
2050          }
2051  
2052          $icon = $this->render($pixicon);
2053  
2054          if ($linktext) {
2055              $text = $pixicon->attributes['alt'];
2056          } else {
2057              $text = '';
2058          }
2059  
2060          return $this->action_link($url, $text.$icon, $action, $attributes);
2061      }
2062  
2063     /**
2064      * Print a message along with button choices for Continue/Cancel
2065      *
2066      * If a string or moodle_url is given instead of a single_button, method defaults to post.
2067      *
2068      * @param string $message The question to ask the user
2069      * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer. Can also be a moodle_url or string URL
2070      * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer. Can also be a moodle_url or string URL
2071      * @param array $displayoptions optional extra display options
2072      * @return string HTML fragment
2073      */
2074      public function confirm($message, $continue, $cancel, array $displayoptions = []) {
2075  
2076          // Check existing displayoptions.
2077          $displayoptions['confirmtitle'] = $displayoptions['confirmtitle'] ?? get_string('confirm');
2078          $displayoptions['continuestr'] = $displayoptions['continuestr'] ?? get_string('continue');
2079          $displayoptions['cancelstr'] = $displayoptions['cancelstr'] ?? get_string('cancel');
2080  
2081          if ($continue instanceof single_button) {
2082              // Continue button should be primary if set to secondary type as it is the fefault.
2083              if ($continue->type === single_button::BUTTON_SECONDARY) {
2084                  $continue->type = single_button::BUTTON_PRIMARY;
2085              }
2086          } else if (is_string($continue)) {
2087              $continue = new single_button(new moodle_url($continue), $displayoptions['continuestr'], 'post',
2088                  $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
2089          } else if ($continue instanceof moodle_url) {
2090              $continue = new single_button($continue, $displayoptions['continuestr'], 'post',
2091                  $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
2092          } else {
2093              throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2094          }
2095  
2096          if ($cancel instanceof single_button) {
2097              // ok
2098          } else if (is_string($cancel)) {
2099              $cancel = new single_button(new moodle_url($cancel), $displayoptions['cancelstr'], 'get');
2100          } else if ($cancel instanceof moodle_url) {
2101              $cancel = new single_button($cancel, $displayoptions['cancelstr'], 'get');
2102          } else {
2103              throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL (string/moodle_url) or a single_button instance.');
2104          }
2105  
2106          $attributes = [
2107              'role'=>'alertdialog',
2108              'aria-labelledby'=>'modal-header',
2109              'aria-describedby'=>'modal-body',
2110              'aria-modal'=>'true'
2111          ];
2112  
2113          $output = $this->box_start('generalbox modal modal-dialog modal-in-page show', 'notice', $attributes);
2114          $output .= $this->box_start('modal-content', 'modal-content');
2115          $output .= $this->box_start('modal-header px-3', 'modal-header');
2116          $output .= html_writer::tag('h4', $displayoptions['confirmtitle']);
2117          $output .= $this->box_end();
2118          $attributes = [
2119              'role'=>'alert',
2120              'data-aria-autofocus'=>'true'
2121          ];
2122          $output .= $this->box_start('modal-body', 'modal-body', $attributes);
2123          $output .= html_writer::tag('p', $message);
2124          $output .= $this->box_end();
2125          $output .= $this->box_start('modal-footer', 'modal-footer');
2126          $output .= html_writer::tag('div', $this->render($cancel) . $this->render($continue), ['class' => 'buttons']);
2127          $output .= $this->box_end();
2128          $output .= $this->box_end();
2129          $output .= $this->box_end();
2130          return $output;
2131      }
2132  
2133      /**
2134       * Returns a form with a single button.
2135       *
2136       * Theme developers: DO NOT OVERRIDE! Please override function
2137       * {@link core_renderer::render_single_button()} instead.
2138       *
2139       * @param string|moodle_url $url
2140       * @param string $label button text
2141       * @param string $method get or post submit method
2142       * @param array $options associative array {disabled, title, etc.}
2143       * @return string HTML fragment
2144       */
2145      public function single_button($url, $label, $method='post', array $options=null) {
2146          if (!($url instanceof moodle_url)) {
2147              $url = new moodle_url($url);
2148          }
2149          $button = new single_button($url, $label, $method);
2150  
2151          foreach ((array)$options as $key=>$value) {
2152              if (property_exists($button, $key)) {
2153                  $button->$key = $value;
2154              } else {
2155                  $button->set_attribute($key, $value);
2156              }
2157          }
2158  
2159          return $this->render($button);
2160      }
2161  
2162      /**
2163       * Renders a single button widget.
2164       *
2165       * This will return HTML to display a form containing a single button.
2166       *
2167       * @param single_button $button
2168       * @return string HTML fragment
2169       */
2170      protected function render_single_button(single_button $button) {
2171          return $this->render_from_template('core/single_button', $button->export_for_template($this));
2172      }
2173  
2174      /**
2175       * Returns a form with a single select widget.
2176       *
2177       * Theme developers: DO NOT OVERRIDE! Please override function
2178       * {@link core_renderer::render_single_select()} instead.
2179       *
2180       * @param moodle_url $url form action target, includes hidden fields
2181       * @param string $name name of selection field - the changing parameter in url
2182       * @param array $options list of options
2183       * @param string $selected selected element
2184       * @param array $nothing
2185       * @param string $formid
2186       * @param array $attributes other attributes for the single select
2187       * @return string HTML fragment
2188       */
2189      public function single_select($url, $name, array $options, $selected = '',
2190                                  $nothing = array('' => 'choosedots'), $formid = null, $attributes = array()) {
2191          if (!($url instanceof moodle_url)) {
2192              $url = new moodle_url($url);
2193          }
2194          $select = new single_select($url, $name, $options, $selected, $nothing, $formid);
2195  
2196          if (array_key_exists('label', $attributes)) {
2197              $select->set_label($attributes['label']);
2198              unset($attributes['label']);
2199          }
2200          $select->attributes = $attributes;
2201  
2202          return $this->render($select);
2203      }
2204  
2205      /**
2206       * Returns a dataformat selection and download form
2207       *
2208       * @param string $label A text label
2209       * @param moodle_url|string $base The download page url
2210       * @param string $name The query param which will hold the type of the download
2211       * @param array $params Extra params sent to the download page
2212       * @return string HTML fragment
2213       */
2214      public function download_dataformat_selector($label, $base, $name = 'dataformat', $params = array()) {
2215  
2216          $formats = core_plugin_manager::instance()->get_plugins_of_type('dataformat');
2217          $options = array();
2218          foreach ($formats as $format) {
2219              if ($format->is_enabled()) {
2220                  $options[] = array(
2221                      'value' => $format->name,
2222                      'label' => get_string('dataformat', $format->component),
2223                  );
2224              }
2225          }
2226          $hiddenparams = array();
2227          foreach ($params as $key => $value) {
2228              $hiddenparams[] = array(
2229                  'name' => $key,
2230                  'value' => $value,
2231              );
2232          }
2233          $data = array(
2234              'label' => $label,
2235              'base' => $base,
2236              'name' => $name,
2237              'params' => $hiddenparams,
2238              'options' => $options,
2239              'sesskey' => sesskey(),
2240              'submit' => get_string('download'),
2241          );
2242  
2243          return $this->render_from_template('core/dataformat_selector', $data);
2244      }
2245  
2246  
2247      /**
2248       * Internal implementation of single_select rendering
2249       *
2250       * @param single_select $select
2251       * @return string HTML fragment
2252       */
2253      protected function render_single_select(single_select $select) {
2254          return $this->render_from_template('core/single_select', $select->export_for_template($this));
2255      }
2256  
2257      /**
2258       * Returns a form with a url select widget.
2259       *
2260       * Theme developers: DO NOT OVERRIDE! Please override function
2261       * {@link core_renderer::render_url_select()} instead.
2262       *
2263       * @param array $urls list of urls - array('/course/view.php?id=1'=>'Frontpage', ....)
2264       * @param string $selected selected element
2265       * @param array $nothing
2266       * @param string $formid
2267       * @return string HTML fragment
2268       */
2269      public function url_select(array $urls, $selected, $nothing = array('' => 'choosedots'), $formid = null) {
2270          $select = new url_select($urls, $selected, $nothing, $formid);
2271          return $this->render($select);
2272      }
2273  
2274      /**
2275       * Internal implementation of url_select rendering
2276       *
2277       * @param url_select $select
2278       * @return string HTML fragment
2279       */
2280      protected function render_url_select(url_select $select) {
2281          return $this->render_from_template('core/url_select', $select->export_for_template($this));
2282      }
2283  
2284      /**
2285       * Returns a string containing a link to the user documentation.
2286       * Also contains an icon by default. Shown to teachers and admin only.
2287       *
2288       * @param string $path The page link after doc root and language, no leading slash.
2289       * @param string $text The text to be displayed for the link
2290       * @param boolean $forcepopup Whether to force a popup regardless of the value of $CFG->doctonewwindow
2291       * @param array $attributes htm attributes
2292       * @return string
2293       */
2294      public function doc_link($path, $text = '', $forcepopup = false, array $attributes = []) {
2295          global $CFG;
2296  
2297          $icon = $this->pix_icon('book', '', 'moodle', array('class' => 'iconhelp icon-pre', 'role' => 'presentation'));
2298  
2299          $attributes['href'] = new moodle_url(get_docs_url($path));
2300          $newwindowicon = '';
2301          if (!empty($CFG->doctonewwindow) || $forcepopup) {
2302              $attributes['target'] = '_blank';
2303              $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle',
2304              ['class' => 'fa fa-externallink fa-fw']);
2305          }
2306  
2307          return html_writer::tag('a', $icon . $text . $newwindowicon, $attributes);
2308      }
2309  
2310      /**
2311       * Return HTML for an image_icon.
2312       *
2313       * Theme developers: DO NOT OVERRIDE! Please override function
2314       * {@link core_renderer::render_image_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 attributes
2320       * @return string HTML fragment
2321       */
2322      public function image_icon($pix, $alt, $component='moodle', array $attributes = null) {
2323          $icon = new image_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 image_icon $icon
2331       * @return string HTML fragment
2332       */
2333      protected function render_image_icon(image_icon $icon) {
2334          $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2335          return $system->render_pix_icon($this, $icon);
2336      }
2337  
2338      /**
2339       * Return HTML for a pix_icon.
2340       *
2341       * Theme developers: DO NOT OVERRIDE! Please override function
2342       * {@link core_renderer::render_pix_icon()} instead.
2343       *
2344       * @param string $pix short pix name
2345       * @param string $alt mandatory alt attribute
2346       * @param string $component standard compoennt name like 'moodle', 'mod_forum', etc.
2347       * @param array $attributes htm lattributes
2348       * @return string HTML fragment
2349       */
2350      public function pix_icon($pix, $alt, $component='moodle', array $attributes = null) {
2351          $icon = new pix_icon($pix, $alt, $component, $attributes);
2352          return $this->render($icon);
2353      }
2354  
2355      /**
2356       * Renders a pix_icon widget and returns the HTML to display it.
2357       *
2358       * @param pix_icon $icon
2359       * @return string HTML fragment
2360       */
2361      protected function render_pix_icon(pix_icon $icon) {
2362          $system = \core\output\icon_system::instance();
2363          return $system->render_pix_icon($this, $icon);
2364      }
2365  
2366      /**
2367       * Return HTML to display an emoticon icon.
2368       *
2369       * @param pix_emoticon $emoticon
2370       * @return string HTML fragment
2371       */
2372      protected function render_pix_emoticon(pix_emoticon $emoticon) {
2373          $system = \core\output\icon_system::instance(\core\output\icon_system::STANDARD);
2374          return $system->render_pix_icon($this, $emoticon);
2375      }
2376  
2377      /**
2378       * Produces the html that represents this rating in the UI
2379       *
2380       * @param rating $rating the page object on which this rating will appear
2381       * @return string
2382       */
2383      function render_rating(rating $rating) {
2384          global $CFG, $USER;
2385  
2386          if ($rating->settings->aggregationmethod == RATING_AGGREGATE_NONE) {
2387              return null;//ratings are turned off
2388          }
2389  
2390          $ratingmanager = new rating_manager();
2391          // Initialise the JavaScript so ratings can be done by AJAX.
2392          $ratingmanager->initialise_rating_javascript($this->page);
2393  
2394          $strrate = get_string("rate", "rating");
2395          $ratinghtml = ''; //the string we'll return
2396  
2397          // permissions check - can they view the aggregate?
2398          if ($rating->user_can_view_aggregate()) {
2399  
2400              $aggregatelabel = $ratingmanager->get_aggregate_label($rating->settings->aggregationmethod);
2401              $aggregatelabel = html_writer::tag('span', $aggregatelabel, array('class'=>'rating-aggregate-label'));
2402              $aggregatestr   = $rating->get_aggregate_string();
2403  
2404              $aggregatehtml  = html_writer::tag('span', $aggregatestr, array('id' => 'ratingaggregate'.$rating->itemid, 'class' => 'ratingaggregate')).' ';
2405              if ($rating->count > 0) {
2406                  $countstr = "({$rating->count})";
2407              } else {
2408                  $countstr = '-';
2409              }
2410              $aggregatehtml .= html_writer::tag('span', $countstr, array('id'=>"ratingcount{$rating->itemid}", 'class' => 'ratingcount')).' ';
2411  
2412              if ($rating->settings->permissions->viewall && $rating->settings->pluginpermissions->viewall) {
2413  
2414                  $nonpopuplink = $rating->get_view_ratings_url();
2415                  $popuplink = $rating->get_view_ratings_url(true);
2416  
2417                  $action = new popup_action('click', $popuplink, 'ratings', array('height' => 400, 'width' => 600));
2418                  $aggregatehtml = $this->action_link($nonpopuplink, $aggregatehtml, $action);
2419              }
2420  
2421              $ratinghtml .= html_writer::tag('span', $aggregatelabel . $aggregatehtml, array('class' => 'rating-aggregate-container'));
2422          }
2423  
2424          $formstart = null;
2425          // if the item doesn't belong to the current user, the user has permission to rate
2426          // and we're within the assessable period
2427          if ($rating->user_can_rate()) {
2428  
2429              $rateurl = $rating->get_rate_url();
2430              $inputs = $rateurl->params();
2431  
2432              //start the rating form
2433              $formattrs = array(
2434                  'id'     => "postrating{$rating->itemid}",
2435                  'class'  => 'postratingform',
2436                  'method' => 'post',
2437                  'action' => $rateurl->out_omit_querystring()
2438              );
2439              $formstart  = html_writer::start_tag('form', $formattrs);
2440              $formstart .= html_writer::start_tag('div', array('class' => 'ratingform'));
2441  
2442              // add the hidden inputs
2443              foreach ($inputs as $name => $value) {
2444                  $attributes = array('type' => 'hidden', 'class' => 'ratinginput', 'name' => $name, 'value' => $value);
2445                  $formstart .= html_writer::empty_tag('input', $attributes);
2446              }
2447  
2448              if (empty($ratinghtml)) {
2449                  $ratinghtml .= $strrate.': ';
2450              }
2451              $ratinghtml = $formstart.$ratinghtml;
2452  
2453              $scalearray = array(RATING_UNSET_RATING => $strrate.'...') + $rating->settings->scale->scaleitems;
2454              $scaleattrs = array('class'=>'postratingmenu ratinginput','id'=>'menurating'.$rating->itemid);
2455              $ratinghtml .= html_writer::label($rating->rating, 'menurating'.$rating->itemid, false, array('class' => 'accesshide'));
2456              $ratinghtml .= html_writer::select($scalearray, 'rating', $rating->rating, false, $scaleattrs);
2457  
2458              //output submit button
2459              $ratinghtml .= html_writer::start_tag('span', array('class'=>"ratingsubmit"));
2460  
2461              $attributes = array('type' => 'submit', 'class' => 'postratingmenusubmit', 'id' => 'postratingsubmit'.$rating->itemid, 'value' => s(get_string('rate', 'rating')));
2462              $ratinghtml .= html_writer::empty_tag('input', $attributes);
2463  
2464              if (!$rating->settings->scale->isnumeric) {
2465                  // If a global scale, try to find current course ID from the context
2466                  if (empty($rating->settings->scale->courseid) and $coursecontext = $rating->context->get_course_context(false)) {
2467                      $courseid = $coursecontext->instanceid;
2468                  } else {
2469                      $courseid = $rating->settings->scale->courseid;
2470                  }
2471                  $ratinghtml .= $this->help_icon_scale($courseid, $rating->settings->scale);
2472              }
2473              $ratinghtml .= html_writer::end_tag('span');
2474              $ratinghtml .= html_writer::end_tag('div');
2475              $ratinghtml .= html_writer::end_tag('form');
2476          }
2477  
2478          return $ratinghtml;
2479      }
2480  
2481      /**
2482       * Centered heading with attached help button (same title text)
2483       * and optional icon attached.
2484       *
2485       * @param string $text A heading text
2486       * @param string $helpidentifier The keyword that defines a help page
2487       * @param string $component component name
2488       * @param string|moodle_url $icon
2489       * @param string $iconalt icon alt text
2490       * @param int $level The level of importance of the heading. Defaulting to 2
2491       * @param string $classnames A space-separated list of CSS classes. Defaulting to null
2492       * @return string HTML fragment
2493       */
2494      public function heading_with_help($text, $helpidentifier, $component = 'moodle', $icon = '', $iconalt = '', $level = 2, $classnames = null) {
2495          $image = '';
2496          if ($icon) {
2497              $image = $this->pix_icon($icon, $iconalt, $component, array('class'=>'icon iconlarge'));
2498          }
2499  
2500          $help = '';
2501          if ($helpidentifier) {
2502              $help = $this->help_icon($helpidentifier, $component);
2503          }
2504  
2505          return $this->heading($image.$text.$help, $level, $classnames);
2506      }
2507  
2508      /**
2509       * Returns HTML to display a help icon.
2510       *
2511       * @deprecated since Moodle 2.0
2512       */
2513      public function old_help_icon($helpidentifier, $title, $component = 'moodle', $linktext = '') {
2514          throw new coding_exception('old_help_icon() can not be used any more, please see help_icon().');
2515      }
2516  
2517      /**
2518       * Returns HTML to display a help icon.
2519       *
2520       * Theme developers: DO NOT OVERRIDE! Please override function
2521       * {@link core_renderer::render_help_icon()} instead.
2522       *
2523       * @param string $identifier The keyword that defines a help page
2524       * @param string $component component name
2525       * @param string|bool $linktext true means use $title as link text, string means link text value
2526       * @return string HTML fragment
2527       */
2528      public function help_icon($identifier, $component = 'moodle', $linktext = '') {
2529          $icon = new help_icon($identifier, $component);
2530          $icon->diag_strings();
2531          if ($linktext === true) {
2532              $icon->linktext = get_string($icon->identifier, $icon->component);
2533          } else if (!empty($linktext)) {
2534              $icon->linktext = $linktext;
2535          }
2536          return $this->render($icon);
2537      }
2538  
2539      /**
2540       * Implementation of user image rendering.
2541       *
2542       * @param help_icon $helpicon A help icon instance
2543       * @return string HTML fragment
2544       */
2545      protected function render_help_icon(help_icon $helpicon) {
2546          $context = $helpicon->export_for_template($this);
2547          return $this->render_from_template('core/help_icon', $context);
2548      }
2549  
2550      /**
2551       * Returns HTML to display a scale help icon.
2552       *
2553       * @param int $courseid
2554       * @param stdClass $scale instance
2555       * @return string HTML fragment
2556       */
2557      public function help_icon_scale($courseid, stdClass $scale) {
2558          global $CFG;
2559  
2560          $title = get_string('helpprefix2', '', $scale->name) .' ('.get_string('newwindow').')';
2561  
2562          $icon = $this->pix_icon('help', get_string('scales'), 'moodle', array('class'=>'iconhelp'));
2563  
2564          $scaleid = abs($scale->id);
2565  
2566          $link = new moodle_url('/course/scales.php', array('id' => $courseid, 'list' => true, 'scaleid' => $scaleid));
2567          $action = new popup_action('click', $link, 'ratingscale');
2568  
2569          return html_writer::tag('span', $this->action_link($link, $icon, $action), array('class' => 'helplink'));
2570      }
2571  
2572      /**
2573       * Creates and returns a spacer image with optional line break.
2574       *
2575       * @param array $attributes Any HTML attributes to add to the spaced.
2576       * @param bool $br Include a BR after the spacer.... DON'T USE THIS. Don't be
2577       *     laxy do it with CSS which is a much better solution.
2578       * @return string HTML fragment
2579       */
2580      public function spacer(array $attributes = null, $br = false) {
2581          $attributes = (array)$attributes;
2582          if (empty($attributes['width'])) {
2583              $attributes['width'] = 1;
2584          }
2585          if (empty($attributes['height'])) {
2586              $attributes['height'] = 1;
2587          }
2588          $attributes['class'] = 'spacer';
2589  
2590          $output = $this->pix_icon('spacer', '', 'moodle', $attributes);
2591  
2592          if (!empty($br)) {
2593              $output .= '<br />';
2594          }
2595  
2596          return $output;
2597      }
2598  
2599      /**
2600       * Returns HTML to display the specified user's avatar.
2601       *
2602       * User avatar may be obtained in two ways:
2603       * <pre>
2604       * // Option 1: (shortcut for simple cases, preferred way)
2605       * // $user has come from the DB and has fields id, picture, imagealt, firstname and lastname
2606       * $OUTPUT->user_picture($user, array('popup'=>true));
2607       *
2608       * // Option 2:
2609       * $userpic = new user_picture($user);
2610       * // Set properties of $userpic
2611       * $userpic->popup = true;
2612       * $OUTPUT->render($userpic);
2613       * </pre>
2614       *
2615       * Theme developers: DO NOT OVERRIDE! Please override function
2616       * {@link core_renderer::render_user_picture()} instead.
2617       *
2618       * @param stdClass $user Object with at least fields id, picture, imagealt, firstname, lastname
2619       *     If any of these are missing, the database is queried. Avoid this
2620       *     if at all possible, particularly for reports. It is very bad for performance.
2621       * @param array $options associative array with user picture options, used only if not a user_picture object,
2622       *     options are:
2623       *     - courseid=$this->page->course->id (course id of user profile in link)
2624       *     - size=35 (size of image)
2625       *     - link=true (make image clickable - the link leads to user profile)
2626       *     - popup=false (open in popup)
2627       *     - alttext=true (add image alt attribute)
2628       *     - class = image class attribute (default 'userpicture')
2629       *     - visibletoscreenreaders=true (whether to be visible to screen readers)
2630       *     - includefullname=false (whether to include the user's full name together with the user picture)
2631       *     - includetoken = false (whether to use a token for authentication. True for current user, int value for other user id)
2632       * @return string HTML fragment
2633       */
2634      public function user_picture(stdClass $user, array $options = null) {
2635          $userpicture = new user_picture($user);
2636          foreach ((array)$options as $key=>$value) {
2637              if (property_exists($userpicture, $key)) {
2638                  $userpicture->$key = $value;
2639              }
2640          }
2641          return $this->render($userpicture);
2642      }
2643  
2644      /**
2645       * Internal implementation of user image rendering.
2646       *
2647       * @param user_picture $userpicture
2648       * @return string
2649       */
2650      protected function render_user_picture(user_picture $userpicture) {
2651          global $CFG;
2652  
2653          $user = $userpicture->user;
2654          $canviewfullnames = has_capability('moodle/site:viewfullnames', $this->page->context);
2655  
2656          $alt = '';
2657          if ($userpicture->alttext) {
2658              if (!empty($user->imagealt)) {
2659                  $alt = trim($user->imagealt);
2660              }
2661          }
2662  
2663          // If the user picture is being rendered as a link but without the full name, an empty alt text for the user picture
2664          // would mean that the link displayed will not have any discernible text. This becomes an accessibility issue,
2665          // especially to screen reader users. Use the user's full name by default for the user picture's alt-text if this is
2666          // the case.
2667          if ($userpicture->link && !$userpicture->includefullname && empty($alt)) {
2668              $alt = fullname($user);
2669          }
2670  
2671          if (empty($userpicture->size)) {
2672              $size = 35;
2673          } else if ($userpicture->size === true or $userpicture->size == 1) {
2674              $size = 100;
2675          } else {
2676              $size = $userpicture->size;
2677          }
2678  
2679          $class = $userpicture->class;
2680  
2681          if ($user->picture == 0) {
2682              $class .= ' defaultuserpic';
2683          }
2684  
2685          $src = $userpicture->get_url($this->page, $this);
2686  
2687          $attributes = array('src' => $src, 'class' => $class, 'width' => $size, 'height' => $size);
2688          if (!$userpicture->visibletoscreenreaders) {
2689              $alt = '';
2690          }
2691          $attributes['alt'] = $alt;
2692  
2693          if (!empty($alt)) {
2694              $attributes['title'] = $alt;
2695          }
2696  
2697          // Get the image html output first, auto generated based on initials if one isn't already set.
2698          if ($user->picture == 0 && empty($CFG->enablegravatar) && !defined('BEHAT_SITE_RUNNING')) {
2699              $initials = \core_user::get_initials($user);
2700              // Don't modify in corner cases where neither the firstname nor the lastname appears.
2701              $output = html_writer::tag(
2702                  'span', $initials,
2703                  ['class' => 'userinitials size-' . $size]
2704              );
2705          } else {
2706              $output = html_writer::empty_tag('img', $attributes);
2707          }
2708  
2709          // Show fullname together with the picture when desired.
2710          if ($userpicture->includefullname) {
2711              $output .= fullname($userpicture->user, $canviewfullnames);
2712          }
2713  
2714          if (empty($userpicture->courseid)) {
2715              $courseid = $this->page->course->id;
2716          } else {
2717              $courseid = $userpicture->courseid;
2718          }
2719          if ($courseid == SITEID) {
2720              $url = new moodle_url('/user/profile.php', array('id' => $user->id));
2721          } else {
2722              $url = new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $courseid));
2723          }
2724  
2725          // Then wrap it in link if needed. Also we don't wrap it in link if the link redirects to itself.
2726          if (!$userpicture->link ||
2727                  ($this->page->has_set_url() && $this->page->url == $url)) { // Protect against unset page->url.
2728              return $output;
2729          }
2730  
2731          $attributes = array('href' => $url, 'class' => 'd-inline-block aabtn');
2732          if (!$userpicture->visibletoscreenreaders) {
2733              $attributes['tabindex'] = '-1';
2734              $attributes['aria-hidden'] = 'true';
2735          }
2736  
2737          if ($userpicture->popup) {
2738              $id = html_writer::random_id('userpicture');
2739              $attributes['id'] = $id;
2740              $this->add_action_handler(new popup_action('click', $url), $id);
2741          }
2742  
2743          return html_writer::tag('a', $output, $attributes);
2744      }
2745  
2746      /**
2747       * Internal implementation of file tree viewer items rendering.
2748       *
2749       * @param array $dir
2750       * @return string
2751       */
2752      public function htmllize_file_tree($dir) {
2753          if (empty($dir['subdirs']) and empty($dir['files'])) {
2754              return '';
2755          }
2756          $result = '<ul>';
2757          foreach ($dir['subdirs'] as $subdir) {
2758              $result .= '<li>'.s($subdir['dirname']).' '.$this->htmllize_file_tree($subdir).'</li>';
2759          }
2760          foreach ($dir['files'] as $file) {
2761              $filename = $file->get_filename();
2762              $result .= '<li><span>'.html_writer::link($file->fileurl, $filename).'</span></li>';
2763          }
2764          $result .= '</ul>';
2765  
2766          return $result;
2767      }
2768  
2769      /**
2770       * Returns HTML to display the file picker
2771       *
2772       * <pre>
2773       * $OUTPUT->file_picker($options);
2774       * </pre>
2775       *
2776       * Theme developers: DO NOT OVERRIDE! Please override function
2777       * {@link core_renderer::render_file_picker()} instead.
2778       *
2779       * @param stdClass $options file manager options
2780       *   options are:
2781       *       maxbytes=>-1,
2782       *       itemid=>0,
2783       *       client_id=>uniqid(),
2784       *       acepted_types=>'*',
2785       *       return_types=>FILE_INTERNAL,
2786       *       context=>current page context
2787       * @return string HTML fragment
2788       */
2789      public function file_picker($options) {
2790          $fp = new file_picker($options);
2791          return $this->render($fp);
2792      }
2793  
2794      /**
2795       * Internal implementation of file picker rendering.
2796       *
2797       * @param file_picker $fp
2798       * @return string
2799       */
2800      public function render_file_picker(file_picker $fp) {
2801          $options = $fp->options;
2802          $client_id = $options->client_id;
2803          $strsaved = get_string('filesaved', 'repository');
2804          $straddfile = get_string('openpicker', 'repository');
2805          $strloading  = get_string('loading', 'repository');
2806          $strdndenabled = get_string('dndenabled_inbox', 'moodle');
2807          $strdroptoupload = get_string('droptoupload', 'moodle');
2808          $iconprogress = $this->pix_icon('i/loading_small', $strloading).'';
2809  
2810          $currentfile = $options->currentfile;
2811          if (empty($currentfile)) {
2812              $currentfile = '';
2813          } else {
2814              $currentfile .= ' - ';
2815          }
2816          if ($options->maxbytes) {
2817              $size = $options->maxbytes;
2818          } else {
2819              $size = get_max_upload_file_size();
2820          }
2821          if ($size == -1) {
2822              $maxsize = '';
2823          } else {
2824              $maxsize = get_string('maxfilesize', 'moodle', display_size($size, 0));
2825          }
2826          if ($options->buttonname) {
2827              $buttonname = ' name="' . $options->buttonname . '"';
2828          } else {
2829              $buttonname = '';
2830          }
2831          $html = <<<EOD
2832  <div class="filemanager-loading mdl-align" id='filepicker-loading-{$client_id}'>
2833  $iconprogress
2834  </div>
2835  <div id="filepicker-wrapper-{$client_id}" class="mdl-left w-100" style="display:none">
2836      <div>
2837          <input type="button" class="btn btn-secondary fp-btn-choose" id="filepicker-button-{$client_id}" value="{$straddfile}"{$buttonname}/>
2838          <span> $maxsize </span>
2839      </div>
2840  EOD;
2841          if ($options->env != 'url') {
2842              $html .= <<<EOD
2843      <div id="file_info_{$client_id}" class="mdl-left filepicker-filelist" style="position: relative">
2844      <div class="filepicker-filename">
2845          <div class="filepicker-container">$currentfile
2846              <div class="dndupload-message">$strdndenabled <br/>
2847                  <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2848              </div>
2849          </div>
2850          <div class="dndupload-progressbars"></div>
2851      </div>
2852      <div>
2853          <div class="dndupload-target">{$strdroptoupload}<br/>
2854              <div class="dndupload-arrow d-flex"><i class="fa fa-arrow-circle-o-down fa-3x m-auto"></i></div>
2855          </div>
2856      </div>
2857      </div>
2858  EOD;
2859          }
2860          $html .= '</div>';
2861          return $html;
2862      }
2863  
2864      /**
2865       * @deprecated since Moodle 3.2
2866       */
2867      public function update_module_button() {
2868          throw new coding_exception('core_renderer::update_module_button() can not be used anymore. Activity ' .
2869              'modules should not add the edit module button, the link is already available in the Administration block. ' .
2870              'Themes can choose to display the link in the buttons row consistently for all module types.');
2871      }
2872  
2873      /**
2874       * Returns HTML to display a "Turn editing on/off" button in a form.
2875       *
2876       * @param moodle_url $url The URL + params to send through when clicking the button
2877       * @param string $method
2878       * @return string HTML the button
2879       */
2880      public function edit_button(moodle_url $url, string $method = 'post') {
2881  
2882          if ($this->page->theme->haseditswitch == true) {
2883              return;
2884          }
2885          $url->param('sesskey', sesskey());
2886          if ($this->page->user_is_editing()) {
2887              $url->param('edit', 'off');
2888              $editstring = get_string('turneditingoff');
2889          } else {
2890              $url->param('edit', 'on');
2891              $editstring = get_string('turneditingon');
2892          }
2893  
2894          return $this->single_button($url, $editstring, $method);
2895      }
2896  
2897      /**
2898       * Create a navbar switch for toggling editing mode.
2899       *
2900       * @return string Html containing the edit switch
2901       */
2902      public function edit_switch() {
2903          if ($this->page->user_allowed_editing()) {
2904  
2905              $temp = (object) [
2906                  'legacyseturl' => (new moodle_url('/editmode.php'))->out(false),
2907                  'pagecontextid' => $this->page->context->id,
2908                  'pageurl' => $this->page->url,
2909                  'sesskey' => sesskey(),
2910              ];
2911              if ($this->page->user_is_editing()) {
2912                  $temp->checked = true;
2913              }
2914              return $this->render_from_template('core/editswitch', $temp);
2915          }
2916      }
2917  
2918      /**
2919       * Returns HTML to display a simple button to close a window
2920       *
2921       * @param string $text The lang string for the button's label (already output from get_string())
2922       * @return string html fragment
2923       */
2924      public function close_window_button($text='') {
2925          if (empty($text)) {
2926              $text = get_string('closewindow');
2927          }
2928          $button = new single_button(new moodle_url('#'), $text, 'get');
2929          $button->add_action(new component_action('click', 'close_window'));
2930  
2931          return $this->container($this->render($button), 'closewindow');
2932      }
2933  
2934      /**
2935       * Output an error message. By default wraps the error message in <span class="error">.
2936       * If the error message is blank, nothing is output.
2937       *
2938       * @param string $message the error message.
2939       * @return string the HTML to output.
2940       */
2941      public function error_text($message) {
2942          if (empty($message)) {
2943              return '';
2944          }
2945          $message = $this->pix_icon('i/warning', get_string('error'), '', array('class' => 'icon icon-pre', 'title'=>'')) . $message;
2946          return html_writer::tag('span', $message, array('class' => 'error'));
2947      }
2948  
2949      /**
2950       * Do not call this function directly.
2951       *
2952       * To terminate the current script with a fatal error, throw an exception.
2953       * Doing this will then call this function to display the error, before terminating the execution.
2954       *
2955       * @param string $message The message to output
2956       * @param string $moreinfourl URL where more info can be found about the error
2957       * @param string $link Link for the Continue button
2958       * @param array $backtrace The execution backtrace
2959       * @param string $debuginfo Debugging information
2960       * @return string the HTML to output.
2961       */
2962      public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
2963          global $CFG;
2964  
2965          $output = '';
2966          $obbuffer = '';
2967  
2968          if ($this->has_started()) {
2969              // we can not always recover properly here, we have problems with output buffering,
2970              // html tables, etc.
2971              $output .= $this->opencontainers->pop_all_but_last();
2972  
2973          } else {
2974              // It is really bad if library code throws exception when output buffering is on,
2975              // because the buffered text would be printed before our start of page.
2976              // NOTE: this hack might be behave unexpectedly in case output buffering is enabled in PHP.ini
2977              error_reporting(0); // disable notices from gzip compression, etc.
2978              while (ob_get_level() > 0) {
2979                  $buff = ob_get_clean();
2980                  if ($buff === false) {
2981                      break;
2982                  }
2983                  $obbuffer .= $buff;
2984              }
2985              error_reporting($CFG->debug);
2986  
2987              // Output not yet started.
2988              $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2989              if (empty($_SERVER['HTTP_RANGE'])) {
2990                  @header($protocol . ' 404 Not Found');
2991              } else if (core_useragent::check_safari_ios_version(602) && !empty($_SERVER['HTTP_X_PLAYBACK_SESSION_ID'])) {
2992                  // Coax iOS 10 into sending the session cookie.
2993                  @header($protocol . ' 403 Forbidden');
2994              } else {
2995                  // Must stop byteserving attempts somehow,
2996                  // this is weird but Chrome PDF viewer can be stopped only with 407!
2997                  @header($protocol . ' 407 Proxy Authentication Required');
2998              }
2999  
3000              $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
3001              $this->page->set_url('/'); // no url
3002              //$this->page->set_pagelayout('base'); //TODO: MDL-20676 blocks on error pages are weird, unfortunately it somehow detect the pagelayout from URL :-(
3003              $this->page->set_title(get_string('error'));
3004              $this->page->set_heading($this->page->course->fullname);
3005              // No need to display the activity header when encountering an error.
3006              $this->page->activityheader->disable();
3007              $output .= $this->header();
3008          }
3009  
3010          $message = '<p class="errormessage">' . s($message) . '</p>'.
3011                  '<p class="errorcode"><a href="' . s($moreinfourl) . '">' .
3012                  get_string('moreinformation') . '</a></p>';
3013          if (empty($CFG->rolesactive)) {
3014              $message .= '<p class="errormessage">' . get_string('installproblem', 'error') . '</p>';
3015              //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.
3016          }
3017          $output .= $this->box($message, 'errorbox alert alert-danger', null, array('data-rel' => 'fatalerror'));
3018  
3019          if ($CFG->debugdeveloper) {
3020              $labelsep = get_string('labelsep', 'langconfig');
3021              if (!empty($debuginfo)) {
3022                  $debuginfo = s($debuginfo); // removes all nasty JS
3023                  $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
3024                  $label = get_string('debuginfo', 'debug') . $labelsep;
3025                  $output .= $this->notification("<strong>$label</strong> " . $debuginfo, 'notifytiny');
3026              }
3027              if (!empty($backtrace)) {
3028                  $label = get_string('stacktrace', 'debug') . $labelsep;
3029                  $output .= $this->notification("<strong>$label</strong> " . format_backtrace($backtrace), 'notifytiny');
3030              }
3031              if ($obbuffer !== '' ) {
3032                  $label = get_string('outputbuffer', 'debug') . $labelsep;
3033                  $output .= $this->notification("<strong>$label</strong> " . s($obbuffer), 'notifytiny');
3034              }
3035          }
3036  
3037          if (empty($CFG->rolesactive)) {
3038              // continue does not make much sense if moodle is not installed yet because error is most probably not recoverable
3039          } else if (!empty($link)) {
3040              $output .= $this->continue_button($link);
3041          }
3042  
3043          $output .= $this->footer();
3044  
3045          // Padding to encourage IE to display our error page, rather than its own.
3046          $output .= str_repeat(' ', 512);
3047  
3048          return $output;
3049      }
3050  
3051      /**
3052       * Output a notification (that is, a status message about something that has just happened).
3053       *
3054       * Note: \core\notification::add() may be more suitable for your usage.
3055       *
3056       * @param string $message The message to print out.
3057       * @param ?string $type   The type of notification. See constants on \core\output\notification.
3058       * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
3059       * @return string the HTML to output.
3060       */
3061      public function notification($message, $type = null, $closebutton = true) {
3062          $typemappings = [
3063              // Valid types.
3064              'success'           => \core\output\notification::NOTIFY_SUCCESS,
3065              'info'              => \core\output\notification::NOTIFY_INFO,
3066              'warning'           => \core\output\notification::NOTIFY_WARNING,
3067              'error'             => \core\output\notification::NOTIFY_ERROR,
3068  
3069              // Legacy types mapped to current types.
3070              'notifyproblem'     => \core\output\notification::NOTIFY_ERROR,
3071              'notifytiny'        => \core\output\notification::NOTIFY_ERROR,
3072              'notifyerror'       => \core\output\notification::NOTIFY_ERROR,
3073              'notifysuccess'     => \core\output\notification::NOTIFY_SUCCESS,
3074              'notifymessage'     => \core\output\notification::NOTIFY_INFO,
3075              'notifyredirect'    => \core\output\notification::NOTIFY_INFO,
3076              'redirectmessage'   => \core\output\notification::NOTIFY_INFO,
3077          ];
3078  
3079          $extraclasses = [];
3080  
3081          if ($type) {
3082              if (strpos($type, ' ') === false) {
3083                  // No spaces in the list of classes, therefore no need to loop over and determine the class.
3084                  if (isset($typemappings[$type])) {
3085                      $type = $typemappings[$type];
3086                  } else {
3087                      // The value provided did not match a known type. It must be an extra class.
3088                      $extraclasses = [$type];
3089                  }
3090              } else {
3091                  // Identify what type of notification this is.
3092                  $classarray = explode(' ', self::prepare_classes($type));
3093  
3094                  // Separate out the type of notification from the extra classes.
3095                  foreach ($classarray as $class) {
3096                      if (isset($typemappings[$class])) {
3097                          $type = $typemappings[$class];
3098                      } else {
3099                          $extraclasses[] = $class;
3100                      }
3101                  }
3102              }
3103          }
3104  
3105          $notification = new \core\output\notification($message, $type, $closebutton);
3106          if (count($extraclasses)) {
3107              $notification->set_extra_classes($extraclasses);
3108          }
3109  
3110          // Return the rendered template.
3111          return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3112      }
3113  
3114      /**
3115       * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3116       */
3117      public function notify_problem() {
3118          throw new coding_exception('core_renderer::notify_problem() can not be used any more, '.
3119              'please use \core\notification::add(), or \core\output\notification as required.');
3120      }
3121  
3122      /**
3123       * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3124       */
3125      public function notify_success() {
3126          throw new coding_exception('core_renderer::notify_success() can not be used any more, '.
3127              'please use \core\notification::add(), or \core\output\notification as required.');
3128      }
3129  
3130      /**
3131       * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3132       */
3133      public function notify_message() {
3134          throw new coding_exception('core_renderer::notify_message() can not be used any more, '.
3135              'please use \core\notification::add(), or \core\output\notification as required.');
3136      }
3137  
3138      /**
3139       * @deprecated since Moodle 3.1 MDL-30811 - please do not use this function any more.
3140       */
3141      public function notify_redirect() {
3142          throw new coding_exception('core_renderer::notify_redirect() can not be used any more, '.
3143              'please use \core\notification::add(), or \core\output\notification as required.');
3144      }
3145  
3146      /**
3147       * Render a notification (that is, a status message about something that has
3148       * just happened).
3149       *
3150       * @param \core\output\notification $notification the notification to print out
3151       * @return string the HTML to output.
3152       */
3153      protected function render_notification(\core\output\notification $notification) {
3154          return $this->render_from_template($notification->get_template_name(), $notification->export_for_template($this));
3155      }
3156  
3157      /**
3158       * Returns HTML to display a continue button that goes to a particular URL.
3159       *
3160       * @param string|moodle_url $url The url the button goes to.
3161       * @return string the HTML to output.
3162       */
3163      public function continue_button($url) {
3164          if (!($url instanceof moodle_url)) {
3165              $url = new moodle_url($url);
3166          }
3167          $button = new single_button($url, get_string('continue'), 'get', single_button::BUTTON_PRIMARY);
3168          $button->class = 'continuebutton';
3169  
3170          return $this->render($button);
3171      }
3172  
3173      /**
3174       * Returns HTML to display a single paging bar to provide access to other pages  (usually in a search)
3175       *
3176       * Theme developers: DO NOT OVERRIDE! Please override function
3177       * {@link core_renderer::render_paging_bar()} instead.
3178       *
3179       * @param int $totalcount The total number of entries available to be paged through
3180       * @param int $page The page you are currently viewing
3181       * @param int $perpage The number of entries that should be shown per page
3182       * @param string|moodle_url $baseurl url of the current page, the $pagevar parameter is added
3183       * @param string $pagevar name of page parameter that holds the page number
3184       * @return string the HTML to output.
3185       */
3186      public function paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar = 'page') {
3187          $pb = new paging_bar($totalcount, $page, $perpage, $baseurl, $pagevar);
3188          return $this->render($pb);
3189      }
3190  
3191      /**
3192       * Returns HTML to display the paging bar.
3193       *
3194       * @param paging_bar $pagingbar
3195       * @return string the HTML to output.
3196       */
3197      protected function render_paging_bar(paging_bar $pagingbar) {
3198          // Any more than 10 is not usable and causes weird wrapping of the pagination.
3199          $pagingbar->maxdisplay = 10;
3200          return $this->render_from_template('core/paging_bar', $pagingbar->export_for_template($this));
3201      }
3202  
3203      /**
3204       * Returns HTML to display initials bar to provide access to other pages  (usually in a search)
3205       *
3206       * @param string $current the currently selected letter.
3207       * @param string $class class name to add to this initial bar.
3208       * @param string $title the name to put in front of this initial bar.
3209       * @param string $urlvar URL parameter name for this initial.
3210       * @param string $url URL object.
3211       * @param array $alpha of letters in the alphabet.
3212       * @param bool $minirender Return a trimmed down view of the initials bar.
3213       * @return string the HTML to output.
3214       */
3215      public function initials_bar($current, $class, $title, $urlvar, $url, $alpha = null, bool $minirender = false) {
3216          $ib = new initials_bar($current, $class, $title, $urlvar, $url, $alpha, $minirender);
3217          return $this->render($ib);
3218      }
3219  
3220      /**
3221       * Internal implementation of initials bar rendering.
3222       *
3223       * @param initials_bar $initialsbar
3224       * @return string
3225       */
3226      protected function render_initials_bar(initials_bar $initialsbar) {
3227          return $this->render_from_template('core/initials_bar', $initialsbar->export_for_template($this));
3228      }
3229  
3230      /**
3231       * Output the place a skip link goes to.
3232       *
3233       * @param string $id The target name from the corresponding $PAGE->requires->skip_link_to($target) call.
3234       * @return string the HTML to output.
3235       */
3236      public function skip_link_target($id = null) {
3237          return html_writer::span('', '', array('id' => $id));
3238      }
3239  
3240      /**
3241       * Outputs a heading
3242       *
3243       * @param string $text The text of the heading
3244       * @param int $level The level of importance of the heading. Defaulting to 2
3245       * @param string $classes A space-separated list of CSS classes. Defaulting to null
3246       * @param string $id An optional ID
3247       * @return string the HTML to output.
3248       */
3249      public function heading($text, $level = 2, $classes = null, $id = null) {
3250          $level = (integer) $level;
3251          if ($level < 1 or $level > 6) {
3252              throw new coding_exception('Heading level must be an integer between 1 and 6.');
3253          }
3254          return html_writer::tag('h' . $level, $text, array('id' => $id, 'class' => renderer_base::prepare_classes($classes)));
3255      }
3256  
3257      /**
3258       * Outputs a box.
3259       *
3260       * @param string $contents The contents of the box
3261       * @param string $classes A space-separated list of CSS classes
3262       * @param string $id An optional ID
3263       * @param array $attributes An array of other attributes to give the box.
3264       * @return string the HTML to output.
3265       */
3266      public function box($contents, $classes = 'generalbox', $id = null, $attributes = array()) {
3267          return $this->box_start($classes, $id, $attributes) . $contents . $this->box_end();
3268      }
3269  
3270      /**
3271       * Outputs the opening section of a box.
3272       *
3273       * @param string $classes A space-separated list of CSS classes
3274       * @param string $id An optional ID
3275       * @param array $attributes An array of other attributes to give the box.
3276       * @return string the HTML to output.
3277       */
3278      public function box_start($classes = 'generalbox', $id = null, $attributes = array()) {
3279          $this->opencontainers->push('box', html_writer::end_tag('div'));
3280          $attributes['id'] = $id;
3281          $attributes['class'] = 'box py-3 ' . renderer_base::prepare_classes($classes);
3282          return html_writer::start_tag('div', $attributes);
3283      }
3284  
3285      /**
3286       * Outputs the closing section of a box.
3287       *
3288       * @return string the HTML to output.
3289       */
3290      public function box_end() {
3291          return $this->opencontainers->pop('box');
3292      }
3293  
3294      /**
3295       * Outputs a container.
3296       *
3297       * @param string $contents The contents of the box
3298       * @param string $classes A space-separated list of CSS classes
3299       * @param string $id An optional ID
3300       * @return string the HTML to output.
3301       */
3302      public function container($contents, $classes = null, $id = null) {
3303          return $this->container_start($classes, $id) . $contents . $this->container_end();
3304      }
3305  
3306      /**
3307       * Outputs the opening section of a container.
3308       *
3309       * @param string $classes A space-separated list of CSS classes
3310       * @param string $id An optional ID
3311       * @return string the HTML to output.
3312       */
3313      public function container_start($classes = null, $id = null) {
3314          $this->opencontainers->push('container', html_writer::end_tag('div'));
3315          return html_writer::start_tag('div', array('id' => $id,
3316                  'class' => renderer_base::prepare_classes($classes)));
3317      }
3318  
3319      /**
3320       * Outputs the closing section of a container.
3321       *
3322       * @return string the HTML to output.
3323       */
3324      public function container_end() {
3325          return $this->opencontainers->pop('container');
3326      }
3327  
3328      /**
3329       * Make nested HTML lists out of the items
3330       *
3331       * The resulting list will look something like this:
3332       *
3333       * <pre>
3334       * <<ul>>
3335       * <<li>><div class='tree_item parent'>(item contents)</div>
3336       *      <<ul>
3337       *      <<li>><div class='tree_item'>(item contents)</div><</li>>
3338       *      <</ul>>
3339       * <</li>>
3340       * <</ul>>
3341       * </pre>
3342       *
3343       * @param array $items
3344       * @param array $attrs html attributes passed to the top ofs the list
3345       * @return string HTML
3346       */
3347      public function tree_block_contents($items, $attrs = array()) {
3348          // exit if empty, we don't want an empty ul element
3349          if (empty($items)) {
3350              return '';
3351          }
3352          // array of nested li elements
3353          $lis = array();
3354          foreach ($items as $item) {
3355              // this applies to the li item which contains all child lists too
3356              $content = $item->content($this);
3357              $liclasses = array($item->get_css_type());
3358              if (!$item->forceopen || (!$item->forceopen && $item->collapse) || ($item->children->count()==0  && $item->nodetype==navigation_node::NODETYPE_BRANCH)) {
3359                  $liclasses[] = 'collapsed';
3360              }
3361              if ($item->isactive === true) {
3362                  $liclasses[] = 'current_branch';
3363              }
3364              $liattr = array('class'=>join(' ',$liclasses));
3365              // class attribute on the div item which only contains the item content
3366              $divclasses = array('tree_item');
3367              if ($item->children->count()>0  || $item->nodetype==navigation_node::NODETYPE_BRANCH) {
3368                  $divclasses[] = 'branch';
3369              } else {
3370                  $divclasses[] = 'leaf';
3371              }
3372              if (!empty($item->classes) && count($item->classes)>0) {
3373                  $divclasses[] = join(' ', $item->classes);
3374              }
3375              $divattr = array('class'=>join(' ', $divclasses));
3376              if (!empty($item->id)) {
3377                  $divattr['id'] = $item->id;
3378              }
3379              $content = html_writer::tag('p', $content, $divattr) . $this->tree_block_contents($item->children);
3380              if (!empty($item->preceedwithhr) && $item->preceedwithhr===true) {
3381                  $content = html_writer::empty_tag('hr') . $content;
3382              }
3383              $content = html_writer::tag('li', $content, $liattr);
3384              $lis[] = $content;
3385          }
3386          return html_writer::tag('ul', implode("\n", $lis), $attrs);
3387      }
3388  
3389      /**
3390       * Returns a search box.
3391       *
3392       * @param  string $id     The search box wrapper div id, defaults to an autogenerated one.
3393       * @return string         HTML with the search form hidden by default.
3394       */
3395      public function search_box($id = false) {
3396          global $CFG;
3397  
3398          // Accessing $CFG directly as using \core_search::is_global_search_enabled would
3399          // result in an extra included file for each site, even the ones where global search
3400          // is disabled.
3401          if (empty($CFG->enableglobalsearch) || !has_capability('moodle/search:query', context_system::instance())) {
3402              return '';
3403          }
3404  
3405          $data = [
3406              'action' => new moodle_url('/search/index.php'),
3407              'hiddenfields' => (object) ['name' => 'context', 'value' => $this->page->context->id],
3408              'inputname' => 'q',
3409              'searchstring' => get_string('search'),
3410              ];
3411          return $this->render_from_template('core/search_input_navbar', $data);
3412      }
3413  
3414      /**
3415       * Allow plugins to provide some content to be rendered in the navbar.
3416       * The plugin must define a PLUGIN_render_navbar_output function that returns
3417       * the HTML they wish to add to the navbar.
3418       *
3419       * @return string HTML for the navbar
3420       */
3421      public function navbar_plugin_output() {
3422          $output = '';
3423  
3424          // Give subsystems an opportunity to inject extra html content. The callback
3425          // must always return a string containing valid html.
3426          foreach (\core_component::get_core_subsystems() as $name => $path) {
3427              if ($path) {
3428                  $output .= component_callback($name, 'render_navbar_output', [$this], '');
3429              }
3430          }
3431  
3432          if ($pluginsfunction = get_plugins_with_function('render_navbar_output')) {
3433              foreach ($pluginsfunction as $plugintype => $plugins) {
3434                  foreach ($plugins as $pluginfunction) {
3435                      $output .= $pluginfunction($this);
3436                  }
3437              }
3438          }
3439  
3440          return $output;
3441      }
3442  
3443      /**
3444       * Construct a user menu, returning HTML that can be echoed out by a
3445       * layout file.
3446       *
3447       * @param stdClass $user A user object, usually $USER.
3448       * @param bool $withlinks true if a dropdown should be built.
3449       * @return string HTML fragment.
3450       */
3451      public function user_menu($user = null, $withlinks = null) {
3452          global $USER, $CFG;
3453          require_once($CFG->dirroot . '/user/lib.php');
3454  
3455          if (is_null($user)) {
3456              $user = $USER;
3457          }
3458  
3459          // Note: this behaviour is intended to match that of core_renderer::login_info,
3460          // but should not be considered to be good practice; layout options are
3461          // intended to be theme-specific. Please don't copy this snippet anywhere else.
3462          if (is_null($withlinks)) {
3463              $withlinks = empty($this->page->layout_options['nologinlinks']);
3464          }
3465  
3466          // Add a class for when $withlinks is false.
3467          $usermenuclasses = 'usermenu';
3468          if (!$withlinks) {
3469              $usermenuclasses .= ' withoutlinks';
3470          }
3471  
3472          $returnstr = "";
3473  
3474          // If during initial install, return the empty return string.
3475          if (during_initial_install()) {
3476              return $returnstr;
3477          }
3478  
3479          $loginpage = $this->is_login_page();
3480          $loginurl = get_login_url();
3481  
3482          // Get some navigation opts.
3483          $opts = user_get_user_navigation_info($user, $this->page);
3484  
3485          if (!empty($opts->unauthenticateduser)) {
3486              $returnstr = get_string($opts->unauthenticateduser['content'], 'moodle');
3487              // If not logged in, show the typical not-logged-in string.
3488              if (!$loginpage && (!$opts->unauthenticateduser['guest'] || $withlinks)) {
3489                  $returnstr .= " (<a href=\"$loginurl\">" . get_string('login') . '</a>)';
3490              }
3491  
3492              return html_writer::div(
3493                  html_writer::span(
3494                      $returnstr,
3495                      'login nav-link'
3496                  ),
3497                  $usermenuclasses
3498              );
3499          }
3500  
3501          $avatarclasses = "avatars";
3502          $avatarcontents = html_writer::span($opts->metadata['useravatar'], 'avatar current');
3503          $usertextcontents = $opts->metadata['userfullname'];
3504  
3505          // Other user.
3506          if (!empty($opts->metadata['asotheruser'])) {
3507              $avatarcontents .= html_writer::span(
3508                  $opts->metadata['realuseravatar'],
3509                  'avatar realuser'
3510              );
3511              $usertextcontents = $opts->metadata['realuserfullname'];
3512              $usertextcontents .= html_writer::tag(
3513                  'span',
3514                  get_string(
3515                      'loggedinas',
3516                      'moodle',
3517                      html_writer::span(
3518                          $opts->metadata['userfullname'],
3519                          'value'
3520                      )
3521                  ),
3522                  array('class' => 'meta viewingas')
3523              );
3524          }
3525  
3526          // Role.
3527          if (!empty($opts->metadata['asotherrole'])) {
3528              $role = core_text::strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['rolename'])));
3529              $usertextcontents .= html_writer::span(
3530                  $opts->metadata['rolename'],
3531                  'meta role role-' . $role
3532              );
3533          }
3534  
3535          // User login failures.
3536          if (!empty($opts->metadata['userloginfail'])) {
3537              $usertextcontents .= html_writer::span(
3538                  $opts->metadata['userloginfail'],
3539                  'meta loginfailures'
3540              );
3541          }
3542  
3543          // MNet.
3544          if (!empty($opts->metadata['asmnetuser'])) {
3545              $mnet = strtolower(preg_replace('#[ ]+#', '-', trim($opts->metadata['mnetidprovidername'])));
3546              $usertextcontents .= html_writer::span(
3547                  $opts->metadata['mnetidprovidername'],
3548                  'meta mnet mnet-' . $mnet
3549              );
3550          }
3551  
3552          $returnstr .= html_writer::span(
3553              html_writer::span($usertextcontents, 'usertext mr-1') .
3554              html_writer::span($avatarcontents, $avatarclasses),
3555              'userbutton'
3556          );
3557  
3558          // Create a divider (well, a filler).
3559          $divider = new action_menu_filler();
3560          $divider->primary = false;
3561  
3562          $am = new action_menu();
3563          $am->set_menu_trigger(
3564              $returnstr,
3565              'nav-link'
3566          );
3567          $am->set_action_label(get_string('usermenu'));
3568          $am->set_nowrap_on_items();
3569          if ($withlinks) {
3570              $navitemcount = count($opts->navitems);
3571              $idx = 0;
3572              foreach ($opts->navitems as $key => $value) {
3573  
3574                  switch ($value->itemtype) {
3575                      case 'divider':
3576                          // If the nav item is a divider, add one and skip link processing.
3577                          $am->add($divider);
3578                          break;
3579  
3580                      case 'invalid':
3581                          // Silently skip invalid entries (should we post a notification?).
3582                          break;
3583  
3584                      case 'link':
3585                          // Process this as a link item.
3586                          $pix = null;
3587                          if (isset($value->pix) && !empty($value->pix)) {
3588                              $pix = new pix_icon($value->pix, '', null, array('class' => 'iconsmall'));
3589                          } else if (isset($value->imgsrc) && !empty($value->imgsrc)) {
3590                              $value->title = html_writer::img(
3591                                  $value->imgsrc,
3592                                  $value->title,
3593                                  array('class' => 'iconsmall')
3594                              ) . $value->title;
3595                          }
3596  
3597                          $al = new action_menu_link_secondary(
3598                              $value->url,
3599                              $pix,
3600                              $value->title,
3601                              array('class' => 'icon')
3602                          );
3603                          if (!empty($value->titleidentifier)) {
3604                              $al->attributes['data-title'] = $value->titleidentifier;
3605                          }
3606                          $am->add($al);
3607                          break;
3608                  }
3609  
3610                  $idx++;
3611  
3612                  // Add dividers after the first item and before the last item.
3613                  if ($idx == 1 || $idx == $navitemcount - 1) {
3614                      $am->add($divider);
3615                  }
3616              }
3617          }
3618  
3619          return html_writer::div(
3620              $this->render($am),
3621              $usermenuclasses
3622          );
3623      }
3624  
3625      /**
3626       * Secure layout login info.
3627       *
3628       * @return string
3629       */
3630      public function secure_layout_login_info() {
3631          if (get_config('core', 'logininfoinsecurelayout')) {
3632              return $this->login_info(false);
3633          } else {
3634              return '';
3635          }
3636      }
3637  
3638      /**
3639       * Returns the language menu in the secure layout.
3640       *
3641       * No custom menu items are passed though, such that it will render only the language selection.
3642       *
3643       * @return string
3644       */
3645      public function secure_layout_language_menu() {
3646          if (get_config('core', 'langmenuinsecurelayout')) {
3647              $custommenu = new custom_menu('', current_language());
3648              return $this->render_custom_menu($custommenu);
3649          } else {
3650              return '';
3651          }
3652      }
3653  
3654      /**
3655       * This renders the navbar.
3656       * Uses bootstrap compatible html.
3657       */
3658      public function navbar() {
3659          return $this->render_from_template('core/navbar', $this->page->navbar);
3660      }
3661  
3662      /**
3663       * Renders a breadcrumb navigation node object.
3664       *
3665       * @param breadcrumb_navigation_node $item The navigation node to render.
3666       * @return string HTML fragment
3667       */
3668      protected function render_breadcrumb_navigation_node(breadcrumb_navigation_node $item) {
3669  
3670          if ($item->action instanceof moodle_url) {
3671              $content = $item->get_content();
3672              $title = $item->get_title();
3673              $attributes = array();
3674              $attributes['itemprop'] = 'url';
3675              if ($title !== '') {
3676                  $attributes['title'] = $title;
3677              }
3678              if ($item->hidden) {
3679                  $attributes['class'] = 'dimmed_text';
3680              }
3681              if ($item->is_last()) {
3682                  $attributes['aria-current'] = 'page';
3683              }
3684              $content = html_writer::tag('span', $content, array('itemprop' => 'title'));
3685              $content = html_writer::link($item->action, $content, $attributes);
3686  
3687              $attributes = array();
3688              $attributes['itemscope'] = '';
3689              $attributes['itemtype'] = 'http://data-vocabulary.org/Breadcrumb';
3690              $content = html_writer::tag('span', $content, $attributes);
3691  
3692          } else {
3693              $content = $this->render_navigation_node($item);
3694          }
3695          return $content;
3696      }
3697  
3698      /**
3699       * Renders a navigation node object.
3700       *
3701       * @param navigation_node $item The navigation node to render.
3702       * @return string HTML fragment
3703       */
3704      protected function render_navigation_node(navigation_node $item) {
3705          $content = $item->get_content();
3706          $title = $item->get_title();
3707          if ($item->icon instanceof renderable && !$item->hideicon) {
3708              $icon = $this->render($item->icon);
3709              $content = $icon.$content; // use CSS for spacing of icons
3710          }
3711          if ($item->helpbutton !== null) {
3712              $content = trim($item->helpbutton).html_writer::tag('span', $content, array('class'=>'clearhelpbutton', 'tabindex'=>'0'));
3713          }
3714          if ($content === '') {
3715              return '';
3716          }
3717          if ($item->action instanceof action_link) {
3718              $link = $item->action;
3719              if ($item->hidden) {
3720                  $link->add_class('dimmed');
3721              }
3722              if (!empty($content)) {
3723                  // Providing there is content we will use that for the link content.
3724                  $link->text = $content;
3725              }
3726              $content = $this->render($link);
3727          } else if ($item->action instanceof moodle_url) {
3728              $attributes = array();
3729              if ($title !== '') {
3730                  $attributes['title'] = $title;
3731              }
3732              if ($item->hidden) {
3733                  $attributes['class'] = 'dimmed_text';
3734              }
3735              $content = html_writer::link($item->action, $content, $attributes);
3736  
3737          } else if (is_string($item->action) || empty($item->action)) {
3738              $attributes = array('tabindex'=>'0'); //add tab support to span but still maintain character stream sequence.
3739              if ($title !== '') {
3740                  $attributes['title'] = $title;
3741              }
3742              if ($item->hidden) {
3743                  $attributes['class'] = 'dimmed_text';
3744              }
3745              $content = html_writer::tag('span', $content, $attributes);
3746          }
3747          return $content;
3748      }
3749  
3750      /**
3751       * Accessibility: Right arrow-like character is
3752       * used in the breadcrumb trail, course navigation menu
3753       * (previous/next activity), calendar, and search forum block.
3754       * If the theme does not set characters, appropriate defaults
3755       * are set automatically. Please DO NOT
3756       * use &lt; &gt; &raquo; - these are confusing for blind users.
3757       *
3758       * @return string
3759       */
3760      public function rarrow() {
3761          return $this->page->theme->rarrow;
3762      }
3763  
3764      /**
3765       * Accessibility: Left arrow-like character is
3766       * used in the breadcrumb trail, course navigation menu
3767       * (previous/next activity), calendar, and search forum block.
3768       * If the theme does not set characters, appropriate defaults
3769       * are set automatically. Please DO NOT
3770       * use &lt; &gt; &raquo; - these are confusing for blind users.
3771       *
3772       * @return string
3773       */
3774      public function larrow() {
3775          return $this->page->theme->larrow;
3776      }
3777  
3778      /**
3779       * Accessibility: Up arrow-like character is used in
3780       * the book heirarchical navigation.
3781       * If the theme does not set characters, appropriate defaults
3782       * are set automatically. Please DO NOT
3783       * use ^ - this is confusing for blind users.
3784       *
3785       * @return string
3786       */
3787      public function uarrow() {
3788          return $this->page->theme->uarrow;
3789      }
3790  
3791      /**
3792       * Accessibility: Down arrow-like character.
3793       * If the theme does not set characters, appropriate defaults
3794       * are set automatically.
3795       *
3796       * @return string
3797       */
3798      public function darrow() {
3799          return $this->page->theme->darrow;
3800      }
3801  
3802      /**
3803       * Returns the custom menu if one has been set
3804       *
3805       * A custom menu can be configured by browsing to
3806       *    Settings: Administration > Appearance > Themes > Theme settings
3807       * and then configuring the custommenu config setting as described.
3808       *
3809       * Theme developers: DO NOT OVERRIDE! Please override function
3810       * {@link core_renderer::render_custom_menu()} instead.
3811       *
3812       * @param string $custommenuitems - custom menuitems set by theme instead of global theme settings
3813       * @return string
3814       */
3815      public function custom_menu($custommenuitems = '') {
3816          global $CFG;
3817  
3818          if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3819              $custommenuitems = $CFG->custommenuitems;
3820          }
3821          $custommenu = new custom_menu($custommenuitems, current_language());
3822          return $this->render_custom_menu($custommenu);
3823      }
3824  
3825      /**
3826       * We want to show the custom menus as a list of links in the footer on small screens.
3827       * Just return the menu object exported so we can render it differently.
3828       */
3829      public function custom_menu_flat() {
3830          global $CFG;
3831          $custommenuitems = '';
3832  
3833          if (empty($custommenuitems) && !empty($CFG->custommenuitems)) {
3834              $custommenuitems = $CFG->custommenuitems;
3835          }
3836          $custommenu = new custom_menu($custommenuitems, current_language());
3837          $langs = get_string_manager()->get_list_of_translations();
3838          $haslangmenu = $this->lang_menu() != '';
3839  
3840          if ($haslangmenu) {
3841              $strlang = get_string('language');
3842              $currentlang = current_language();
3843              if (isset($langs[$currentlang])) {
3844                  $currentlang = $langs[$currentlang];
3845              } else {
3846                  $currentlang = $strlang;
3847              }
3848              $this->language = $custommenu->add($currentlang, new moodle_url('#'), $strlang, 10000);
3849              foreach ($langs as $langtype => $langname) {
3850                  $this->language->add($langname, new moodle_url($this->page->url, array('lang' => $langtype)), $langname);
3851              }
3852          }
3853  
3854          return $custommenu->export_for_template($this);
3855      }
3856  
3857      /**
3858       * Renders a custom menu object (located in outputcomponents.php)
3859       *
3860       * The custom menu this method produces makes use of the YUI3 menunav widget
3861       * and requires very specific html elements and classes.
3862       *
3863       * @staticvar int $menucount
3864       * @param custom_menu $menu
3865       * @return string
3866       */
3867      protected function render_custom_menu(custom_menu $menu) {
3868          global $CFG;
3869  
3870          $langs = get_string_manager()->get_list_of_translations();
3871          $haslangmenu = $this->lang_menu() != '';
3872  
3873          if (!$menu->has_children() && !$haslangmenu) {
3874              return '';
3875          }
3876  
3877          if ($haslangmenu) {
3878              $strlang = get_string('language');
3879              $currentlang = current_language();
3880              if (isset($langs[$currentlang])) {
3881                  $currentlangstr = $langs[$currentlang];
3882              } else {
3883                  $currentlangstr = $strlang;
3884              }
3885              $this->language = $menu->add($currentlangstr, new moodle_url('#'), $strlang, 10000);
3886              foreach ($langs as $langtype => $langname) {
3887                  $attributes = [];
3888                  // Set the lang attribute for languages different from the page's current language.
3889                  if ($langtype !== $currentlang) {
3890                      $attributes[] = [
3891                          'key' => 'lang',
3892                          'value' => get_html_lang_attribute_value($langtype),
3893                      ];
3894                  }
3895                  $this->language->add($langname, new moodle_url($this->page->url, ['lang' => $langtype]), null, null, $attributes);
3896              }
3897          }
3898  
3899          $content = '';
3900          foreach ($menu->get_children() as $item) {
3901              $context = $item->export_for_template($this);
3902              $content .= $this->render_from_template('core/custom_menu_item', $context);
3903          }
3904  
3905          return $content;
3906      }
3907  
3908      /**
3909       * Renders a custom menu node as part of a submenu
3910       *
3911       * The custom menu this method produces makes use of the YUI3 menunav widget
3912       * and requires very specific html elements and classes.
3913       *
3914       * @see core:renderer::render_custom_menu()
3915       *
3916       * @staticvar int $submenucount
3917       * @param custom_menu_item $menunode
3918       * @return string
3919       */
3920      protected function render_custom_menu_item(custom_menu_item $menunode) {
3921          // Required to ensure we get unique trackable id's
3922          static $submenucount = 0;
3923          if ($menunode->has_children()) {
3924              // If the child has menus render it as a sub menu
3925              $submenucount++;
3926              $content = html_writer::start_tag('li');
3927              if ($menunode->get_url() !== null) {
3928                  $url = $menunode->get_url();
3929              } else {
3930                  $url = '#cm_submenu_'.$submenucount;
3931              }
3932              $content .= html_writer::link($url, $menunode->get_text(), array('class'=>'yui3-menu-label', 'title'=>$menunode->get_title()));
3933              $content .= html_writer::start_tag('div', array('id'=>'cm_submenu_'.$submenucount, 'class'=>'yui3-menu custom_menu_submenu'));
3934              $content .= html_writer::start_tag('div', array('class'=>'yui3-menu-content'));
3935              $content .= html_writer::start_tag('ul');
3936              foreach ($menunode->get_children() as $menunode) {
3937                  $content .= $this->render_custom_menu_item($menunode);
3938              }
3939              $content .= html_writer::end_tag('ul');
3940              $content .= html_writer::end_tag('div');
3941              $content .= html_writer::end_tag('div');
3942              $content .= html_writer::end_tag('li');
3943          } else {
3944              // The node doesn't have children so produce a final menuitem.
3945              // Also, if the node's text matches '####', add a class so we can treat it as a divider.
3946              $content = '';
3947              if (preg_match("/^#+$/", $menunode->get_text())) {
3948  
3949                  // This is a divider.
3950                  $content = html_writer::start_tag('li', array('class' => 'yui3-menuitem divider'));
3951              } else {
3952                  $content = html_writer::start_tag(
3953                      'li',
3954                      array(
3955                          'class' => 'yui3-menuitem'
3956                      )
3957                  );
3958                  if ($menunode->get_url() !== null) {
3959                      $url = $menunode->get_url();
3960                  } else {
3961                      $url = '#';
3962                  }
3963                  $content .= html_writer::link(
3964                      $url,
3965                      $menunode->get_text(),
3966                      array('class' => 'yui3-menuitem-content', 'title' => $menunode->get_title())
3967                  );
3968              }
3969              $content .= html_writer::end_tag('li');
3970          }
3971          // Return the sub menu
3972          return $content;
3973      }
3974  
3975      /**
3976       * Renders theme links for switching between default and other themes.
3977       *
3978       * @return string
3979       */
3980      protected function theme_switch_links() {
3981  
3982          $actualdevice = core_useragent::get_device_type();
3983          $currentdevice = $this->page->devicetypeinuse;
3984          $switched = ($actualdevice != $currentdevice);
3985  
3986          if (!$switched && $currentdevice == 'default' && $actualdevice == 'default') {
3987              // The user is using the a default device and hasn't switched so don't shown the switch
3988              // device links.
3989              return '';
3990          }
3991  
3992          if ($switched) {
3993              $linktext = get_string('switchdevicerecommended');
3994              $devicetype = $actualdevice;
3995          } else {
3996              $linktext = get_string('switchdevicedefault');
3997              $devicetype = 'default';
3998          }
3999          $linkurl = new moodle_url('/theme/switchdevice.php', array('url' => $this->page->url, 'device' => $devicetype, 'sesskey' => sesskey()));
4000  
4001          $content  = html_writer::start_tag('div', array('id' => 'theme_switch_link'));
4002          $content .= html_writer::link($linkurl, $linktext, array('rel' => 'nofollow'));
4003          $content .= html_writer::end_tag('div');
4004  
4005          return $content;
4006      }
4007  
4008      /**
4009       * Renders tabs
4010       *
4011       * This function replaces print_tabs() used before Moodle 2.5 but with slightly different arguments
4012       *
4013       * Theme developers: In order to change how tabs are displayed please override functions
4014       * {@link core_renderer::render_tabtree()} and/or {@link core_renderer::render_tabobject()}
4015       *
4016       * @param array $tabs array of tabs, each of them may have it's own ->subtree
4017       * @param string|null $selected which tab to mark as selected, all parent tabs will
4018       *     automatically be marked as activated
4019       * @param array|string|null $inactive list of ids of inactive tabs, regardless of
4020       *     their level. Note that you can as weel specify tabobject::$inactive for separate instances
4021       * @return string
4022       */
4023      public final function tabtree($tabs, $selected = null, $inactive = null) {
4024          return $this->render(new tabtree($tabs, $selected, $inactive));
4025      }
4026  
4027      /**
4028       * Renders tabtree
4029       *
4030       * @param tabtree $tabtree
4031       * @return string
4032       */
4033      protected function render_tabtree(tabtree $tabtree) {
4034          if (empty($tabtree->subtree)) {
4035              return '';
4036          }
4037          $data = $tabtree->export_for_template($this);
4038          return $this->render_from_template('core/tabtree', $data);
4039      }
4040  
4041      /**
4042       * Renders tabobject (part of tabtree)
4043       *
4044       * This function is called from {@link core_renderer::render_tabtree()}
4045       * and also it calls itself when printing the $tabobject subtree recursively.
4046       *
4047       * Property $tabobject->level indicates the number of row of tabs.
4048       *
4049       * @param tabobject $tabobject
4050       * @return string HTML fragment
4051       */
4052      protected function render_tabobject(tabobject $tabobject) {
4053          $str = '';
4054  
4055          // Print name of the current tab.
4056          if ($tabobject instanceof tabtree) {
4057              // No name for tabtree root.
4058          } else if ($tabobject->inactive || $tabobject->activated || ($tabobject->selected && !$tabobject->linkedwhenselected)) {
4059              // Tab name without a link. The <a> tag is used for styling.
4060              $str .= html_writer::tag('a', html_writer::span($tabobject->text), array('class' => 'nolink moodle-has-zindex'));
4061          } else {
4062              // Tab name with a link.
4063              if (!($tabobject->link instanceof moodle_url)) {
4064                  // backward compartibility when link was passed as quoted string
4065                  $str .= "<a href=\"$tabobject->link\" title=\"$tabobject->title\"><span>$tabobject->text</span></a>";
4066              } else {
4067                  $str .= html_writer::link($tabobject->link, html_writer::span($tabobject->text), array('title' => $tabobject->title));
4068              }
4069          }
4070  
4071          if (empty($tabobject->subtree)) {
4072              if ($tabobject->selected) {
4073                  $str .= html_writer::tag('div', '&nbsp;', array('class' => 'tabrow'. ($tabobject->level + 1). ' empty'));
4074              }
4075              return $str;
4076          }
4077  
4078          // Print subtree.
4079          if ($tabobject->level == 0 || $tabobject->selected || $tabobject->activated) {
4080              $str .= html_writer::start_tag('ul', array('class' => 'tabrow'. $tabobject->level));
4081              $cnt = 0;
4082              foreach ($tabobject->subtree as $tab) {
4083                  $liclass = '';
4084                  if (!$cnt) {
4085                      $liclass .= ' first';
4086                  }
4087                  if ($cnt == count($tabobject->subtree) - 1) {
4088                      $liclass .= ' last';
4089                  }
4090                  if ((empty($tab->subtree)) && (!empty($tab->selected))) {
4091                      $liclass .= ' onerow';
4092                  }
4093  
4094                  if ($tab->selected) {
4095                      $liclass .= ' here selected';
4096                  } else if ($tab->activated) {
4097                      $liclass .= ' here active';
4098                  }
4099  
4100                  // This will recursively call function render_tabobject() for each item in subtree.
4101                  $str .= html_writer::tag('li', $this->render($tab), array('class' => trim($liclass)));
4102                  $cnt++;
4103              }
4104              $str .= html_writer::end_tag('ul');
4105          }
4106  
4107          return $str;
4108      }
4109  
4110      /**
4111       * Get the HTML for blocks in the given region.
4112       *
4113       * @since Moodle 2.5.1 2.6
4114       * @param string $region The region to get HTML for.
4115       * @param array $classes Wrapping tag classes.
4116       * @param string $tag Wrapping tag.
4117       * @param boolean $fakeblocksonly Include fake blocks only.
4118       * @return string HTML.
4119       */
4120      public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
4121          $displayregion = $this->page->apply_theme_region_manipulations($region);
4122          $classes = (array)$classes;
4123          $classes[] = 'block-region';
4124          $attributes = array(
4125              'id' => 'block-region-'.preg_replace('#[^a-zA-Z0-9_\-]+#', '-', $displayregion),
4126              'class' => join(' ', $classes),
4127              'data-blockregion' => $displayregion,
4128              'data-droptarget' => '1'
4129          );
4130          if ($this->page->blocks->region_has_content($displayregion, $this)) {
4131              $content = $this->blocks_for_region($displayregion, $fakeblocksonly);
4132          } else {
4133              $content = '';
4134          }
4135          return html_writer::tag($tag, $content, $attributes);
4136      }
4137  
4138      /**
4139       * Renders a custom block region.
4140       *
4141       * Use this method if you want to add an additional block region to the content of the page.
4142       * Please note this should only be used in special situations.
4143       * We want to leave the theme is control where ever possible!
4144       *
4145       * This method must use the same method that the theme uses within its layout file.
4146       * As such it asks the theme what method it is using.
4147       * It can be one of two values, blocks or blocks_for_region (deprecated).
4148       *
4149       * @param string $regionname The name of the custom region to add.
4150       * @return string HTML for the block region.
4151       */
4152      public function custom_block_region($regionname) {
4153          if ($this->page->theme->get_block_render_method() === 'blocks') {
4154              return $this->blocks($regionname);
4155          } else {
4156              return $this->blocks_for_region($regionname);
4157          }
4158      }
4159  
4160      /**
4161       * Returns the CSS classes to apply to the body tag.
4162       *
4163       * @since Moodle 2.5.1 2.6
4164       * @param array $additionalclasses Any additional classes to apply.
4165       * @return string
4166       */
4167      public function body_css_classes(array $additionalclasses = array()) {
4168          return $this->page->bodyclasses . ' ' . implode(' ', $additionalclasses);
4169      }
4170  
4171      /**
4172       * The ID attribute to apply to the body tag.
4173       *
4174       * @since Moodle 2.5.1 2.6
4175       * @return string
4176       */
4177      public function body_id() {
4178          return $this->page->bodyid;
4179      }
4180  
4181      /**
4182       * Returns HTML attributes to use within the body tag. This includes an ID and classes.
4183       *
4184       * @since Moodle 2.5.1 2.6
4185       * @param string|array $additionalclasses Any additional classes to give the body tag,
4186       * @return string
4187       */
4188      public function body_attributes($additionalclasses = array()) {
4189          if (!is_array($additionalclasses)) {
4190              $additionalclasses = explode(' ', $additionalclasses);
4191          }
4192          return ' id="'. $this->body_id().'" class="'.$this->body_css_classes($additionalclasses).'"';
4193      }
4194  
4195      /**
4196       * Gets HTML for the page heading.
4197       *
4198       * @since Moodle 2.5.1 2.6
4199       * @param string $tag The tag to encase the heading in. h1 by default.
4200       * @return string HTML.
4201       */
4202      public function page_heading($tag = 'h1') {
4203          return html_writer::tag($tag, $this->page->heading);
4204      }
4205  
4206      /**
4207       * Gets the HTML for the page heading button.
4208       *
4209       * @since Moodle 2.5.1 2.6
4210       * @return string HTML.
4211       */
4212      public function page_heading_button() {
4213          return $this->page->button;
4214      }
4215  
4216      /**
4217       * Returns the Moodle docs link to use for this page.
4218       *
4219       * @since Moodle 2.5.1 2.6
4220       * @param string $text
4221       * @return string
4222       */
4223      public function page_doc_link($text = null) {
4224          if ($text === null) {
4225              $text = get_string('moodledocslink');
4226          }
4227          $path = page_get_doc_link_path($this->page);
4228          if (!$path) {
4229              return '';
4230          }
4231          return $this->doc_link($path, $text);
4232      }
4233  
4234      /**
4235       * Returns the HTML for the site support email link
4236       *
4237       * @param array $customattribs Array of custom attributes for the support email anchor tag.
4238       * @return string The html code for the support email link.
4239       */
4240      public function supportemail(array $customattribs = []): string {
4241          global $CFG;
4242  
4243          // Do not provide a link to contact site support if it is unavailable to this user. This would be where the site has
4244          // disabled support, or limited it to authenticated users and the current user is a guest or not logged in.
4245          if (!isset($CFG->supportavailability) ||
4246                  $CFG->supportavailability == CONTACT_SUPPORT_DISABLED ||
4247                  ($CFG->supportavailability == CONTACT_SUPPORT_AUTHENTICATED && (!isloggedin() || isguestuser()))) {
4248              return '';
4249          }
4250  
4251          $label = get_string('contactsitesupport', 'admin');
4252          $icon = $this->pix_icon('t/email', '');
4253          $content = $icon . $label;
4254  
4255          if (!empty($CFG->supportpage)) {
4256              $attributes = ['href' => $CFG->supportpage, 'target' => 'blank'];
4257              $content .= $this->pix_icon('i/externallink', '', 'moodle', ['class' => 'ml-1']);
4258          } else {
4259              $attributes = ['href' => $CFG->wwwroot . '/user/contactsitesupport.php'];
4260          }
4261  
4262          $attributes += $customattribs;
4263  
4264          return html_writer::tag('a', $content, $attributes);
4265      }
4266  
4267      /**
4268       * Returns the services and support link for the help pop-up.
4269       *
4270       * @return string
4271       */
4272      public function services_support_link(): string {
4273          global $CFG;
4274  
4275          if (during_initial_install() ||
4276              (isset($CFG->showservicesandsupportcontent) && $CFG->showservicesandsupportcontent == false) ||
4277              !is_siteadmin()) {
4278              return '';
4279          }
4280  
4281          $liferingicon = $this->pix_icon('t/life-ring', '', 'moodle', ['class' => 'fa fa-life-ring']);
4282          $newwindowicon = $this->pix_icon('i/externallink', get_string('opensinnewwindow'), 'moodle', ['class' => 'ml-1']);
4283          $link = !empty($CFG->servicespage)
4284              ? $CFG->servicespage
4285              : 'https://moodle.com/help/?utm_source=CTA-banner&utm_medium=platform&utm_campaign=name~Moodle4+cat~lms+mp~no';
4286          $content = $liferingicon . get_string('moodleservicesandsupport') . $newwindowicon;
4287  
4288          return html_writer::tag('a', $content, ['target' => '_blank', 'href' => $link]);
4289      }
4290  
4291      /**
4292       * Helper function to decide whether to show the help popover header or not.
4293       *
4294       * @return bool
4295       */
4296      public function has_popover_links(): bool {
4297          return !empty($this->services_support_link()) || !empty($this->page_doc_link()) || !empty($this->supportemail());
4298      }
4299  
4300      /**
4301       * Returns the page heading menu.
4302       *
4303       * @since Moodle 2.5.1 2.6
4304       * @return string HTML.
4305       */
4306      public function page_heading_menu() {
4307          return $this->page->headingmenu;
4308      }
4309  
4310      /**
4311       * Returns the title to use on the page.
4312       *
4313       * @since Moodle 2.5.1 2.6
4314       * @return string
4315       */
4316      public function page_title() {
4317          return $this->page->title;
4318      }
4319  
4320      /**
4321       * Returns the moodle_url for the favicon.
4322       *
4323       * @since Moodle 2.5.1 2.6
4324       * @return moodle_url The moodle_url for the favicon
4325       */
4326      public function favicon() {
4327          $logo = null;
4328          if (!during_initial_install()) {
4329              $logo = get_config('core_admin', 'favicon');
4330          }
4331          if (empty($logo)) {
4332              return $this->image_url('favicon', 'theme');
4333          }
4334  
4335          // Use $CFG->themerev to prevent browser caching when the file changes.
4336          return moodle_url::make_pluginfile_url(context_system::instance()->id, 'core_admin', 'favicon', '64x64/',
4337              theme_get_revision(), $logo);
4338      }
4339  
4340      /**
4341       * Renders preferences groups.
4342       *
4343       * @param  preferences_groups $renderable The renderable
4344       * @return string The output.
4345       */
4346      public function render_preferences_groups(preferences_groups $renderable) {
4347          return $this->render_from_template('core/preferences_groups', $renderable);
4348      }
4349  
4350      /**
4351       * Renders preferences group.
4352       *
4353       * @param  preferences_group $renderable The renderable
4354       * @return string The output.
4355       */
4356      public function render_preferences_group(preferences_group $renderable) {
4357          $html = '';
4358          $html .= html_writer::start_tag('div', array('class' => 'col-sm-4 preferences-group'));
4359          $html .= $this->heading($renderable->title, 3);
4360          $html .= html_writer::start_tag('ul');
4361          foreach ($renderable->nodes as $node) {
4362              if ($node->has_children()) {
4363                  debugging('Preferences nodes do not support children', DEBUG_DEVELOPER);
4364              }
4365              $html .= html_writer::tag('li', $this->render($node));
4366          }
4367          $html .= html_writer::end_tag('ul');
4368          $html .= html_writer::end_tag('div');
4369          return $html;
4370      }
4371  
4372      public function context_header($headerinfo = null, $headinglevel = 1) {
4373          global $DB, $USER, $CFG, $SITE;
4374          require_once($CFG->dirroot . '/user/lib.php');
4375          $context = $this->page->context;
4376          $heading = null;
4377          $imagedata = null;
4378          $subheader = null;
4379          $userbuttons = null;
4380  
4381          // Make sure to use the heading if it has been set.
4382          if (isset($headerinfo['heading'])) {
4383              $heading = $headerinfo['heading'];
4384          } else {
4385              $heading = $this->page->heading;
4386          }
4387  
4388          // The user context currently has images and buttons. Other contexts may follow.
4389          if ((isset($headerinfo['user']) || $context->contextlevel == CONTEXT_USER) && $this->page->pagetype !== 'my-index') {
4390              if (isset($headerinfo['user'])) {
4391                  $user = $headerinfo['user'];
4392              } else {
4393                  // Look up the user information if it is not supplied.
4394                  $user = $DB->get_record('user', array('id' => $context->instanceid));
4395              }
4396  
4397              // If the user context is set, then use that for capability checks.
4398              if (isset($headerinfo['usercontext'])) {
4399                  $context = $headerinfo['usercontext'];
4400              }
4401  
4402              // Only provide user information if the user is the current user, or a user which the current user can view.
4403              // When checking user_can_view_profile(), either:
4404              // If the page context is course, check the course context (from the page object) or;
4405              // If page context is NOT course, then check across all courses.
4406              $course = ($this->page->context->contextlevel == CONTEXT_COURSE) ? $this->page->course : null;
4407  
4408              if (user_can_view_profile($user, $course)) {
4409                  // Use the user's full name if the heading isn't set.
4410                  if (empty($heading)) {
4411                      $heading = fullname($user);
4412                  }
4413  
4414                  $imagedata = $this->user_picture($user, array('size' => 100));
4415  
4416                  // Check to see if we should be displaying a message button.
4417                  if (!empty($CFG->messaging) && has_capability('moodle/site:sendmessage', $context)) {
4418                      $userbuttons = array(
4419                          'messages' => array(
4420                              'buttontype' => 'message',
4421                              'title' => get_string('message', 'message'),
4422                              'url' => new moodle_url('/message/index.php', array('id' => $user->id)),
4423                              'image' => 'message',
4424                              'linkattributes' => \core_message\helper::messageuser_link_params($user->id),
4425                              'page' => $this->page
4426                          )
4427                      );
4428  
4429                      if ($USER->id != $user->id) {
4430                          $iscontact = \core_message\api::is_contact($USER->id, $user->id);
4431                          $contacttitle = $iscontact ? 'removefromyourcontacts' : 'addtoyourcontacts';
4432                          $contacturlaction = $iscontact ? 'removecontact' : 'addcontact';
4433                          $contactimage = $iscontact ? 'removecontact' : 'addcontact';
4434                          $userbuttons['togglecontact'] = array(
4435                                  'buttontype' => 'togglecontact',
4436                                  'title' => get_string($contacttitle, 'message'),
4437                                  'url' => new moodle_url('/message/index.php', array(
4438                                          'user1' => $USER->id,
4439                                          'user2' => $user->id,
4440                                          $contacturlaction => $user->id,
4441                                          'sesskey' => sesskey())
4442                                  ),
4443                                  'image' => $contactimage,
4444                                  'linkattributes' => \core_message\helper::togglecontact_link_params($user, $iscontact),
4445                                  'page' => $this->page
4446                              );
4447                      }
4448                  }
4449              } else {
4450                  $heading = null;
4451              }
4452          }
4453  
4454  
4455          $contextheader = new context_header($heading, $headinglevel, $imagedata, $userbuttons);
4456          return $this->render_context_header($contextheader);
4457      }
4458  
4459      /**
4460       * Renders the skip links for the page.
4461       *
4462       * @param array $links List of skip links.
4463       * @return string HTML for the skip links.
4464       */
4465      public function render_skip_links($links) {
4466          $context = [ 'links' => []];
4467  
4468          foreach ($links as $url => $text) {
4469              $context['links'][] = [ 'url' => $url, 'text' => $text];
4470          }
4471  
4472          return $this->render_from_template('core/skip_links', $context);
4473      }
4474  
4475       /**
4476        * Renders the header bar.
4477        *
4478        * @param context_header $contextheader Header bar object.
4479        * @return string HTML for the header bar.
4480        */
4481      protected function render_context_header(context_header $contextheader) {
4482  
4483          // Generate the heading first and before everything else as we might have to do an early return.
4484          if (!isset($contextheader->heading)) {
4485              $heading = $this->heading($this->page->heading, $contextheader->headinglevel);
4486          } else {
4487              $heading = $this->heading($contextheader->heading, $contextheader->headinglevel);
4488          }
4489  
4490          $showheader = empty($this->page->layout_options['nocontextheader']);
4491          if (!$showheader) {
4492              // Return the heading wrapped in an sr-only element so it is only visible to screen-readers.
4493              return html_writer::div($heading, 'sr-only');
4494          }
4495  
4496          // All the html stuff goes here.
4497          $html = html_writer::start_div('page-context-header');
4498  
4499          // Image data.
4500          if (isset($contextheader->imagedata)) {
4501              // Header specific image.
4502              $html .= html_writer::div($contextheader->imagedata, 'page-header-image icon-size-7');
4503          }
4504  
4505          // Headings.
4506          if (isset($contextheader->prefix)) {
4507              $prefix = html_writer::div($contextheader->prefix, 'text-muted');
4508              $heading = $prefix . $heading;
4509          }
4510          $html .= html_writer::tag('div', $heading, array('class' => 'page-header-headings'));
4511  
4512          // Buttons.
4513          if (isset($contextheader->additionalbuttons)) {
4514              $html .= html_writer::start_div('btn-group header-button-group');
4515              foreach ($contextheader->additionalbuttons as $button) {
4516                  if (!isset($button->page)) {
4517                      // Include js for messaging.
4518                      if ($button['buttontype'] === 'togglecontact') {
4519                          \core_message\helper::togglecontact_requirejs();
4520                      }
4521                      if ($button['buttontype'] === 'message') {
4522                          \core_message\helper::messageuser_requirejs();
4523                      }
4524                      $image = $this->pix_icon($button['formattedimage'], $button['title'], 'moodle', array(
4525                          'class' => 'iconsmall',
4526                          'role' => 'presentation'
4527                      ));
4528                      $image .= html_writer::span($button['title'], 'header-button-title');
4529                  } else {
4530                      $image = html_writer::empty_tag('img', array(
4531                          'src' => $button['formattedimage'],
4532                          'role' => 'presentation'
4533                      ));
4534                  }
4535                  $html .= html_writer::link($button['url'], html_writer::tag('span', $image), $button['linkattributes']);
4536              }
4537              $html .= html_writer::end_div();
4538          }
4539          $html .= html_writer::end_div();
4540  
4541          return $html;
4542      }
4543  
4544      /**
4545       * Wrapper for header elements.
4546       *
4547       * @return string HTML to display the main header.
4548       */
4549      public function full_header() {
4550          $pagetype = $this->page->pagetype;
4551          $homepage = get_home_page();
4552          $homepagetype = null;
4553          // Add a special case since /my/courses is a part of the /my subsystem.
4554          if ($homepage == HOMEPAGE_MY || $homepage == HOMEPAGE_MYCOURSES) {
4555              $homepagetype = 'my-index';
4556          } else if ($homepage == HOMEPAGE_SITE) {
4557              $homepagetype = 'site-index';
4558          }
4559          if ($this->page->include_region_main_settings_in_header_actions() &&
4560                  !$this->page->blocks->is_block_present('settings')) {
4561              // Only include the region main settings if the page has requested it and it doesn't already have
4562              // the settings block on it. The region main settings are included in the settings block and
4563              // duplicating the content causes behat failures.
4564              $this->page->add_header_action(html_writer::div(
4565                  $this->region_main_settings_menu(),
4566                  'd-print-none',
4567                  ['id' => 'region-main-settings-menu']
4568              ));
4569          }
4570  
4571          $header = new stdClass();
4572          $header->settingsmenu = $this->context_header_settings_menu();
4573          $header->contextheader = $this->context_header();
4574          $header->hasnavbar = empty($this->page->layout_options['nonavbar']);
4575          $header->navbar = $this->navbar();
4576          $header->pageheadingbutton = $this->page_heading_button();
4577          $header->courseheader = $this->course_header();
4578          $header->headeractions = $this->page->get_header_actions();
4579          if (!empty($pagetype) && !empty($homepagetype) && $pagetype == $homepagetype) {
4580              $header->welcomemessage = \core_user::welcome_message();
4581          }
4582          return $this->render_from_template('core/full_header', $header);
4583      }
4584  
4585      /**
4586       * This is an optional menu that can be added to a layout by a theme. It contains the
4587       * menu for the course administration, only on the course main page.
4588       *
4589       * @return string
4590       */
4591      public function context_header_settings_menu() {
4592          $context = $this->page->context;
4593          $menu = new action_menu();
4594  
4595          $items = $this->page->navbar->get_items();
4596          $currentnode = end($items);
4597  
4598          $showcoursemenu = false;
4599          $showfrontpagemenu = false;
4600          $showusermenu = false;
4601  
4602          // We are on the course home page.
4603          if (($context->contextlevel == CONTEXT_COURSE) &&
4604                  !empty($currentnode) &&
4605                  ($currentnode->type == navigation_node::TYPE_COURSE || $currentnode->type == navigation_node::TYPE_SECTION)) {
4606              $showcoursemenu = true;
4607          }
4608  
4609          $courseformat = course_get_format($this->page->course);
4610          // This is a single activity course format, always show the course menu on the activity main page.
4611          if ($context->contextlevel == CONTEXT_MODULE &&
4612                  !$courseformat->has_view_page()) {
4613  
4614              $this->page->navigation->initialise();
4615              $activenode = $this->page->navigation->find_active_node();
4616              // If the settings menu has been forced then show the menu.
4617              if ($this->page->is_settings_menu_forced()) {
4618                  $showcoursemenu = true;
4619              } else if (!empty($activenode) && ($activenode->type == navigation_node::TYPE_ACTIVITY ||
4620                              $activenode->type == navigation_node::TYPE_RESOURCE)) {
4621  
4622                  // We only want to show the menu on the first page of the activity. This means
4623                  // the breadcrumb has no additional nodes.
4624                  if ($currentnode && ($currentnode->key == $activenode->key && $currentnode->type == $activenode->type)) {
4625                      $showcoursemenu = true;
4626                  }
4627              }
4628          }
4629  
4630          // This is the site front page.
4631          if ($context->contextlevel == CONTEXT_COURSE &&
4632                  !empty($currentnode) &&
4633                  $currentnode->key === 'home') {
4634              $showfrontpagemenu = true;
4635          }
4636  
4637          // This is the user profile page.
4638          if ($context->contextlevel == CONTEXT_USER &&
4639                  !empty($currentnode) &&
4640                  ($currentnode->key === 'myprofile')) {
4641              $showusermenu = true;
4642          }
4643  
4644          if ($showfrontpagemenu) {
4645              $settingsnode = $this->page->settingsnav->find('frontpage', navigation_node::TYPE_SETTING);
4646              if ($settingsnode) {
4647                  // Build an action menu based on the visible nodes from this navigation tree.
4648                  $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4649  
4650                  // We only add a list to the full settings menu if we didn't include every node in the short menu.
4651                  if ($skipped) {
4652                      $text = get_string('morenavigationlinks');
4653                      $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4654                      $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4655                      $menu->add_secondary_action($link);
4656                  }
4657              }
4658          } else if ($showcoursemenu) {
4659              $settingsnode = $this->page->settingsnav->find('courseadmin', navigation_node::TYPE_COURSE);
4660              if ($settingsnode) {
4661                  // Build an action menu based on the visible nodes from this navigation tree.
4662                  $skipped = $this->build_action_menu_from_navigation($menu, $settingsnode, false, true);
4663  
4664                  // We only add a list to the full settings menu if we didn't include every node in the short menu.
4665                  if ($skipped) {
4666                      $text = get_string('morenavigationlinks');
4667                      $url = new moodle_url('/course/admin.php', array('courseid' => $this->page->course->id));
4668                      $link = new action_link($url, $text, null, null, new pix_icon('t/edit', $text));
4669                      $menu->add_secondary_action($link);
4670                  }
4671              }
4672          } else if ($showusermenu) {
4673              // Get the course admin node from the settings navigation.
4674              $settingsnode = $this->page->settingsnav->find('useraccount', navigation_node::TYPE_CONTAINER);
4675              if ($settingsnode) {
4676                  // Build an action menu based on the visible nodes from this navigation tree.
4677                  $this->build_action_menu_from_navigation($menu, $settingsnode);
4678              }
4679          }
4680  
4681          return $this->render($menu);
4682      }
4683  
4684      /**
4685       * Take a node in the nav tree and make an action menu out of it.
4686       * The links are injected in the action menu.
4687       *
4688       * @param action_menu $menu
4689       * @param navigation_node $node
4690       * @param boolean $indent
4691       * @param boolean $onlytopleafnodes
4692       * @return boolean nodesskipped - True if nodes were skipped in building the menu
4693       */
4694      protected function build_action_menu_from_navigation(action_menu $menu,
4695              navigation_node $node,
4696              $indent = false,
4697              $onlytopleafnodes = false) {
4698          $skipped = false;
4699          // Build an action menu based on the visible nodes from this navigation tree.
4700          foreach ($node->children as $menuitem) {
4701              if ($menuitem->display) {
4702                  if ($onlytopleafnodes && $menuitem->children->count()) {
4703                      $skipped = true;
4704                      continue;
4705                  }
4706                  if ($menuitem->action) {
4707                      if ($menuitem->action instanceof action_link) {
4708                          $link = $menuitem->action;
4709                          // Give preference to setting icon over action icon.
4710                          if (!empty($menuitem->icon)) {
4711                              $link->icon = $menuitem->icon;
4712                          }
4713                      } else {
4714                          $link = new action_link($menuitem->action, $menuitem->text, null, null, $menuitem->icon);
4715                      }
4716                  } else {
4717                      if ($onlytopleafnodes) {
4718                          $skipped = true;
4719                          continue;
4720                      }
4721                      $link = new action_link(new moodle_url('#'), $menuitem->text, null, ['disabled' => true], $menuitem->icon);
4722                  }
4723                  if ($indent) {
4724                      $link->add_class('ml-4');
4725                  }
4726                  if (!empty($menuitem->classes)) {
4727                      $link->add_class(implode(" ", $menuitem->classes));
4728                  }
4729  
4730                  $menu->add_secondary_action($link);
4731                  $skipped = $skipped || $this->build_action_menu_from_navigation($menu, $menuitem, true);
4732              }
4733          }
4734          return $skipped;
4735      }
4736  
4737      /**
4738       * This is an optional menu that can be added to a layout by a theme. It contains the
4739       * menu for the most specific thing from the settings block. E.g. Module administration.
4740       *
4741       * @return string
4742       */
4743      public function region_main_settings_menu() {
4744          $context = $this->page->context;
4745          $menu = new action_menu();
4746  
4747          if ($context->contextlevel == CONTEXT_MODULE) {
4748  
4749              $this->page->navigation->initialise();
4750              $node = $this->page->navigation->find_active_node();
4751              $buildmenu = false;
4752              // If the settings menu has been forced then show the menu.
4753              if ($this->page->is_settings_menu_forced()) {
4754                  $buildmenu = true;
4755              } else if (!empty($node) && ($node->type == navigation_node::TYPE_ACTIVITY ||
4756                              $node->type == navigation_node::TYPE_RESOURCE)) {
4757  
4758                  $items = $this->page->navbar->get_items();
4759                  $navbarnode = end($items);
4760                  // We only want to show the menu on the first page of the activity. This means
4761                  // the breadcrumb has no additional nodes.
4762                  if ($navbarnode && ($navbarnode->key === $node->key && $navbarnode->type == $node->type)) {
4763                      $buildmenu = true;
4764                  }
4765              }
4766              if ($buildmenu) {
4767                  // Get the course admin node from the settings navigation.
4768                  $node = $this->page->settingsnav->find('modulesettings', navigation_node::TYPE_SETTING);
4769                  if ($node) {
4770                      // Build an action menu based on the visible nodes from this navigation tree.
4771                      $this->build_action_menu_from_navigation($menu, $node);
4772                  }
4773              }
4774  
4775          } else if ($context->contextlevel == CONTEXT_COURSECAT) {
4776              // For course category context, show category settings menu, if we're on the course category page.
4777              if ($this->page->pagetype === 'course-index-category') {
4778                  $node = $this->page->settingsnav->find('categorysettings', navigation_node::TYPE_CONTAINER);
4779                  if ($node) {
4780                      // Build an action menu based on the visible nodes from this navigation tree.
4781                      $this->build_action_menu_from_navigation($menu, $node);
4782                  }
4783              }
4784  
4785          } else {
4786              $items = $this->page->navbar->get_items();
4787              $navbarnode = end($items);
4788  
4789              if ($navbarnode && ($navbarnode->key === 'participants')) {
4790                  $node = $this->page->settingsnav->find('users', navigation_node::TYPE_CONTAINER);
4791                  if ($node) {
4792                      // Build an action menu based on the visible nodes from this navigation tree.
4793                      $this->build_action_menu_from_navigation($menu, $node);
4794                  }
4795  
4796              }
4797          }
4798          return $this->render($menu);
4799      }
4800  
4801      /**
4802       * Displays the list of tags associated with an entry
4803       *
4804       * @param array $tags list of instances of core_tag or stdClass
4805       * @param string $label label to display in front, by default 'Tags' (get_string('tags')), set to null
4806       *               to use default, set to '' (empty string) to omit the label completely
4807       * @param string $classes additional classes for the enclosing div element
4808       * @param int $limit limit the number of tags to display, if size of $tags is more than this limit the "more" link
4809       *               will be appended to the end, JS will toggle the rest of the tags
4810       * @param context $pagecontext specify if needed to overwrite the current page context for the view tag link
4811       * @param bool $accesshidelabel if true, the label should have class="accesshide" added.
4812       * @return string
4813       */
4814      public function tag_list($tags, $label = null, $classes = '', $limit = 10,
4815              $pagecontext = null, $accesshidelabel = false) {
4816          $list = new \core_tag\output\taglist($tags, $label, $classes, $limit, $pagecontext, $accesshidelabel);
4817          return $this->render_from_template('core_tag/taglist', $list->export_for_template($this));
4818      }
4819  
4820      /**
4821       * Renders element for inline editing of any value
4822       *
4823       * @param \core\output\inplace_editable $element
4824       * @return string
4825       */
4826      public function render_inplace_editable(\core\output\inplace_editable $element) {
4827          return $this->render_from_template('core/inplace_editable', $element->export_for_template($this));
4828      }
4829  
4830      /**
4831       * Renders a bar chart.
4832       *
4833       * @param \core\chart_bar $chart The chart.
4834       * @return string
4835       */
4836      public function render_chart_bar(\core\chart_bar $chart) {
4837          return $this->render_chart($chart);
4838      }
4839  
4840      /**
4841       * Renders a line chart.
4842       *
4843       * @param \core\chart_line $chart The chart.
4844       * @return string
4845       */
4846      public function render_chart_line(\core\chart_line $chart) {
4847          return $this->render_chart($chart);
4848      }
4849  
4850      /**
4851       * Renders a pie chart.
4852       *
4853       * @param \core\chart_pie $chart The chart.
4854       * @return string
4855       */
4856      public function render_chart_pie(\core\chart_pie $chart) {
4857          return $this->render_chart($chart);
4858      }
4859  
4860      /**
4861       * Renders a chart.
4862       *
4863       * @param \core\chart_base $chart The chart.
4864       * @param bool $withtable Whether to include a data table with the chart.
4865       * @return string
4866       */
4867      public function render_chart(\core\chart_base $chart, $withtable = true) {
4868          $chartdata = json_encode($chart);
4869          return $this->render_from_template('core/chart', (object) [
4870              'chartdata' => $chartdata,
4871              'withtable' => $withtable
4872          ]);
4873      }
4874  
4875      /**
4876       * Renders the login form.
4877       *
4878       * @param \core_auth\output\login $form The renderable.
4879       * @return string
4880       */
4881      public function render_login(\core_auth\output\login $form) {
4882          global $CFG, $SITE;
4883  
4884          $context = $form->export_for_template($this);
4885  
4886          $context->errorformatted = $this->error_text($context->error);
4887          $url = $this->get_logo_url();
4888          if ($url) {
4889              $url = $url->out(false);
4890          }
4891          $context->logourl = $url;
4892          $context->sitename = format_string($SITE->fullname, true,
4893                  ['context' => context_course::instance(SITEID), "escape" => false]);
4894  
4895          return $this->render_from_template('core/loginform', $context);
4896      }
4897  
4898      /**
4899       * Renders an mform element from a template.
4900       *
4901       * @param HTML_QuickForm_element $element element
4902       * @param bool $required if input is required field
4903       * @param bool $advanced if input is an advanced field
4904       * @param string $error error message to display
4905       * @param bool $ingroup True if this element is rendered as part of a group
4906       * @return mixed string|bool
4907       */
4908      public function mform_element($element, $required, $advanced, $error, $ingroup) {
4909          $templatename = 'core_form/element-' . $element->getType();
4910          if ($ingroup) {
4911              $templatename .= "-inline";
4912          }
4913          try {
4914              // We call this to generate a file not found exception if there is no template.
4915              // We don't want to call export_for_template if there is no template.
4916              core\output\mustache_template_finder::get_template_filepath($templatename);
4917  
4918              if ($element instanceof templatable) {
4919                  $elementcontext = $element->export_for_template($this);
4920  
4921                  $helpbutton = '';
4922                  if (method_exists($element, 'getHelpButton')) {
4923                      $helpbutton = $element->getHelpButton();
4924                  }
4925                  $label = $element->getLabel();
4926                  $text = '';
4927                  if (method_exists($element, 'getText')) {
4928                      // There currently exists code that adds a form element with an empty label.
4929                      // If this is the case then set the label to the description.
4930                      if (empty($label)) {
4931                          $label = $element->getText();
4932                      } else {
4933                          $text = $element->getText();
4934                      }
4935                  }
4936  
4937                  // Generate the form element wrapper ids and names to pass to the template.
4938                  // This differs between group and non-group elements.
4939                  if ($element->getType() === 'group') {
4940                      // Group element.
4941                      // The id will be something like 'fgroup_id_NAME'. E.g. fgroup_id_mygroup.
4942                      $elementcontext['wrapperid'] = $elementcontext['id'];
4943  
4944                      // Ensure group elements pass through the group name as the element name.
4945                      $elementcontext['name'] = $elementcontext['groupname'];
4946                  } else {
4947                      // Non grouped element.
4948                      // Creates an id like 'fitem_id_NAME'. E.g. fitem_id_mytextelement.
4949                      $elementcontext['wrapperid'] = 'fitem_' . $elementcontext['id'];
4950                  }
4951  
4952                  $context = array(
4953                      'element' => $elementcontext,
4954                      'label' => $label,
4955                      'text' => $text,
4956                      'required' => $required,
4957                      'advanced' => $advanced,
4958                      'helpbutton' => $helpbutton,
4959                      'error' => $error
4960                  );
4961                  return $this->render_from_template($templatename, $context);
4962              }
4963          } catch (Exception $e) {
4964              // No template for this element.
4965              return false;
4966          }
4967      }
4968  
4969      /**
4970       * Render the login signup form into a nice template for the theme.
4971       *
4972       * @param mform $form
4973       * @return string
4974       */
4975      public function render_login_signup_form($form) {
4976          global $SITE;
4977  
4978          $context = $form->export_for_template($this);
4979          $url = $this->get_logo_url();
4980          if ($url) {
4981              $url = $url->out(false);
4982          }
4983          $context['logourl'] = $url;
4984          $context['sitename'] = format_string($SITE->fullname, true,
4985                  ['context' => context_course::instance(SITEID), "escape" => false]);
4986  
4987          return $this->render_from_template('core/signup_form_layout', $context);
4988      }
4989  
4990      /**
4991       * Render the verify age and location page into a nice template for the theme.
4992       *
4993       * @param \core_auth\output\verify_age_location_page $page The renderable
4994       * @return string
4995       */
4996      protected function render_verify_age_location_page($page) {
4997          $context = $page->export_for_template($this);
4998  
4999          return $this->render_from_template('core/auth_verify_age_location_page', $context);
5000      }
5001  
5002      /**
5003       * Render the digital minor contact information page into a nice template for the theme.
5004       *
5005       * @param \core_auth\output\digital_minor_page $page The renderable
5006       * @return string
5007       */
5008      protected function render_digital_minor_page($page) {
5009          $context = $page->export_for_template($this);
5010  
5011          return $this->render_from_template('core/auth_digital_minor_page', $context);
5012      }
5013  
5014      /**
5015       * Renders a progress bar.
5016       *
5017       * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5018       *
5019       * @param  progress_bar $bar The bar.
5020       * @return string HTML fragment
5021       */
5022      public function render_progress_bar(progress_bar $bar) {
5023          $data = $bar->export_for_template($this);
5024          return $this->render_from_template('core/progress_bar', $data);
5025      }
5026  
5027      /**
5028       * Renders an update to a progress bar.
5029       *
5030       * Note: This does not cleanly map to a renderable class and should
5031       * never be used directly.
5032       *
5033       * @param  string $id
5034       * @param  float $percent
5035       * @param  string $msg Message
5036       * @param  string $estimate time remaining message
5037       * @return string ascii fragment
5038       */
5039      public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
5040          return html_writer::script(js_writer::function_call('updateProgressBar', [$id, $percent, $msg, $estimate]));
5041      }
5042  
5043      /**
5044       * Renders element for a toggle-all checkbox.
5045       *
5046       * @param \core\output\checkbox_toggleall $element
5047       * @return string
5048       */
5049      public function render_checkbox_toggleall(\core\output\checkbox_toggleall $element) {
5050          return $this->render_from_template($element->get_template(), $element->export_for_template($this));
5051      }
5052  
5053      /**
5054       * Renders the tertiary nav for the participants page
5055       *
5056       * @param object $course The course we are operating within
5057       * @param string|null $renderedbuttons Any additional buttons/content to be displayed in line with the nav
5058       * @return string
5059       */
5060      public function render_participants_tertiary_nav(object $course, ?string $renderedbuttons = null) {
5061          $actionbar = new \core\output\participants_action_bar($course, $this->page, $renderedbuttons);
5062          $content = $this->render_from_template('core_course/participants_actionbar', $actionbar->export_for_template($this));
5063          return $content ?: "";
5064      }
5065  
5066      /**
5067       * Renders release information in the footer popup
5068       * @return string Moodle release info.
5069       */
5070      public function moodle_release() {
5071          global $CFG;
5072          if (!during_initial_install() && is_siteadmin()) {
5073              return $CFG->release;
5074          }
5075      }
5076  
5077      /**
5078       * Generate the add block button when editing mode is turned on and the user can edit blocks.
5079       *
5080       * @param string $region where new blocks should be added.
5081       * @return string html for the add block button.
5082       */
5083      public function addblockbutton($region = ''): string {
5084          $addblockbutton = '';
5085          $regions = $this->page->blocks->get_regions();
5086          if (count($regions) == 0) {
5087              return '';
5088          }
5089          if (isset($this->page->theme->addblockposition) &&
5090                  $this->page->user_is_editing() &&
5091                  $this->page->user_can_edit_blocks() &&
5092                  $this->page->pagelayout !== 'mycourses'
5093          ) {
5094              $params = ['bui_addblock' => '', 'sesskey' => sesskey()];
5095              if (!empty($region)) {
5096                  $params['bui_blockregion'] = $region;
5097              }
5098              $url = new moodle_url($this->page->url, $params);
5099              $addblockbutton = $this->render_from_template('core/add_block_button',
5100                  [
5101                      'link' => $url->out(false),
5102                      'escapedlink' => "?{$url->get_query_string(false)}",
5103                      'pagehash' => $this->page->get_edited_page_hash(),
5104                      'blockregion' => $region,
5105                      // The following parameters are not used since Moodle 4.2 but are
5106                      // still passed for backward-compatibility.
5107                      'pageType' => $this->page->pagetype,
5108                      'pageLayout' => $this->page->pagelayout,
5109                      'subPage' => $this->page->subpage,
5110                  ]
5111              );
5112          }
5113          return $addblockbutton;
5114      }
5115  }
5116  
5117  /**
5118   * A renderer that generates output for command-line scripts.
5119   *
5120   * The implementation of this renderer is probably incomplete.
5121   *
5122   * @copyright 2009 Tim Hunt
5123   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5124   * @since Moodle 2.0
5125   * @package core
5126   * @category output
5127   */
5128  class core_renderer_cli extends core_renderer {
5129  
5130      /**
5131       * @var array $progressmaximums stores the largest percentage for a progress bar.
5132       * @return string ascii fragment
5133       */
5134      private $progressmaximums = [];
5135  
5136      /**
5137       * Returns the page header.
5138       *
5139       * @return string HTML fragment
5140       */
5141      public function header() {
5142          return $this->page->heading . "\n";
5143      }
5144  
5145      /**
5146       * Renders a Check API result
5147       *
5148       * To aid in CLI consistency this status is NOT translated and the visual
5149       * width is always exactly 10 chars.
5150       *
5151       * @param core\check\result $result
5152       * @return string HTML fragment
5153       */
5154      protected function render_check_result(core\check\result $result) {
5155          $status = $result->get_status();
5156  
5157          $labels = [
5158              core\check\result::NA        => '      ' . cli_ansi_format('<colour:darkGray>' ) . ' NA ',
5159              core\check\result::OK        => '      ' . cli_ansi_format('<colour:green>') . ' OK ',
5160              core\check\result::INFO      => '    '   . cli_ansi_format('<colour:blue>' ) . ' INFO ',
5161              core\check\result::UNKNOWN   => ' '      . cli_ansi_format('<colour:darkGray>' ) . ' UNKNOWN ',
5162              core\check\result::WARNING   => ' '      . cli_ansi_format('<colour:black><bgcolour:yellow>') . ' WARNING ',
5163              core\check\result::ERROR     => '   '    . cli_ansi_format('<bgcolour:red>') . ' ERROR ',
5164              core\check\result::CRITICAL  => ''       . cli_ansi_format('<bgcolour:red>') . ' CRITICAL ',
5165          ];
5166          $string = $labels[$status] . cli_ansi_format('<colour:normal>');
5167          return $string;
5168      }
5169  
5170      /**
5171       * Renders a Check API result
5172       *
5173       * @param result $result
5174       * @return string fragment
5175       */
5176      public function check_result(core\check\result $result) {
5177          return $this->render_check_result($result);
5178      }
5179  
5180      /**
5181       * Renders a progress bar.
5182       *
5183       * Do not use $OUTPUT->render($bar), instead use progress_bar::create().
5184       *
5185       * @param  progress_bar $bar The bar.
5186       * @return string ascii fragment
5187       */
5188      public function render_progress_bar(progress_bar $bar) {
5189          global $CFG;
5190  
5191          $size = 55; // The width of the progress bar in chars.
5192          $ascii = "\n";
5193  
5194          if (stream_isatty(STDOUT)) {
5195              require_once($CFG->libdir.'/clilib.php');
5196  
5197              $ascii .= "[" . str_repeat(' ', $size) . "] 0% \n";
5198              return cli_ansi_format($ascii);
5199          }
5200  
5201          $this->progressmaximums[$bar->get_id()] = 0;
5202          $ascii .= '[';
5203          return $ascii;
5204      }
5205  
5206      /**
5207       * Renders an update to a progress bar.
5208       *
5209       * Note: This does not cleanly map to a renderable class and should
5210       * never be used directly.
5211       *
5212       * @param  string $id
5213       * @param  float $percent
5214       * @param  string $msg Message
5215       * @param  string $estimate time remaining message
5216       * @return string ascii fragment
5217       */
5218      public function render_progress_bar_update(string $id, float $percent, string $msg, string $estimate) : string {
5219          $size = 55; // The width of the progress bar in chars.
5220          $ascii = '';
5221  
5222          // If we are rendering to a terminal then we can safely use ansii codes
5223          // to move the cursor and redraw the complete progress bar each time
5224          // it is updated.
5225          if (stream_isatty(STDOUT)) {
5226              $colour = $percent == 100 ? 'green' : 'blue';
5227  
5228              $done = $percent * $size * 0.01;
5229              $whole = floor($done);
5230              $bar = "<colour:$colour>";
5231              $bar .= str_repeat('█', $whole);
5232  
5233              if ($whole < $size) {
5234                  // By using unicode chars for partial blocks we can have higher
5235                  // precision progress bar.
5236                  $fraction = floor(($done - $whole) * 8);
5237                  $bar .= core_text::substr(' ▏▎▍▌▋▊▉', $fraction, 1);
5238  
5239                  // Fill the rest of the empty bar.
5240                  $bar .= str_repeat(' ', $size - $whole - 1);
5241              }
5242  
5243              $bar .= '<colour:normal>';
5244  
5245              if ($estimate) {
5246                  $estimate = "- $estimate";
5247              }
5248  
5249              $ascii .= '<cursor:up>';
5250              $ascii .= '<cursor:up>';
5251              $ascii .= sprintf("[$bar] %3.1f%% %-22s\n", $percent, $estimate);
5252              $ascii .= sprintf("%-80s\n", $msg);
5253              return cli_ansi_format($ascii);
5254          }
5255  
5256          // If we are not rendering to a tty, ie when piped to another command
5257          // or on windows we need to progressively render the progress bar
5258          // which can only ever go forwards.
5259          $done = round($percent * $size * 0.01);
5260          $delta = max(0, $done - $this->progressmaximums[$id]);
5261  
5262          $ascii .= str_repeat('#', $delta);
5263          if ($percent >= 100 && $delta > 0) {
5264              $ascii .= sprintf("] %3.1f%%\n$msg\n", $percent);
5265          }
5266          $this->progressmaximums[$id] += $delta;
5267          return $ascii;
5268      }
5269  
5270      /**
5271       * Returns a template fragment representing a Heading.
5272       *
5273       * @param string $text The text of the heading
5274       * @param int $level The level of importance of the heading
5275       * @param string $classes A space-separated list of CSS classes
5276       * @param string $id An optional ID
5277       * @return string A template fragment for a heading
5278       */
5279      public function heading($text, $level = 2, $classes = 'main', $id = null) {
5280          $text .= "\n";
5281          switch ($level) {
5282              case 1:
5283                  return '=>' . $text;
5284              case 2:
5285                  return '-->' . $text;
5286              default:
5287                  return $text;
5288          }
5289      }
5290  
5291      /**
5292       * Returns a template fragment representing a fatal error.
5293       *
5294       * @param string $message The message to output
5295       * @param string $moreinfourl URL where more info can be found about the error
5296       * @param string $link Link for the Continue button
5297       * @param array $backtrace The execution backtrace
5298       * @param string $debuginfo Debugging information
5299       * @return string A template fragment for a fatal error
5300       */
5301      public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5302          global $CFG;
5303  
5304          $output = "!!! $message !!!\n";
5305  
5306          if ($CFG->debugdeveloper) {
5307              if (!empty($debuginfo)) {
5308                  $output .= $this->notification($debuginfo, 'notifytiny');
5309              }
5310              if (!empty($backtrace)) {
5311                  $output .= $this->notification('Stack trace: ' . format_backtrace($backtrace, true), 'notifytiny');
5312              }
5313          }
5314  
5315          return $output;
5316      }
5317  
5318      /**
5319       * Returns a template fragment representing a notification.
5320       *
5321       * @param string $message The message to print out.
5322       * @param string $type    The type of notification. See constants on \core\output\notification.
5323       * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5324       * @return string A template fragment for a notification
5325       */
5326      public function notification($message, $type = null, $closebutton = true) {
5327          $message = clean_text($message);
5328          if ($type === 'notifysuccess' || $type === 'success') {
5329              return "++ $message ++\n";
5330          }
5331          return "!! $message !!\n";
5332      }
5333  
5334      /**
5335       * There is no footer for a cli request, however we must override the
5336       * footer method to prevent the default footer.
5337       */
5338      public function footer() {}
5339  
5340      /**
5341       * Render a notification (that is, a status message about something that has
5342       * just happened).
5343       *
5344       * @param \core\output\notification $notification the notification to print out
5345       * @return string plain text output
5346       */
5347      public function render_notification(\core\output\notification $notification) {
5348          return $this->notification($notification->get_message(), $notification->get_message_type());
5349      }
5350  }
5351  
5352  
5353  /**
5354   * A renderer that generates output for ajax scripts.
5355   *
5356   * This renderer prevents accidental sends back only json
5357   * encoded error messages, all other output is ignored.
5358   *
5359   * @copyright 2010 Petr Skoda
5360   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5361   * @since Moodle 2.0
5362   * @package core
5363   * @category output
5364   */
5365  class core_renderer_ajax extends core_renderer {
5366  
5367      /**
5368       * Returns a template fragment representing a fatal error.
5369       *
5370       * @param string $message The message to output
5371       * @param string $moreinfourl URL where more info can be found about the error
5372       * @param string $link Link for the Continue button
5373       * @param array $backtrace The execution backtrace
5374       * @param string $debuginfo Debugging information
5375       * @return string A template fragment for a fatal error
5376       */
5377      public function fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = "") {
5378          global $CFG;
5379  
5380          $this->page->set_context(null); // ugly hack - make sure page context is set to something, we do not want bogus warnings here
5381  
5382          $e = new stdClass();
5383          $e->error      = $message;
5384          $e->errorcode  = $errorcode;
5385          $e->stacktrace = NULL;
5386          $e->debuginfo  = NULL;
5387          $e->reproductionlink = NULL;
5388          if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
5389              $link = (string) $link;
5390              if ($link) {
5391                  $e->reproductionlink = $link;
5392              }
5393              if (!empty($debuginfo)) {
5394                  $e->debuginfo = $debuginfo;
5395              }
5396              if (!empty($backtrace)) {
5397                  $e->stacktrace = format_backtrace($backtrace, true);
5398              }
5399          }
5400          $this->header();
5401          return json_encode($e);
5402      }
5403  
5404      /**
5405       * Used to display a notification.
5406       * For the AJAX notifications are discarded.
5407       *
5408       * @param string $message The message to print out.
5409       * @param string $type    The type of notification. See constants on \core\output\notification.
5410       * @param bool $closebutton Whether to show a close icon to remove the notification (default true).
5411       */
5412      public function notification($message, $type = null, $closebutton = true) {
5413      }
5414  
5415      /**
5416       * Used to display a redirection message.
5417       * AJAX redirections should not occur and as such redirection messages
5418       * are discarded.
5419       *
5420       * @param moodle_url|string $encodedurl
5421       * @param string $message
5422       * @param int $delay
5423       * @param bool $debugdisableredirect
5424       * @param string $messagetype The type of notification to show the message in.
5425       *         See constants on \core\output\notification.
5426       */
5427      public function redirect_message($encodedurl, $message, $delay, $debugdisableredirect,
5428                                       $messagetype = \core\output\notification::NOTIFY_INFO) {}
5429  
5430      /**
5431       * Prepares the start of an AJAX output.
5432       */
5433      public function header() {
5434          // unfortunately YUI iframe upload does not support application/json
5435          if (!empty($_FILES)) {
5436              @header('Content-type: text/plain; charset=utf-8');
5437              if (!core_useragent::supports_json_contenttype()) {
5438                  @header('X-Content-Type-Options: nosniff');
5439              }
5440          } else if (!core_useragent::supports_json_contenttype()) {
5441              @header('Content-type: text/plain; charset=utf-8');
5442              @header('X-Content-Type-Options: nosniff');
5443          } else {
5444              @header('Content-type: application/json; charset=utf-8');
5445          }
5446  
5447          // Headers to make it not cacheable and json
5448          @header('Cache-Control: no-store, no-cache, must-revalidate');
5449          @header('Cache-Control: post-check=0, pre-check=0', false);
5450          @header('Pragma: no-cache');
5451          @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
5452          @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
5453          @header('Accept-Ranges: none');
5454      }
5455  
5456      /**
5457       * There is no footer for an AJAX request, however we must override the
5458       * footer method to prevent the default footer.
5459       */
5460      public function footer() {}
5461  
5462      /**
5463       * No need for headers in an AJAX request... this should never happen.
5464       * @param string $text
5465       * @param int $level
5466       * @param string $classes
5467       * @param string $id
5468       */
5469      public function heading($text, $level = 2, $classes = 'main', $id = null) {}
5470  }
5471  
5472  
5473  
5474  /**
5475   * The maintenance renderer.
5476   *
5477   * The purpose of this renderer is to block out the core renderer methods that are not usable when the site
5478   * is running a maintenance related task.
5479   * It must always extend the core_renderer as we switch from the core_renderer to this renderer in a couple of places.
5480   *
5481   * @since Moodle 2.6
5482   * @package core
5483   * @category output
5484   * @copyright 2013 Sam Hemelryk
5485   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
5486   */
5487  class core_renderer_maintenance extends core_renderer {
5488  
5489      /**
5490       * Initialises the renderer instance.
5491       *
5492       * @param moodle_page $page
5493       * @param string $target
5494       * @throws coding_exception
5495       */
5496      public function __construct(moodle_page $page, $target) {
5497          if ($target !== RENDERER_TARGET_MAINTENANCE || $page->pagelayout !== 'maintenance') {
5498              throw new coding_exception('Invalid request for the maintenance renderer.');
5499          }
5500          parent::__construct($page, $target);
5501      }
5502  
5503      /**
5504       * Does nothing. The maintenance renderer cannot produce blocks.
5505       *
5506       * @param block_contents $bc
5507       * @param string $region
5508       * @return string
5509       */
5510      public function block(block_contents $bc, $region) {
5511          return '';
5512      }
5513  
5514      /**
5515       * Does nothing. The maintenance renderer cannot produce blocks.
5516       *
5517       * @param string $region
5518       * @param array $classes
5519       * @param string $tag
5520       * @param boolean $fakeblocksonly
5521       * @return string
5522       */
5523      public function blocks($region, $classes = array(), $tag = 'aside', $fakeblocksonly = false) {
5524          return '';
5525      }
5526  
5527      /**
5528       * Does nothing. The maintenance renderer cannot produce blocks.
5529       *
5530       * @param string $region
5531       * @param boolean $fakeblocksonly Output fake block only.
5532       * @return string
5533       */
5534      public function blocks_for_region($region, $fakeblocksonly = false) {
5535          return '';
5536      }
5537  
5538      /**
5539       * Does nothing. The maintenance renderer cannot produce a course content header.
5540       *
5541       * @param bool $onlyifnotcalledbefore
5542       * @return string
5543       */
5544      public function course_content_header($onlyifnotcalledbefore = false) {
5545          return '';
5546      }
5547  
5548      /**
5549       * Does nothing. The maintenance renderer cannot produce a course content footer.
5550       *
5551       * @param bool $onlyifnotcalledbefore
5552       * @return string
5553       */
5554      public function course_content_footer($onlyifnotcalledbefore = false) {
5555          return '';
5556      }
5557  
5558      /**
5559       * Does nothing. The maintenance renderer cannot produce a course header.
5560       *
5561       * @return string
5562       */
5563      public function course_header() {
5564          return '';
5565      }
5566  
5567      /**
5568       * Does nothing. The maintenance renderer cannot produce a course footer.
5569       *
5570       * @return string
5571       */
5572      public function course_footer() {
5573          return '';
5574      }
5575  
5576      /**
5577       * Does nothing. The maintenance renderer cannot produce a custom menu.
5578       *
5579       * @param string $custommenuitems
5580       * @return string
5581       */
5582      public function custom_menu($custommenuitems = '') {
5583          return '';
5584      }
5585  
5586      /**
5587       * Does nothing. The maintenance renderer cannot produce a file picker.
5588       *
5589       * @param array $options
5590       * @return string
5591       */
5592      public function file_picker($options) {
5593          return '';
5594      }
5595  
5596      /**
5597       * Does nothing. The maintenance renderer cannot produce and HTML file tree.
5598       *
5599       * @param array $dir
5600       * @return string
5601       */
5602      public function htmllize_file_tree($dir) {
5603          return '';
5604  
5605      }
5606  
5607      /**
5608       * Overridden confirm message for upgrades.
5609       *
5610       * @param string $message The question to ask the user
5611       * @param single_button|moodle_url|string $continue The single_button component representing the Continue answer.
5612       * @param single_button|moodle_url|string $cancel The single_button component representing the Cancel answer.
5613       * @param array $displayoptions optional extra display options
5614       * @return string HTML fragment
5615       */
5616      public function confirm($message, $continue, $cancel, array $displayoptions = []) {
5617          // We need plain styling of confirm boxes on upgrade because we don't know which stylesheet we have (it could be
5618          // from any previous version of Moodle).
5619          if ($continue instanceof single_button) {
5620              $continue->type = single_button::BUTTON_PRIMARY;
5621          } else if (is_string($continue)) {
5622              $continue = new single_button(new moodle_url($continue), get_string('continue'), 'post',
5623                  $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
5624          } else if ($continue instanceof moodle_url) {
5625              $continue = new single_button($continue, get_string('continue'), 'post',
5626                  $displayoptions['type'] ?? single_button::BUTTON_PRIMARY);
5627          } else {
5628              throw new coding_exception('The continue param to $OUTPUT->confirm() must be either a URL' .
5629                                         ' (string/moodle_url) or a single_button instance.');
5630          }
5631  
5632          if ($cancel instanceof single_button) {
5633              $output = '';
5634          } else if (is_string($cancel)) {
5635              $cancel = new single_button(new moodle_url($cancel), get_string('cancel'), 'get');
5636          } else if ($cancel instanceof moodle_url) {
5637              $cancel = new single_button($cancel, get_string('cancel'), 'get');
5638          } else {
5639              throw new coding_exception('The cancel param to $OUTPUT->confirm() must be either a URL' .
5640                                         ' (string/moodle_url) or a single_button instance.');
5641          }
5642  
5643          $output = $this->box_start('generalbox', 'notice');
5644          $output .= html_writer::tag('h4', get_string('confirm'));
5645          $output .= html_writer::tag('p', $message);
5646          $output .= html_writer::tag('div', $this->render($cancel) . $this->render($continue), ['class' => 'buttons']);
5647          $output .= $this->box_end();
5648          return $output;
5649      }
5650  
5651      /**
5652       * Does nothing. The maintenance renderer does not support JS.
5653       *
5654       * @param block_contents $bc
5655       */
5656      public function init_block_hider_js(block_contents $bc) {
5657          // Does nothing.
5658      }
5659  
5660      /**
5661       * Does nothing. The maintenance renderer cannot produce language menus.
5662       *
5663       * @return string
5664       */
5665      public function lang_menu() {
5666          return '';
5667      }
5668  
5669      /**
5670       * Does nothing. The maintenance renderer has no need for login information.
5671       *
5672       * @param null $withlinks
5673       * @return string
5674       */
5675      public function login_info($withlinks = null) {
5676          return '';
5677      }
5678  
5679      /**
5680       * Secure login info.
5681       *
5682       * @return string
5683       */
5684      public function secure_login_info() {
5685          return $this->login_info(false);
5686      }
5687  
5688      /**
5689       * Does nothing. The maintenance renderer cannot produce user pictures.
5690       *
5691       * @param stdClass $user
5692       * @param array $options
5693       * @return string
5694       */
5695      public function user_picture(stdClass $user, array $options = null) {
5696          return '';
5697      }
5698  }