Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

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

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