Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

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

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