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.
/lib/ -> pagelib.php (source)

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   * This file contains the moodle_page class. There is normally a single instance
  19   * of this class in the $PAGE global variable. This class is a central repository
  20   * of information about the page we are building up to send back to the user.
  21   *
  22   * @package core
  23   * @category page
  24   * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
  25   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  26   */
  27  
  28  defined('MOODLE_INTERNAL') || die();
  29  
  30  use core\navigation\views\primary;
  31  use core\navigation\views\secondary;
  32  use core\navigation\output\primary as primaryoutput;
  33  use core\output\activity_header;
  34  
  35  /**
  36   * $PAGE is a central store of information about the current page we are
  37   * generating in response to the user's request.
  38   *
  39   * It does not do very much itself
  40   * except keep track of information, however, it serves as the access point to
  41   * some more significant components like $PAGE->theme, $PAGE->requires,
  42   * $PAGE->blocks, etc.
  43   *
  44   * @copyright 2009 Tim Hunt
  45   * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  46   * @since Moodle 2.0
  47   * @package core
  48   * @category page
  49   *
  50   * The following properties are alphabetical. Please keep it that way so that its
  51   * easy to maintain.
  52   *
  53   * @property-read string $activityname The type of activity we are in, for example 'forum' or 'quiz'.
  54   *      Will be null if this page is not within a module.
  55   * @property-read stdClass $activityrecord The row from the activities own database table (for example
  56   *      the forum or quiz table) that this page belongs to. Will be null
  57   *      if this page is not within a module.
  58   * @property-read activity_header $activityheader The activity header for the page, representing standard components
  59   *      displayed within the header
  60   * @property-read array $alternativeversions Mime type => object with ->url and ->title.
  61   * @property-read block_manager $blocks The blocks manager object for this page.
  62   * @property-read array $blockmanipulations
  63   * @property-read string $bodyclasses A string to use within the class attribute on the body tag.
  64   * @property-read string $bodyid A string to use as the id of the body tag.
  65   * @property-read string $button The HTML to go where the Turn editing on button normally goes.
  66   * @property-read bool $cacheable Defaults to true. Set to false to stop the page being cached at all.
  67   * @property-read array $categories An array of all the categories the page course belongs to,
  68   *      starting with the immediately containing category, and working out to
  69   *      the top-level category. This may be the empty array if we are in the
  70   *      front page course.
  71   * @property-read mixed $category The category that the page course belongs to.
  72   * @property-read cm_info $cm The course_module that this page belongs to. Will be null
  73   *      if this page is not within a module. This is a full cm object, as loaded
  74   *      by get_coursemodule_from_id or get_coursemodule_from_instance,
  75   *      so the extra modname and name fields are present.
  76   * @property-read context $context The main context to which this page belongs.
  77   * @property-read stdClass $course The current course that we are inside - a row from the
  78   *      course table. (Also available as $COURSE global.) If we are not inside
  79   *      an actual course, this will be the site course.
  80   * @property-read string $devicetypeinuse The name of the device type in use
  81   * @property-read string $docspath The path to the Help and documentation.
  82   * @property-read string $focuscontrol The id of the HTML element to be focused when the page has loaded.
  83   * @property-read bool $headerprinted True if the page header has already been printed.
  84   * @property-read string $heading The main heading that should be displayed at the top of the <body>.
  85   * @property-read string $headingmenu The menu (or actions) to display in the heading
  86   * @property-read array $layout_options An arrays with options for the layout file.
  87   * @property-read array $legacythemeinuse True if the legacy browser theme is in use.
  88   * @property-read navbar $navbar The navbar object used to display the navbar
  89   * @property-read secondary $secondarynav The secondary navigation object
  90   *      used to display the secondarynav in boost
  91   * @property-read primary $primarynav The primary navigation object used to display the primary nav in boost
  92   * @property-read primaryoutput $primarynavcombined The primary navigation object used to display the primary nav in boost
  93   * @property-read global_navigation $navigation The navigation structure for this page.
  94   * @property-read xhtml_container_stack $opencontainers Tracks XHTML tags on this page that have been opened but not closed.
  95   *      mainly for internal use by the rendering code.
  96   * @property-read string $pagelayout The general type of page this is. For example 'normal', 'popup', 'home'.
  97   *      Allows the theme to display things differently, if it wishes to.
  98   * @property-read string $pagetype The page type string, should be used as the id for the body tag in the theme.
  99   * @property-read int $periodicrefreshdelay The periodic refresh delay to use with meta refresh
 100   * @property-read page_requirements_manager $requires Tracks the JavaScript, CSS files, etc. required by this page.
 101   * @property-read string $requestip The IP address of the current request, null if unknown.
 102   * @property-read string $requestorigin The type of request 'web', 'ws', 'cli', 'restore', etc.
 103   * @property-read settings_navigation $settingsnav The settings navigation
 104   * @property-read int $state One of the STATE_... constants
 105   * @property-read string $subpage The subpage identifier, if any.
 106   * @property-read theme_config $theme The theme for this page.
 107   * @property-read string $title The title that should go in the <head> section of the HTML of this page.
 108   * @property-read moodle_url $url The moodle url object for this page.
 109   */
 110  class moodle_page {
 111  
 112      /** The state of the page before it has printed the header **/
 113      const STATE_BEFORE_HEADER = 0;
 114  
 115      /** The state the page is in temporarily while the header is being printed **/
 116      const STATE_PRINTING_HEADER = 1;
 117  
 118      /** The state the page is in while content is presumably being printed **/
 119      const STATE_IN_BODY = 2;
 120  
 121      /**
 122       * The state the page is when the footer has been printed and its function is
 123       * complete.
 124       */
 125      const STATE_DONE = 3;
 126  
 127      /**
 128       * The separator used for separating page title elements.
 129       */
 130      const TITLE_SEPARATOR = ' | ';
 131  
 132      /**
 133       * @var int The current state of the page. The state a page is within
 134       * determines what actions are possible for it.
 135       */
 136      protected $_state = self::STATE_BEFORE_HEADER;
 137  
 138      /**
 139       * @var stdClass The course currently associated with this page.
 140       * If not has been provided the front page course is used.
 141       */
 142      protected $_course = null;
 143  
 144      /**
 145       * @var cm_info If this page belongs to a module, this is the cm_info module
 146       * description object.
 147       */
 148      protected $_cm = null;
 149  
 150      /**
 151       * @var stdClass If $_cm is not null, then this will hold the corresponding
 152       * row from the modname table. For example, if $_cm->modname is 'quiz', this
 153       * will be a row from the quiz table.
 154       */
 155      protected $_module = null;
 156  
 157      /**
 158       * @var context The context that this page belongs to.
 159       */
 160      protected $_context = null;
 161  
 162      /**
 163       * @var array This holds any categories that $_course belongs to, starting with the
 164       * particular category it belongs to, and working out through any parent
 165       * categories to the top level. These are loaded progressively, if needed.
 166       * There are three states. $_categories = null initially when nothing is
 167       * loaded; $_categories = array($id => $cat, $parentid => null) when we have
 168       * loaded $_course->category, but not any parents; and a complete array once
 169       * everything is loaded.
 170       */
 171      protected $_categories = null;
 172  
 173      /**
 174       * @var array An array of CSS classes that should be added to the body tag in HTML.
 175       */
 176      protected $_bodyclasses = array();
 177  
 178      /**
 179       * @var string The title for the page. Used within the title tag in the HTML head.
 180       */
 181      protected $_title = '';
 182  
 183      /**
 184       * @var string The string to use as the heading of the page. Shown near the top of the
 185       * page within most themes.
 186       */
 187      protected $_heading = '';
 188  
 189      /**
 190       * @var string The pagetype is used to describe the page and defaults to a representation
 191       * of the physical path to the page e.g. my-index, mod-quiz-attempt
 192       */
 193      protected $_pagetype = null;
 194  
 195      /**
 196       * @var string The pagelayout to use when displaying this page. The
 197       * pagelayout needs to have been defined by the theme in use, or one of its
 198       * parents. By default base is used however standard is the more common layout.
 199       * Note that this gets automatically set by core during operations like
 200       * require_login.
 201       */
 202      protected $_pagelayout = 'base';
 203  
 204      /**
 205       * @var array List of theme layout options, these are ignored by core.
 206       * To be used in individual theme layout files only.
 207       */
 208      protected $_layout_options = null;
 209  
 210      /**
 211       * @var string An optional arbitrary parameter that can be set on pages where the context
 212       * and pagetype is not enough to identify the page.
 213       */
 214      protected $_subpage = '';
 215  
 216      /**
 217       * @var string Set a different path to use for the 'Help and documentation' link.
 218       * By default, it uses the path of the file for instance mod/quiz/attempt.
 219       */
 220      protected $_docspath = null;
 221  
 222      /**
 223       * @var string A legacy class that will be added to the body tag
 224       */
 225      protected $_legacyclass = null;
 226  
 227      /**
 228       * @var moodle_url The URL for this page. This is mandatory and must be set
 229       * before output is started.
 230       */
 231      protected $_url = null;
 232  
 233      /**
 234       * @var array An array of links to alternative versions of this page.
 235       * Primarily used for RSS versions of the current page.
 236       */
 237      protected $_alternateversions = array();
 238  
 239      /**
 240       * @var block_manager The blocks manager for this page. It is responsible for
 241       * the blocks and there content on this page.
 242       */
 243      protected $_blocks = null;
 244  
 245      /**
 246       * @var page_requirements_manager Page requirements manager. It is responsible
 247       * for all JavaScript and CSS resources required by this page.
 248       */
 249      protected $_requires = null;
 250  
 251      /** @var page_requirements_manager Saves the requirement manager object used before switching to to fragments one. */
 252      protected $savedrequires = null;
 253  
 254      /**
 255       * @var string The capability required by the user in order to edit blocks
 256       * and block settings on this page.
 257       */
 258      protected $_blockseditingcap = 'moodle/site:manageblocks';
 259  
 260      /**
 261       * @var bool An internal flag to record when block actions have been processed.
 262       * Remember block actions occur on the current URL and it is important that
 263       * even they are never executed more than once.
 264       */
 265      protected $_block_actions_done = false;
 266  
 267      /**
 268       * @var array An array of any other capabilities the current user must have
 269       * in order to editing the page and/or its content (not just blocks).
 270       */
 271      protected $_othereditingcaps = array();
 272  
 273      /**
 274       * @var bool Sets whether this page should be cached by the browser or not.
 275       * If it is set to true (default) the page is served with caching headers.
 276       */
 277      protected $_cacheable = true;
 278  
 279      /**
 280       * @var string Can be set to the ID of an element on the page, if done that
 281       * element receives focus when the page loads.
 282       */
 283      protected $_focuscontrol = '';
 284  
 285      /**
 286       * @var string HTML to go where the turn on editing button is located. This
 287       * is nearly a legacy item and not used very often any more.
 288       */
 289      protected $_button = '';
 290  
 291      /**
 292       * @var theme_config The theme to use with this page. This has to be properly
 293       * initialised via {@link moodle_page::initialise_theme_and_output()} which
 294       * happens magically before any operation that requires it.
 295       */
 296      protected $_theme = null;
 297  
 298      /**
 299       * @var global_navigation Contains the global navigation structure.
 300       */
 301      protected $_navigation = null;
 302  
 303      /**
 304       * @var settings_navigation Contains the settings navigation structure.
 305       */
 306      protected $_settingsnav = null;
 307  
 308      /**
 309       * @var flat_navigation Contains a list of nav nodes, most closely related to the current page.
 310       */
 311      protected $_flatnav = null;
 312  
 313      /**
 314       * @var secondary Contains the nav nodes that will appear
 315       * in the secondary navigation.
 316       */
 317      protected $_secondarynav = null;
 318  
 319      /**
 320       * @var primary Contains the nav nodes that will appear
 321       * in the primary navigation.
 322       */
 323      protected $_primarynav = null;
 324  
 325      /**
 326       * @var primaryoutput Contains the combined nav nodes that will appear
 327       * in the primary navigation. Includes - primarynav, langmenu, usermenu
 328       */
 329      protected $_primarynavcombined = null;
 330  
 331      /**
 332       * @var navbar Contains the navbar structure.
 333       */
 334      protected $_navbar = null;
 335  
 336      /**
 337       * @var string The menu (or actions) to display in the heading.
 338       */
 339      protected $_headingmenu = null;
 340  
 341      /**
 342       * @var array stack trace. Then the theme is initialised, we save the stack
 343       * trace, for use in error messages.
 344       */
 345      protected $_wherethemewasinitialised = null;
 346  
 347      /**
 348       * @var xhtml_container_stack Tracks XHTML tags on this page that have been
 349       * opened but not closed.
 350       */
 351      protected $_opencontainers;
 352  
 353      /**
 354       * @var int Sets the page to refresh after a given delay (in seconds) using
 355       * meta refresh in {@link standard_head_html()} in outputlib.php
 356       * If set to null(default) the page is not refreshed
 357       */
 358      protected $_periodicrefreshdelay = null;
 359  
 360      /**
 361       * @var array Associative array of browser shortnames (as used by check_browser_version)
 362       * and their minimum required versions
 363       */
 364      protected $_legacybrowsers = array('MSIE' => 6.0);
 365  
 366      /**
 367       * @var string Is set to the name of the device type in use.
 368       * This will we worked out when it is first used.
 369       */
 370      protected $_devicetypeinuse = null;
 371  
 372      /**
 373       * @var bool Used to determine if HTTPS should be required for login.
 374       */
 375      protected $_https_login_required = false;
 376  
 377      /**
 378       * @var bool Determines if popup notifications allowed on this page.
 379       * Code such as the quiz module disables popup notifications in situations
 380       * such as upgrading or completing a quiz.
 381       */
 382      protected $_popup_notification_allowed = true;
 383  
 384      /**
 385       * @var bool Is the settings menu being forced to display on this page (activities / resources only).
 386       * This is only used by themes that use the settings menu.
 387       */
 388      protected $_forcesettingsmenu = false;
 389  
 390      /**
 391       * @var array Array of header actions HTML to add to the page header actions menu.
 392       */
 393      protected $_headeractions = [];
 394  
 395      /**
 396       * @var bool Should the region main settings menu be rendered in the header.
 397       */
 398      protected $_regionmainsettingsinheader = false;
 399  
 400      /**
 401       * @var bool Should the secondary menu be rendered.
 402       */
 403      protected $_hassecondarynavigation = true;
 404  
 405      /**
 406       * @var bool Should the secondary menu be rendered as a tablist as opposed to a menubar.
 407       */
 408      protected $_hastablistsecondarynavigation = false;
 409  
 410      /**
 411       * @var string the key of the secondary node to be activated.
 412       */
 413      protected $_activekeysecondary = null;
 414  
 415      /**
 416       * @var string the key of the primary node to be activated.
 417       */
 418      protected $_activenodeprimary = null;
 419  
 420      /**
 421       * @var activity_header The activity header for the page.
 422       */
 423      protected $_activityheader;
 424  
 425      /**
 426       * @var bool The value of displaying the navigation overflow.
 427       */
 428      protected $_navigationoverflow = true;
 429  
 430      /**
 431       * @var bool Whether to override/remove all editing capabilities for blocks on the page.
 432       */
 433      protected $_forcelockallblocks = false;
 434  
 435      /**
 436       * Force the settings menu to be displayed on this page. This will only force the
 437       * settings menu on an activity / resource page that is being displayed on a theme that
 438       * uses a settings menu.
 439       *
 440       * @param bool $forced default of true, can be sent false to turn off the force.
 441       */
 442      public function force_settings_menu($forced = true) {
 443          $this->_forcesettingsmenu = $forced;
 444      }
 445  
 446      /**
 447       * Check to see if the settings menu is forced to display on this activity / resource page.
 448       * This only applies to themes that use the settings menu.
 449       *
 450       * @return bool True if the settings menu is forced to display.
 451       */
 452      public function is_settings_menu_forced() {
 453          return $this->_forcesettingsmenu;
 454      }
 455  
 456      // Magic getter methods =============================================================
 457      // Due to the __get magic below, you normally do not call these as $PAGE->magic_get_x
 458      // methods, but instead use the $PAGE->x syntax.
 459  
 460      /**
 461       * Please do not call this method directly, use the ->state syntax. {@link moodle_page::__get()}.
 462       * @return integer one of the STATE_XXX constants. You should not normally need
 463       * to use this in your code. It is intended for internal use by this class
 464       * and its friends like print_header, to check that everything is working as
 465       * expected. Also accessible as $PAGE->state.
 466       */
 467      protected function magic_get_state() {
 468          return $this->_state;
 469      }
 470  
 471      /**
 472       * Please do not call this method directly, use the ->headerprinted syntax. {@link moodle_page::__get()}.
 473       * @return bool has the header already been printed?
 474       */
 475      protected function magic_get_headerprinted() {
 476          return $this->_state >= self::STATE_IN_BODY;
 477      }
 478  
 479      /**
 480       * Please do not call this method directly, use the ->course syntax. {@link moodle_page::__get()}.
 481       * @return stdClass the current course that we are inside - a row from the
 482       * course table. (Also available as $COURSE global.) If we are not inside
 483       * an actual course, this will be the site course.
 484       */
 485      protected function magic_get_course() {
 486          global $SITE;
 487          if (is_null($this->_course)) {
 488              return $SITE;
 489          }
 490          return $this->_course;
 491      }
 492  
 493      /**
 494       * Please do not call this method directly, use the ->cm syntax. {@link moodle_page::__get()}.
 495       * @return cm_info the course_module that this page belongs to. Will be null
 496       * if this page is not within a module. This is a full cm object, as loaded
 497       * by get_coursemodule_from_id or get_coursemodule_from_instance,
 498       * so the extra modname and name fields are present.
 499       */
 500      protected function magic_get_cm() {
 501          return $this->_cm;
 502      }
 503  
 504      /**
 505       * Please do not call this method directly, use the ->activityrecord syntax. {@link moodle_page::__get()}.
 506       * @return stdClass the row from the activities own database table (for example
 507       * the forum or quiz table) that this page belongs to. Will be null
 508       * if this page is not within a module.
 509       */
 510      protected function magic_get_activityrecord() {
 511          if (is_null($this->_module) && !is_null($this->_cm)) {
 512              $this->load_activity_record();
 513          }
 514          return $this->_module;
 515      }
 516  
 517      /**
 518       * Please do not call this method directly, use the ->activityname syntax. {@link moodle_page::__get()}.
 519       * @return string the The type of activity we are in, for example 'forum' or 'quiz'.
 520       * Will be null if this page is not within a module.
 521       */
 522      protected function magic_get_activityname() {
 523          if (is_null($this->_cm)) {
 524              return null;
 525          }
 526          return $this->_cm->modname;
 527      }
 528  
 529      /**
 530       * Please do not call this method directly, use the ->category syntax. {@link moodle_page::__get()}.
 531       * @return stdClass the category that the page course belongs to. If there isn't one
 532       * (that is, if this is the front page course) returns null.
 533       */
 534      protected function magic_get_category() {
 535          $this->ensure_category_loaded();
 536          if (!empty($this->_categories)) {
 537              return reset($this->_categories);
 538          } else {
 539              return null;
 540          }
 541      }
 542  
 543      /**
 544       * Please do not call this method directly, use the ->categories syntax. {@link moodle_page::__get()}.
 545       * @return array an array of all the categories the page course belongs to,
 546       * starting with the immediately containing category, and working out to
 547       * the top-level category. This may be the empty array if we are in the
 548       * front page course.
 549       */
 550      protected function magic_get_categories() {
 551          $this->ensure_categories_loaded();
 552          return $this->_categories;
 553      }
 554  
 555      /**
 556       * Please do not call this method directly, use the ->context syntax. {@link moodle_page::__get()}.
 557       * @return context the main context to which this page belongs.
 558       */
 559      protected function magic_get_context() {
 560          global $CFG;
 561          if (is_null($this->_context)) {
 562              if (CLI_SCRIPT or NO_MOODLE_COOKIES) {
 563                  // Cli scripts work in system context, do not annoy devs with debug info.
 564                  // Very few scripts do not use cookies, we can safely use system as default context there.
 565              } else if (AJAX_SCRIPT && $CFG->debugdeveloper) {
 566                  // Throw exception inside AJAX script in developer mode, otherwise the debugging message may be missed.
 567                  throw new coding_exception('$PAGE->context was not set. You may have forgotten '
 568                      .'to call require_login() or $PAGE->set_context()');
 569              } else {
 570                  debugging('Coding problem: $PAGE->context was not set. You may have forgotten '
 571                      .'to call require_login() or $PAGE->set_context(). The page may not display '
 572                      .'correctly as a result');
 573              }
 574              $this->_context = context_system::instance();
 575          }
 576          return $this->_context;
 577      }
 578  
 579      /**
 580       * Please do not call this method directly, use the ->pagetype syntax. {@link moodle_page::__get()}.
 581       * @return string e.g. 'my-index' or 'mod-quiz-attempt'.
 582       */
 583      protected function magic_get_pagetype() {
 584          global $CFG;
 585          if (is_null($this->_pagetype) || isset($CFG->pagepath)) {
 586              $this->initialise_default_pagetype();
 587          }
 588          return $this->_pagetype;
 589      }
 590  
 591      /**
 592       * Please do not call this method directly, use the ->pagetype syntax. {@link moodle_page::__get()}.
 593       * @return string The id to use on the body tag, uses {@link magic_get_pagetype()}.
 594       */
 595      protected function magic_get_bodyid() {
 596          return 'page-'.$this->pagetype;
 597      }
 598  
 599      /**
 600       * Please do not call this method directly, use the ->pagelayout syntax. {@link moodle_page::__get()}.
 601       * @return string the general type of page this is. For example 'standard', 'popup', 'home'.
 602       *      Allows the theme to display things differently, if it wishes to.
 603       */
 604      protected function magic_get_pagelayout() {
 605          return $this->_pagelayout;
 606      }
 607  
 608      /**
 609       * Please do not call this method directly, use the ->layout_options syntax. {@link moodle_page::__get()}.
 610       * @return array returns arrays with options for layout file
 611       */
 612      protected function magic_get_layout_options() {
 613          if (!is_array($this->_layout_options)) {
 614              $this->_layout_options = $this->_theme->pagelayout_options($this->pagelayout);
 615          }
 616          return $this->_layout_options;
 617      }
 618  
 619      /**
 620       * Please do not call this method directly, use the ->subpage syntax. {@link moodle_page::__get()}.
 621       * @return string The subpage identifier, if any.
 622       */
 623      protected function magic_get_subpage() {
 624          return $this->_subpage;
 625      }
 626  
 627      /**
 628       * Please do not call this method directly, use the ->bodyclasses syntax. {@link moodle_page::__get()}.
 629       * @return string the class names to put on the body element in the HTML.
 630       */
 631      protected function magic_get_bodyclasses() {
 632          return implode(' ', array_keys($this->_bodyclasses));
 633      }
 634  
 635      /**
 636       * Please do not call this method directly, use the ->title syntax. {@link moodle_page::__get()}.
 637       * @return string the title that should go in the <head> section of the HTML of this page.
 638       */
 639      protected function magic_get_title() {
 640          return $this->_title;
 641      }
 642  
 643      /**
 644       * Please do not call this method directly, use the ->heading syntax. {@link moodle_page::__get()}.
 645       * @return string the main heading that should be displayed at the top of the <body>.
 646       */
 647      protected function magic_get_heading() {
 648          return $this->_heading;
 649      }
 650  
 651      /**
 652       * Please do not call this method directly, use the ->heading syntax. {@link moodle_page::__get()}.
 653       * @return string The menu (or actions) to display in the heading
 654       */
 655      protected function magic_get_headingmenu() {
 656          return $this->_headingmenu;
 657      }
 658  
 659      /**
 660       * Please do not call this method directly, use the ->docspath syntax. {@link moodle_page::__get()}.
 661       * @return string the path to the Help and documentation.
 662       */
 663      protected function magic_get_docspath() {
 664          if (is_string($this->_docspath)) {
 665              return $this->_docspath;
 666          } else {
 667              return str_replace('-', '/', $this->pagetype);
 668          }
 669      }
 670  
 671      /**
 672       * Please do not call this method directly, use the ->url syntax. {@link moodle_page::__get()}.
 673       * @return moodle_url the clean URL required to load the current page. (You
 674       * should normally use this in preference to $ME or $FULLME.)
 675       */
 676      protected function magic_get_url() {
 677          global $FULLME;
 678          if (is_null($this->_url)) {
 679              debugging('This page did not call $PAGE->set_url(...). Using '.s($FULLME), DEBUG_DEVELOPER);
 680              $this->_url = new moodle_url($FULLME);
 681              // Make sure the guessed URL cannot lead to dangerous redirects.
 682              $this->_url->remove_params('sesskey');
 683          }
 684          return new moodle_url($this->_url); // Return a clone for safety.
 685      }
 686  
 687      /**
 688       * The list of alternate versions of this page.
 689       * @return array mime type => object with ->url and ->title.
 690       */
 691      protected function magic_get_alternateversions() {
 692          return $this->_alternateversions;
 693      }
 694  
 695      /**
 696       * Please do not call this method directly, use the ->blocks syntax. {@link moodle_page::__get()}.
 697       * @return block_manager the blocks manager object for this page.
 698       */
 699      protected function magic_get_blocks() {
 700          global $CFG;
 701          if (is_null($this->_blocks)) {
 702              if (!empty($CFG->blockmanagerclass)) {
 703                  if (!empty($CFG->blockmanagerclassfile)) {
 704                      require_once($CFG->blockmanagerclassfile);
 705                  }
 706                  $classname = $CFG->blockmanagerclass;
 707              } else {
 708                  $classname = 'block_manager';
 709              }
 710              $this->_blocks = new $classname($this);
 711          }
 712          return $this->_blocks;
 713      }
 714  
 715      /**
 716       * Please do not call this method directly, use the ->requires syntax. {@link moodle_page::__get()}.
 717       * @return page_requirements_manager tracks the JavaScript, CSS files, etc. required by this page.
 718       */
 719      protected function magic_get_requires() {
 720          if (is_null($this->_requires)) {
 721              $this->_requires = new page_requirements_manager();
 722          }
 723          return $this->_requires;
 724      }
 725  
 726      /**
 727       * Please do not call this method directly, use the ->cacheable syntax. {@link moodle_page::__get()}.
 728       * @return bool can this page be cached by the user's browser.
 729       */
 730      protected function magic_get_cacheable() {
 731          return $this->_cacheable;
 732      }
 733  
 734      /**
 735       * Please do not call this method directly, use the ->focuscontrol syntax. {@link moodle_page::__get()}.
 736       * @return string the id of the HTML element to be focused when the page has loaded.
 737       */
 738      protected function magic_get_focuscontrol() {
 739          return $this->_focuscontrol;
 740      }
 741  
 742      /**
 743       * Please do not call this method directly, use the ->button syntax. {@link moodle_page::__get()}.
 744       * @return string the HTML to go where the Turn editing on button normally goes.
 745       */
 746      protected function magic_get_button() {
 747          return $this->_button;
 748      }
 749  
 750      /**
 751       * Please do not call this method directly, use the ->theme syntax. {@link moodle_page::__get()}.
 752       * @return theme_config the initialised theme for this page.
 753       */
 754      protected function magic_get_theme() {
 755          if (is_null($this->_theme)) {
 756              $this->initialise_theme_and_output();
 757          }
 758          return $this->_theme;
 759      }
 760  
 761      /**
 762       * Returns an array of minipulations or false if there are none to make.
 763       *
 764       * @since Moodle 2.5.1 2.6
 765       * @return bool|array
 766       */
 767      protected function magic_get_blockmanipulations() {
 768          if (!right_to_left()) {
 769              return false;
 770          }
 771          if (is_null($this->_theme)) {
 772              $this->initialise_theme_and_output();
 773          }
 774          return $this->_theme->blockrtlmanipulations;
 775      }
 776  
 777      /**
 778       * Please do not call this method directly, use the ->devicetypeinuse syntax. {@link moodle_page::__get()}.
 779       * @return string The device type being used.
 780       */
 781      protected function magic_get_devicetypeinuse() {
 782          if (empty($this->_devicetypeinuse)) {
 783              $this->_devicetypeinuse = core_useragent::get_user_device_type();
 784          }
 785          return $this->_devicetypeinuse;
 786      }
 787  
 788      /**
 789       * Please do not call this method directly use the ->periodicrefreshdelay syntax
 790       * {@link moodle_page::__get()}
 791       * @return int The periodic refresh delay to use with meta refresh
 792       */
 793      protected function magic_get_periodicrefreshdelay() {
 794          return $this->_periodicrefreshdelay;
 795      }
 796  
 797      /**
 798       * Please do not call this method directly use the ->opencontainers syntax. {@link moodle_page::__get()}
 799       * @return xhtml_container_stack tracks XHTML tags on this page that have been opened but not closed.
 800       *      mainly for internal use by the rendering code.
 801       */
 802      protected function magic_get_opencontainers() {
 803          if (is_null($this->_opencontainers)) {
 804              $this->_opencontainers = new xhtml_container_stack();
 805          }
 806          return $this->_opencontainers;
 807      }
 808  
 809      /**
 810       * Return the navigation object
 811       * @return global_navigation
 812       */
 813      protected function magic_get_navigation() {
 814          if ($this->_navigation === null) {
 815              $this->_navigation = new global_navigation($this);
 816          }
 817          return $this->_navigation;
 818      }
 819  
 820      /**
 821       * Return a navbar object
 822       * @return navbar
 823       */
 824      protected function magic_get_navbar() {
 825          if ($this->_navbar === null) {
 826              $this->_navbar = new navbar($this);
 827          }
 828          return $this->_navbar;
 829      }
 830  
 831      /**
 832       * Returns the settings navigation object
 833       * @return settings_navigation
 834       */
 835      protected function magic_get_settingsnav() {
 836          if ($this->_settingsnav === null) {
 837              $this->_settingsnav = new settings_navigation($this);
 838              $this->_settingsnav->initialise();
 839          }
 840          return $this->_settingsnav;
 841      }
 842  
 843      /**
 844       * Returns the flat navigation object
 845       * @return flat_navigation
 846       */
 847      protected function magic_get_flatnav() {
 848          if ($this->_flatnav === null) {
 849              $this->_flatnav = new flat_navigation($this);
 850              $this->_flatnav->initialise();
 851          }
 852          return $this->_flatnav;
 853      }
 854  
 855      /**
 856       * Returns the activity header object
 857       * @return activity_header
 858       */
 859      protected function magic_get_activityheader(): activity_header {
 860          global $USER;
 861          if ($this->_activityheader === null) {
 862              $class = activity_header::class;
 863              // Try and load a custom class first.
 864              if (class_exists("mod_{$this->activityname}\\output\\activity_header")) {
 865                  $class = "mod_{$this->activityname}\\output\\activity_header";
 866              }
 867  
 868              $this->_activityheader = new $class($this, $USER);
 869          }
 870          return $this->_activityheader;
 871      }
 872  
 873      /**
 874       * Returns the secondary navigation object
 875       *
 876       * @todo MDL-74939 Remove support for old 'local\views\secondary' class location
 877       * @return secondary
 878       */
 879      protected function magic_get_secondarynav() {
 880          if ($this->_secondarynav === null) {
 881              $class = 'core\navigation\views\secondary';
 882              // Try and load a custom class first.
 883              if (class_exists("mod_{$this->activityname}\\navigation\\views\\secondary")) {
 884                  $class = "mod_{$this->activityname}\\navigation\\views\\secondary";
 885              } else if (class_exists("mod_{$this->activityname}\\local\\views\\secondary")) {
 886                  // For backwards compatibility, support the old location for this class (it was in a
 887                  // 'local' namespace which shouldn't be used for core APIs).
 888                  debugging("The class mod_{$this->activityname}}\\local\\views\\secondary uses a deprecated " .
 889                          "namespace. Please move it to mod_{$this->activityname}\\navigation\\views\\secondary.",
 890                          DEBUG_DEVELOPER);
 891                  $class = "mod_{$this->activityname}\\local\\views\\secondary";
 892              }
 893  
 894              $this->_secondarynav = new $class($this);
 895              $this->_secondarynav->initialise();
 896          }
 897          return $this->_secondarynav;
 898      }
 899  
 900      /**
 901       * Returns the primary navigation object
 902       * @return primary
 903       */
 904      protected function magic_get_primarynav() {
 905          if ($this->_primarynav === null) {
 906              $this->_primarynav = new primary($this);
 907              $this->_primarynav->initialise();
 908          }
 909          return $this->_primarynav;
 910      }
 911  
 912      /**
 913       * Returns the primary navigation object
 914       * @return primary
 915       */
 916      protected function magic_get_primarynavcombined() {
 917          if ($this->_primarynavcombined === null) {
 918              $this->_primarynavcombined = new primaryoutput($this);
 919          }
 920          return $this->_primarynavcombined;
 921      }
 922  
 923      /**
 924       * Returns request IP address.
 925       *
 926       * @return string IP address or null if unknown
 927       */
 928      protected function magic_get_requestip() {
 929          return getremoteaddr(null);
 930      }
 931  
 932      /**
 933       * Returns the origin of current request.
 934       *
 935       * Note: constants are not required because we need to use these values in logging and reports.
 936       *
 937       * @return string 'web', 'ws', 'cli', 'restore', etc.
 938       */
 939      protected function magic_get_requestorigin() {
 940          if (class_exists('restore_controller', false) && restore_controller::is_executing()) {
 941              return 'restore';
 942          }
 943  
 944          if (WS_SERVER) {
 945              return 'ws';
 946          }
 947  
 948          if (CLI_SCRIPT) {
 949              return 'cli';
 950          }
 951  
 952          return 'web';
 953      }
 954  
 955      /**
 956       * PHP overloading magic to make the $PAGE->course syntax work by redirecting
 957       * it to the corresponding $PAGE->magic_get_course() method if there is one, and
 958       * throwing an exception if not.
 959       *
 960       * @param string $name property name
 961       * @return mixed
 962       * @throws coding_exception
 963       */
 964      public function __get($name) {
 965          $getmethod = 'magic_get_' . $name;
 966          if (method_exists($this, $getmethod)) {
 967              return $this->$getmethod();
 968          } else {
 969              throw new coding_exception('Unknown property ' . $name . ' of $PAGE.');
 970          }
 971      }
 972  
 973      /**
 974       * PHP overloading magic to catch obvious coding errors.
 975       *
 976       * This method has been created to catch obvious coding errors where the
 977       * developer has tried to set a page property using $PAGE->key = $value.
 978       * In the moodle_page class all properties must be set using the appropriate
 979       * $PAGE->set_something($value) method.
 980       *
 981       * @param string $name property name
 982       * @param mixed $value Value
 983       * @return void Throws exception if field not defined in page class
 984       * @throws coding_exception
 985       */
 986      public function __set($name, $value) {
 987          if (method_exists($this, 'set_' . $name)) {
 988              throw new coding_exception('Invalid attempt to modify page object', "Use \$PAGE->set_$name() instead.");
 989          } else {
 990              throw new coding_exception('Invalid attempt to modify page object', "Unknown property $name");
 991          }
 992      }
 993  
 994      // Other information getting methods ==========================================.
 995  
 996      /**
 997       * Returns instance of page renderer
 998       *
 999       * @param string $component name such as 'core', 'mod_forum' or 'qtype_multichoice'.
1000       * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
1001       * @param string $target one of rendering target constants
1002       * @return renderer_base
1003       */
1004      public function get_renderer($component, $subtype = null, $target = null) {
1005          if ($this->pagelayout === 'maintenance') {
1006              // If the page is using the maintenance layout then we're going to force target to maintenance.
1007              // This leads to a special core renderer that is designed to block access to API's that are likely unavailable for this
1008              // page layout.
1009              $target = RENDERER_TARGET_MAINTENANCE;
1010          }
1011          return $this->magic_get_theme()->get_renderer($this, $component, $subtype, $target);
1012      }
1013  
1014      /**
1015       * Checks to see if there are any items on the navbar object
1016       *
1017       * @return bool true if there are, false if not
1018       */
1019      public function has_navbar() {
1020          if ($this->_navbar === null) {
1021              $this->_navbar = new navbar($this);
1022          }
1023          return $this->_navbar->has_items();
1024      }
1025  
1026      /**
1027       * Switches from the regular requirements manager to the fragment requirements manager to
1028       * capture all necessary JavaScript to display a chunk of HTML such as an mform. This is for use
1029       * by the get_fragment() web service and not for use elsewhere.
1030       */
1031      public function start_collecting_javascript_requirements() {
1032          global $CFG;
1033          require_once($CFG->libdir.'/outputfragmentrequirementslib.php');
1034  
1035          // Check that the requirements manager has not already been switched.
1036          if (get_class($this->_requires) == 'fragment_requirements_manager') {
1037              throw new coding_exception('JavaScript collection has already been started.');
1038          }
1039          // The header needs to have been called to flush out the generic JavaScript for the page. This allows only
1040          // JavaScript for the fragment to be collected. _wherethemewasinitialised is set when header() is called.
1041          if (!empty($this->_wherethemewasinitialised)) {
1042              // Change the current requirements manager over to the fragment manager to capture JS.
1043              $this->savedrequires = $this->_requires;
1044              $this->_requires = new fragment_requirements_manager();
1045          } else {
1046              throw new coding_exception('$OUTPUT->header() needs to be called before collecting JavaScript requirements.');
1047          }
1048      }
1049  
1050      /**
1051       * Switches back from collecting fragment JS requirement to the original requirement manager
1052       */
1053      public function end_collecting_javascript_requirements() {
1054          if ($this->savedrequires === null) {
1055              throw new coding_exception('JavaScript collection has not been started.');
1056          }
1057          $this->_requires = $this->savedrequires;
1058          $this->savedrequires = null;
1059      }
1060  
1061      /**
1062       * Should the current user see this page in editing mode.
1063       * That is, are they allowed to edit this page, and are they currently in
1064       * editing mode.
1065       * @return bool
1066       */
1067      public function user_is_editing() {
1068          global $USER;
1069          return !empty($USER->editing) && $this->user_allowed_editing();
1070      }
1071  
1072      /**
1073       * Does the user have permission to edit blocks on this page.
1074       * Can be forced to false by calling the force_lock_all_blocks() method.
1075       *
1076       * @return bool
1077       */
1078      public function user_can_edit_blocks() {
1079          return $this->_forcelockallblocks ? false : has_capability($this->_blockseditingcap, $this->_context);
1080      }
1081  
1082      /**
1083       * Does the user have permission to see this page in editing mode.
1084       * @return bool
1085       */
1086      public function user_allowed_editing() {
1087          return has_any_capability($this->all_editing_caps(), $this->_context);
1088      }
1089  
1090      /**
1091       * Get a description of this page. Normally displayed in the footer in developer debug mode.
1092       * @return string
1093       */
1094      public function debug_summary() {
1095          $summary = '';
1096          $summary .= 'General type: ' . $this->pagelayout . '. ';
1097          if (!during_initial_install()) {
1098              $summary .= 'Context ' . $this->context->get_context_name() . ' (context id ' . $this->_context->id . '). ';
1099          }
1100          $summary .= 'Page type ' . $this->pagetype .  '. ';
1101          if ($this->subpage) {
1102              $summary .= 'Sub-page ' . $this->subpage .  '. ';
1103          }
1104          return $summary;
1105      }
1106  
1107      // Setter methods =============================================================.
1108  
1109      /**
1110       * Set the state.
1111       *
1112       * The state must be one of that STATE_... constants, and the state is only allowed to advance one step at a time.
1113       *
1114       * @param int $state The new state.
1115       * @throws coding_exception
1116       */
1117      public function set_state($state) {
1118          if ($state != $this->_state + 1 || $state > self::STATE_DONE) {
1119              throw new coding_exception('Invalid state passed to moodle_page::set_state. We are in state ' .
1120                      $this->_state . ' and state ' . $state . ' was requested.');
1121          }
1122  
1123          if ($state == self::STATE_PRINTING_HEADER) {
1124              $this->starting_output();
1125          }
1126  
1127          $this->_state = $state;
1128      }
1129  
1130      /**
1131       * Set the current course. This sets both $PAGE->course and $COURSE. It also
1132       * sets the right theme and locale.
1133       *
1134       * Normally you don't need to call this function yourself, require_login will
1135       * call it for you if you pass a $course to it. You can use this function
1136       * on pages that do need to call require_login().
1137       *
1138       * Sets $PAGE->context to the course context, if it is not already set.
1139       *
1140       * @param stdClass $course the course to set as the global course.
1141       * @throws coding_exception
1142       */
1143      public function set_course($course) {
1144          global $COURSE, $PAGE, $CFG, $SITE;
1145  
1146          if (empty($course->id)) {
1147              throw new coding_exception('$course passed to moodle_page::set_course does not look like a proper course object.');
1148          }
1149  
1150          $this->ensure_theme_not_set();
1151  
1152          if (!empty($this->_course->id) && $this->_course->id != $course->id) {
1153              $this->_categories = null;
1154          }
1155  
1156          $this->_course = clone($course);
1157  
1158          if ($this === $PAGE) {
1159              $COURSE = $this->_course;
1160              moodle_setlocale();
1161          }
1162  
1163          if (!$this->_context) {
1164              $this->set_context(context_course::instance($this->_course->id));
1165          }
1166  
1167          // Notify course format that this page is set for the course.
1168          if ($this->_course->id != $SITE->id) {
1169              require_once($CFG->dirroot.'/course/lib.php');
1170              $courseformat = course_get_format($this->_course);
1171              $this->add_body_class('format-'. $courseformat->get_format());
1172              $courseformat->page_set_course($this);
1173          } else {
1174              $this->add_body_class('format-site');
1175          }
1176      }
1177  
1178      /**
1179       * Set the main context to which this page belongs.
1180       *
1181       * @param context $context a context object. You normally get this with context_xxxx::instance().
1182       */
1183      public function set_context($context) {
1184          if ($context === null) {
1185              // Extremely ugly hack which sets context to some value in order to prevent warnings,
1186              // use only for core error handling!!!!
1187              if (!$this->_context) {
1188                  $this->_context = context_system::instance();
1189              }
1190              return;
1191          }
1192          // Ideally we should set context only once.
1193          if (isset($this->_context) && $context->id !== $this->_context->id) {
1194              $current = $this->_context->contextlevel;
1195              if ($current == CONTEXT_SYSTEM or $current == CONTEXT_COURSE) {
1196                  // Hmm - not ideal, but it might produce too many warnings due to the design of require_login.
1197              } else if ($current == CONTEXT_MODULE and ($parentcontext = $context->get_parent_context()) and
1198                  $this->_context->id == $parentcontext->id) {
1199                  // Hmm - most probably somebody did require_login() and after that set the block context.
1200              } else {
1201                  // We do not want devs to do weird switching of context levels on the fly because we might have used
1202                  // the context already such as in text filter in page title.
1203                  debugging("Coding problem: unsupported modification of PAGE->context from {$current} to {$context->contextlevel}");
1204              }
1205          }
1206  
1207          $this->_context = $context;
1208      }
1209  
1210      /**
1211       * The course module that this page belongs to (if it does belong to one).
1212       *
1213       * @param stdClass|cm_info $cm a record from course_modules table or cm_info from get_fast_modinfo().
1214       * @param stdClass $course
1215       * @param stdClass $module
1216       * @return void
1217       * @throws coding_exception
1218       */
1219      public function set_cm($cm, $course = null, $module = null) {
1220          global $DB, $CFG, $SITE;
1221  
1222          if (!isset($cm->id) || !isset($cm->course)) {
1223              throw new coding_exception('Invalid $cm. It has to be instance of cm_info or record from the course_modules table.');
1224          }
1225  
1226          if (!$this->_course || $this->_course->id != $cm->course) {
1227              if (!$course) {
1228                  $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
1229              }
1230              if ($course->id != $cm->course) {
1231                  throw new coding_exception('The course you passed to $PAGE->set_cm does not correspond to the $cm.');
1232              }
1233              $this->set_course($course);
1234          }
1235  
1236          // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
1237          if (!($cm instanceof cm_info)) {
1238              $modinfo = get_fast_modinfo($this->_course);
1239              $cm = $modinfo->get_cm($cm->id);
1240          }
1241          $this->_cm = $cm;
1242  
1243          // Unfortunately the context setting is a mess.
1244          // Let's try to work around some common block problems and show some debug messages.
1245          if (empty($this->_context) or $this->_context->contextlevel != CONTEXT_BLOCK) {
1246              $context = context_module::instance($cm->id);
1247              $this->set_context($context);
1248          }
1249  
1250          if ($module) {
1251              $this->set_activity_record($module);
1252          }
1253  
1254          // Notify course format that this page is set for the course module.
1255          if ($this->_course->id != $SITE->id) {
1256              require_once($CFG->dirroot.'/course/lib.php');
1257              course_get_format($this->_course)->page_set_cm($this);
1258          }
1259      }
1260  
1261      /**
1262       * Sets the activity record. This could be a row from the main table for a
1263       * module. For instance if the current module (cm) is a forum this should be a row
1264       * from the forum table.
1265       *
1266       * @param stdClass $module A row from the main database table for the module that this page belongs to.
1267       * @throws coding_exception
1268       */
1269      public function set_activity_record($module) {
1270          if (is_null($this->_cm)) {
1271              throw new coding_exception('You cannot call $PAGE->set_activity_record until after $PAGE->cm has been set.');
1272          }
1273          if ($module->id != $this->_cm->instance || $module->course != $this->_course->id) {
1274              throw new coding_exception('The activity record does not seem to correspond to the cm that has been set.');
1275          }
1276          $this->_module = $module;
1277      }
1278  
1279      /**
1280       * Sets the pagetype to use for this page.
1281       *
1282       * Normally you do not need to set this manually, it is automatically created
1283       * from the script name. However, on some pages this is overridden.
1284       * For example the page type for course/view.php includes the course format,
1285       * for example 'course-view-weeks'. This gets used as the id attribute on
1286       * <body> and also for determining which blocks are displayed.
1287       *
1288       * @param string $pagetype e.g. 'my-index' or 'mod-quiz-attempt'.
1289       */
1290      public function set_pagetype($pagetype) {
1291          $this->_pagetype = $pagetype;
1292      }
1293  
1294      /**
1295       * Sets the layout to use for this page.
1296       *
1297       * The page layout determines how the page will be displayed, things such as
1298       * block regions, content areas, etc are controlled by the layout.
1299       * The theme in use for the page will determine that the layout contains.
1300       *
1301       * This properly defaults to 'base', so you only need to call this function if
1302       * you want something different. The exact range of supported layouts is specified
1303       * in the standard theme.
1304       *
1305       * For an idea of the common page layouts see
1306       * {@link https://docs.moodle.org/dev/Themes_overview#Layouts}
1307       * But please keep in mind that it may be (and normally is) out of date.
1308       * The only place to find an accurate up-to-date list of the page layouts
1309       * available for your version of Moodle is {@link theme/base/config.php}
1310       *
1311       * @param string $pagelayout the page layout this is. For example 'popup', 'home'.
1312       */
1313      public function set_pagelayout($pagelayout) {
1314          global $SESSION;
1315  
1316          if (!empty($SESSION->forcepagelayout)) {
1317              $this->_pagelayout = $SESSION->forcepagelayout;
1318          } else {
1319              // Uncomment this to debug theme pagelayout issues like missing blocks.
1320              // if (!empty($this->_wherethemewasinitialised) && $pagelayout != $this->_pagelayout)
1321              //     debugging('Page layout has already been set and cannot be changed.', DEBUG_DEVELOPER);
1322              $this->_pagelayout = $pagelayout;
1323          }
1324      }
1325  
1326      /**
1327       * If context->id and pagetype are not enough to uniquely identify this page,
1328       * then you can set a subpage id as well. For example, the tags page sets
1329       *
1330       * @param string $subpage an arbitrary identifier that, along with context->id
1331       *      and pagetype, uniquely identifies this page.
1332       */
1333      public function set_subpage($subpage) {
1334          if (empty($subpage)) {
1335              $this->_subpage = '';
1336          } else {
1337              $this->_subpage = $subpage;
1338          }
1339      }
1340  
1341      /**
1342       * Force set secondary_nav. Useful in cases where we dealing with non course modules. e.g. blocks, tools.
1343       * @param secondary $nav
1344       */
1345      public function set_secondarynav(secondary $nav) {
1346          $this->_secondarynav = $nav;
1347      }
1348  
1349      /**
1350       * Adds a CSS class to the body tag of the page.
1351       *
1352       * @param string $class add this class name ot the class attribute on the body tag.
1353       * @throws coding_exception
1354       */
1355      public function add_body_class($class) {
1356          if ($this->_state > self::STATE_BEFORE_HEADER) {
1357              throw new coding_exception('Cannot call moodle_page::add_body_class after output has been started.');
1358          }
1359          $this->_bodyclasses[$class] = 1;
1360      }
1361  
1362      /**
1363       * Adds an array of body classes to the body tag of this page.
1364       *
1365       * @param array $classes this utility method calls add_body_class for each array element.
1366       */
1367      public function add_body_classes($classes) {
1368          foreach ($classes as $class) {
1369              $this->add_body_class($class);
1370          }
1371      }
1372  
1373      /**
1374       * Sets the title for the page.
1375       *
1376       * This is normally used within the title tag in the head of the page.
1377       *
1378       * Some tips for providing a meaningful page title:
1379       * - The page title must be accurate and informative.
1380       * - If the page causes a change of context (e.g. a search functionality), it should describe the result or change of context
1381       *   to the user.
1382       * - It should be concise.
1383       * - If possible, it should uniquely identify the page.
1384       * - The most identifying information should come first. (e.g. Submit assignment | Assignment | Moodle)
1385       *
1386       * For more information, see
1387       * {@link https://www.w3.org/WAI/WCAG21/Understanding/page-titled Understanding Success Criterion 2.4.2: Page Titled}
1388       *
1389       * @param string $title the title that should go in the <head> section of the HTML of this page.
1390       * @param bool $appendsitename Appends site name at the end of the given title. It is encouraged to append the site name as this
1391       *                              especially helps with accessibility. If it's necessary to override this, please keep in mind
1392       *                              to ensure that the title provides a concise summary of the page being displayed.
1393       */
1394      public function set_title($title, bool $appendsitename = true) {
1395          global $CFG;
1396  
1397          $title = format_string($title);
1398          $title = strip_tags($title);
1399          $title = str_replace('"', '&quot;', $title);
1400  
1401          if ($appendsitename) {
1402              // Append the site name at the end of the page title.
1403              $sitenamedisplay = 'shortname';
1404              if (!empty($CFG->sitenameintitle)) {
1405                  $sitenamedisplay = $CFG->sitenameintitle;
1406              }
1407              $site = get_site();
1408              if (empty(trim($site->{$sitenamedisplay} ?? ''))) {
1409                  // If for some reason the site name is not yet set, fall back to 'Moodle'.
1410                  $title .= self::TITLE_SEPARATOR . 'Moodle';
1411              } else {
1412                  $title .= self::TITLE_SEPARATOR . format_string($site->{$sitenamedisplay});
1413              }
1414          }
1415  
1416          $this->_title = $title;
1417      }
1418  
1419      /**
1420       * Sets the heading to use for the page.
1421       * This is normally used as the main heading at the top of the content.
1422       *
1423       * @param string $heading the main heading that should be displayed at the top of the <body>.
1424       * @param bool $applyformatting apply format_string() - by default true.
1425       */
1426      public function set_heading($heading, bool $applyformatting = true) {
1427          $this->_heading = $applyformatting ? format_string($heading) : clean_text($heading);
1428      }
1429  
1430      /**
1431       * Sets some HTML to use next to the heading {@link moodle_page::set_heading()}
1432       *
1433       * @param string $menu The menu/content to show in the heading
1434       */
1435      public function set_headingmenu($menu) {
1436          $this->_headingmenu = $menu;
1437      }
1438  
1439      /**
1440       * Set the course category this page belongs to manually.
1441       *
1442       * This automatically sets $PAGE->course to be the site course. You cannot
1443       * use this method if you have already set $PAGE->course - in that case,
1444       * the category must be the one that the course belongs to. This also
1445       * automatically sets the page context to the category context.
1446       *
1447       * @param int $categoryid The id of the category to set.
1448       * @throws coding_exception
1449       */
1450      public function set_category_by_id($categoryid) {
1451          global $SITE;
1452          if (!is_null($this->_course)) {
1453              throw new coding_exception('Course has already been set. You cannot change the category now.');
1454          }
1455          if (is_array($this->_categories)) {
1456              throw new coding_exception('Course category has already been set. You cannot to change it now.');
1457          }
1458          $this->ensure_theme_not_set();
1459          $this->set_course($SITE);
1460          $this->load_category($categoryid);
1461          $this->set_context(context_coursecat::instance($categoryid));
1462      }
1463  
1464      /**
1465       * Set a different path to use for the 'Help and documentation' link.
1466       *
1467       * By default, it uses the pagetype, which is normally the same as the
1468       * script name. So, for example, for mod/quiz/attempt.php, pagetype is
1469       * mod-quiz-attempt, and so docspath is mod/quiz/attempt.
1470       *
1471       * @param string $path the path to use at the end of the moodle docs URL.
1472       */
1473      public function set_docs_path($path) {
1474          $this->_docspath = $path;
1475      }
1476  
1477      /**
1478       * You should call this method from every page to set the URL that should be used to return to this page.
1479       *
1480       * Used, for example, by the blocks editing UI to know where to return the
1481       * user after an action.
1482       * For example, course/view.php does:
1483       *      $id = optional_param('id', 0, PARAM_INT);
1484       *      $PAGE->set_url('/course/view.php', array('id' => $id));
1485       *
1486       * @param moodle_url|string $url URL relative to $CFG->wwwroot or {@link moodle_url} instance
1487       * @param array $params parameters to add to the URL
1488       * @throws coding_exception
1489       */
1490      public function set_url($url, array $params = null) {
1491          global $CFG;
1492  
1493          if (is_string($url) && strpos($url, 'http') !== 0) {
1494              if (strpos($url, '/') === 0) {
1495                  // Add the wwwroot to the relative url.
1496                  $url = $CFG->wwwroot . $url;
1497              } else {
1498                  throw new coding_exception('Invalid parameter $url, has to be full url or in shortened form starting with /.');
1499              }
1500          }
1501  
1502          $this->_url = new moodle_url($url, $params);
1503  
1504          $fullurl = $this->_url->out_omit_querystring();
1505          if (strpos($fullurl, "$CFG->wwwroot/") !== 0) {
1506              debugging('Most probably incorrect set_page() url argument, it does not match the wwwroot!');
1507          }
1508          $shorturl = str_replace("$CFG->wwwroot/", '', $fullurl);
1509  
1510          if (is_null($this->_pagetype)) {
1511              $this->initialise_default_pagetype($shorturl);
1512          }
1513      }
1514  
1515      /**
1516       * Make sure page URL does not contain the given URL parameter.
1517       *
1518       * This should not be necessary if the script has called set_url properly.
1519       * However, in some situations like the block editing actions; when the URL
1520       * has been guessed, it will contain dangerous block-related actions.
1521       * Therefore, the blocks code calls this function to clean up such parameters
1522       * before doing any redirect.
1523       *
1524       * @param string $param the name of the parameter to make sure is not in the
1525       * page URL.
1526       */
1527      public function ensure_param_not_in_url($param) {
1528          $this->_url->remove_params($param);
1529      }
1530  
1531      /**
1532       * Sets an alternative version of this page.
1533       *
1534       * There can be alternate versions of some pages (for example an RSS feed version).
1535       * Call this method for each alternative version available.
1536       * For each alternative version a link will be included in the <head> tag.
1537       *
1538       * @param string $title The title to give the alternate version.
1539       * @param string|moodle_url $url The URL of the alternate version.
1540       * @param string $mimetype The mime-type of the alternate version.
1541       * @throws coding_exception
1542       */
1543      public function add_alternate_version($title, $url, $mimetype) {
1544          if ($this->_state > self::STATE_BEFORE_HEADER) {
1545              throw new coding_exception('Cannot call moodle_page::add_alternate_version after output has been started.');
1546          }
1547          $alt = new stdClass;
1548          $alt->title = $title;
1549          $alt->url = $url;
1550          $this->_alternateversions[$mimetype] = $alt;
1551      }
1552  
1553      /**
1554       * Specify a form control should be focused when the page has loaded.
1555       *
1556       * @param string $controlid the id of the HTML element to be focused.
1557       */
1558      public function set_focuscontrol($controlid) {
1559          $this->_focuscontrol = $controlid;
1560      }
1561  
1562      /**
1563       * Specify a fragment of HTML that goes where the 'Turn editing on' button normally goes.
1564       *
1565       * @param string $html the HTML to display there.
1566       */
1567      public function set_button($html) {
1568          $this->_button = $html;
1569      }
1570  
1571      /**
1572       * Set the capability that allows users to edit blocks on this page.
1573       *
1574       * Normally the default of 'moodle/site:manageblocks' is used, but a few
1575       * pages like the My Moodle page need to use a different capability
1576       * like 'moodle/my:manageblocks'.
1577       *
1578       * @param string $capability a capability.
1579       */
1580      public function set_blocks_editing_capability($capability) {
1581          $this->_blockseditingcap = $capability;
1582      }
1583  
1584      /**
1585       * Some pages let you turn editing on for reasons other than editing blocks.
1586       * If that is the case, you can pass other capabilities that let the user
1587       * edit this page here.
1588       *
1589       * @param string|array $capability either a capability, or an array of capabilities.
1590       */
1591      public function set_other_editing_capability($capability) {
1592          if (is_array($capability)) {
1593              $this->_othereditingcaps = array_unique($this->_othereditingcaps + $capability);
1594          } else {
1595              $this->_othereditingcaps[] = $capability;
1596          }
1597      }
1598  
1599      /**
1600       * Sets whether the browser should cache this page or not.
1601       *
1602       * @param bool $cacheable can this page be cached by the user's browser.
1603       */
1604      public function set_cacheable($cacheable) {
1605          $this->_cacheable = $cacheable;
1606      }
1607  
1608      /**
1609       * Sets the page to periodically refresh
1610       *
1611       * This function must be called before $OUTPUT->header has been called or
1612       * a coding exception will be thrown.
1613       *
1614       * @param int $delay Sets the delay before refreshing the page, if set to null refresh is cancelled.
1615       * @throws coding_exception
1616       */
1617      public function set_periodic_refresh_delay($delay = null) {
1618          if ($this->_state > self::STATE_BEFORE_HEADER) {
1619              throw new coding_exception('You cannot set a periodic refresh delay after the header has been printed');
1620          }
1621          if ($delay === null) {
1622              $this->_periodicrefreshdelay = null;
1623          } else if (is_int($delay)) {
1624              $this->_periodicrefreshdelay = $delay;
1625          }
1626      }
1627  
1628      /**
1629       * Force this page to use a particular theme.
1630       *
1631       * Please use this cautiously.
1632       * It is only intended to be used by the themes selector admin page.
1633       *
1634       * @param string $themename the name of the theme to use.
1635       */
1636      public function force_theme($themename) {
1637          $this->ensure_theme_not_set();
1638          $this->_theme = theme_config::load($themename);
1639      }
1640  
1641      /**
1642       * Reload theme settings.
1643       *
1644       * This is used when we need to reset settings
1645       * because they are now double cached in theme.
1646       */
1647      public function reload_theme() {
1648          if (!is_null($this->_theme)) {
1649              $this->_theme = theme_config::load($this->_theme->name);
1650          }
1651      }
1652  
1653      /**
1654       * Remove access to editing/moving on all blocks on a page.
1655       * This overrides any capabilities and is intended only for pages where no user (including admins) should be able to
1656       * modify blocks on the page (eg My Courses).
1657       *
1658       * @return void
1659       */
1660      public function force_lock_all_blocks(): void {
1661          $this->_forcelockallblocks = true;
1662      }
1663  
1664      /**
1665       * @deprecated since Moodle 3.4
1666       */
1667      public function https_required() {
1668          throw new coding_exception('https_required() cannot be used anymore.');
1669      }
1670  
1671      /**
1672       * @deprecated since Moodle 3.4
1673       */
1674      public function verify_https_required() {
1675          throw new coding_exception('verify_https_required() cannot be used anymore.');
1676      }
1677  
1678      // Initialisation methods =====================================================
1679      // These set various things up in a default way.
1680  
1681      /**
1682       * This method is called when the page first moves out of the STATE_BEFORE_HEADER
1683       * state. This is our last change to initialise things.
1684       */
1685      protected function starting_output() {
1686          global $CFG;
1687  
1688          if (!during_initial_install()) {
1689              $this->blocks->load_blocks();
1690              if (empty($this->_block_actions_done)) {
1691                  $this->_block_actions_done = true;
1692                  if ($this->blocks->process_url_actions($this)) {
1693                      redirect($this->url->out(false));
1694                  }
1695              }
1696              $this->blocks->create_all_block_instances();
1697          }
1698  
1699          // If maintenance mode is on, change the page header.
1700          if (!empty($CFG->maintenance_enabled)) {
1701              $this->set_button('<a href="' . $CFG->wwwroot . '/' . $CFG->admin .
1702                      '/settings.php?section=maintenancemode">' . get_string('maintenancemode', 'admin') .
1703                      '</a> ' . $this->button);
1704  
1705              $this->set_title(get_string('maintenancemode', 'admin'));
1706          }
1707  
1708          $this->initialise_standard_body_classes();
1709      }
1710  
1711      /**
1712       * Method for use by Moodle core to set up the theme. Do not
1713       * use this in your own code.
1714       *
1715       * Make sure the right theme for this page is loaded. Tell our
1716       * blocks_manager about the theme block regions, and then, if
1717       * we are $PAGE, set up the global $OUTPUT.
1718       *
1719       * @return void
1720       */
1721      public function initialise_theme_and_output() {
1722          global $OUTPUT, $PAGE, $SITE, $CFG;
1723  
1724          if (!empty($this->_wherethemewasinitialised)) {
1725              return;
1726          }
1727  
1728          if (!during_initial_install()) {
1729              // Detect PAGE->context mess.
1730              $this->magic_get_context();
1731          }
1732  
1733          if (!$this->_course && !during_initial_install()) {
1734              $this->set_course($SITE);
1735          }
1736  
1737          if (is_null($this->_theme)) {
1738              $themename = $this->resolve_theme();
1739              $this->_theme = theme_config::load($themename);
1740          }
1741  
1742          $this->_theme->setup_blocks($this->pagelayout, $this->blocks);
1743  
1744          if ($this === $PAGE) {
1745              $target = null;
1746              if ($this->pagelayout === 'maintenance') {
1747                  // If the page is using the maintenance layout then we're going to force target to maintenance.
1748                  // This leads to a special core renderer that is designed to block access to API's that are likely unavailable for this
1749                  // page layout.
1750                  $target = RENDERER_TARGET_MAINTENANCE;
1751              }
1752              $OUTPUT = $this->get_renderer('core', null, $target);
1753          }
1754  
1755          if (!during_initial_install()) {
1756              $filtermanager = filter_manager::instance();
1757              $filtermanager->setup_page_for_globally_available_filters($this);
1758          }
1759  
1760          $this->_wherethemewasinitialised = debug_backtrace();
1761      }
1762  
1763      /**
1764       * For diagnostic/debugging purposes, find where the theme setup was triggered.
1765       *
1766       * @return null|array null if theme not yet setup. Stacktrace if it was.
1767       */
1768      public function get_where_theme_was_initialised() {
1769          return $this->_wherethemewasinitialised;
1770      }
1771  
1772      /**
1773       * Reset the theme and output for a new context. This only makes sense from
1774       * external::validate_context(). Do not cheat.
1775       *
1776       * @return string the name of the theme that should be used on this page.
1777       */
1778      public function reset_theme_and_output() {
1779          global $COURSE, $SITE;
1780  
1781          $COURSE = clone($SITE);
1782          $this->_theme = null;
1783          $this->_wherethemewasinitialised = null;
1784          $this->_course = null;
1785          $this->_cm = null;
1786          $this->_module = null;
1787          $this->_context = null;
1788      }
1789  
1790      /**
1791       * Work out the theme this page should use.
1792       *
1793       * This depends on numerous $CFG settings, and the properties of this page.
1794       *
1795       * @return string the name of the theme that should be used on this page.
1796       */
1797      protected function resolve_theme() {
1798          global $CFG, $USER, $SESSION;
1799  
1800          if (empty($CFG->themeorder)) {
1801              $themeorder = array('course', 'category', 'session', 'user', 'cohort', 'site');
1802          } else {
1803              $themeorder = $CFG->themeorder;
1804              // Just in case, make sure we always use the site theme if nothing else matched.
1805              $themeorder[] = 'site';
1806          }
1807  
1808          $mnetpeertheme = '';
1809          $mnetvarsok = isset($CFG->mnet_localhost_id) && isset($USER->mnethostid);
1810          if (isloggedin() and $mnetvarsok and $USER->mnethostid != $CFG->mnet_localhost_id) {
1811              require_once($CFG->dirroot.'/mnet/peer.php');
1812              $mnetpeer = new mnet_peer();
1813              $mnetpeer->set_id($USER->mnethostid);
1814              if ($mnetpeer->force_theme == 1 && $mnetpeer->theme != '') {
1815                  $mnetpeertheme = $mnetpeer->theme;
1816              }
1817          }
1818  
1819          $devicetheme = core_useragent::get_device_type_theme($this->devicetypeinuse);
1820  
1821          // The user is using another device than default, and we have a theme for that, we should use it.
1822          $hascustomdevicetheme = core_useragent::DEVICETYPE_DEFAULT != $this->devicetypeinuse && !empty($devicetheme);
1823  
1824          foreach ($themeorder as $themetype) {
1825  
1826              switch ($themetype) {
1827                  case 'course':
1828                      if (!empty($CFG->allowcoursethemes) && !empty($this->_course->theme) && !$hascustomdevicetheme) {
1829                          return $this->_course->theme;
1830                      }
1831                  break;
1832  
1833                  case 'category':
1834                      if (!empty($CFG->allowcategorythemes) && !empty($this->_course) && !$hascustomdevicetheme) {
1835                          $categories = $this->categories;
1836                          foreach ($categories as $category) {
1837                              if (!empty($category->theme)) {
1838                                  return $category->theme;
1839                              }
1840                          }
1841                      }
1842                  break;
1843  
1844                  case 'session':
1845                      if (!empty($SESSION->theme)) {
1846                          return $SESSION->theme;
1847                      }
1848                  break;
1849  
1850                  case 'user':
1851                      if (!empty($CFG->allowuserthemes) && !empty($USER->theme) && !$hascustomdevicetheme) {
1852                          if ($mnetpeertheme) {
1853                              return $mnetpeertheme;
1854                          } else {
1855                              return $USER->theme;
1856                          }
1857                      }
1858                  break;
1859  
1860                  case 'cohort':
1861                      if (!empty($CFG->allowcohortthemes) && !empty($USER->cohorttheme) && !$hascustomdevicetheme) {
1862                          return $USER->cohorttheme;
1863                      }
1864                  break;
1865  
1866                  case 'site':
1867                      if ($mnetpeertheme) {
1868                          return $mnetpeertheme;
1869                      }
1870                      // First try for the device the user is using.
1871                      if (!empty($devicetheme)) {
1872                          return $devicetheme;
1873                      }
1874                      // Next try for the default device (as a fallback).
1875                      $devicetheme = core_useragent::get_device_type_theme(core_useragent::DEVICETYPE_DEFAULT);
1876                      if (!empty($devicetheme)) {
1877                          return $devicetheme;
1878                      }
1879                      // The default device theme isn't set up - use the overall default theme.
1880                      return theme_config::DEFAULT_THEME;
1881              }
1882          }
1883  
1884          // We should most certainly have resolved a theme by now. Something has gone wrong.
1885          debugging('Error resolving the theme to use for this page.', DEBUG_DEVELOPER);
1886          return theme_config::DEFAULT_THEME;
1887      }
1888  
1889  
1890      /**
1891       * Sets ->pagetype from the script name. For example, if the script that was
1892       * run is mod/quiz/view.php, ->pagetype will be set to 'mod-quiz-view'.
1893       *
1894       * @param string $script the path to the script that should be used to
1895       * initialise ->pagetype. If not passed the $SCRIPT global will be used.
1896       * If legacy code has set $CFG->pagepath that will be used instead, and a
1897       * developer warning issued.
1898       */
1899      protected function initialise_default_pagetype($script = null) {
1900          global $CFG, $SCRIPT;
1901  
1902          if (isset($CFG->pagepath)) {
1903              debugging('Some code appears to have set $CFG->pagepath. That was a horrible deprecated thing. ' .
1904                      'Don\'t do it! Try calling $PAGE->set_pagetype() instead.');
1905              $script = $CFG->pagepath;
1906              unset($CFG->pagepath);
1907          }
1908  
1909          if (is_null($script)) {
1910              $script = ltrim($SCRIPT ?? '', '/');
1911              $len = strlen($CFG->admin);
1912              if (substr($script, 0, $len) == $CFG->admin) {
1913                  $script = 'admin' . substr($script, $len);
1914              }
1915          }
1916  
1917          $path = str_replace('.php', '', $script);
1918          if (substr($path, -1) == '/') {
1919              $path .= 'index';
1920          }
1921  
1922          if (empty($path) || $path == 'index') {
1923              $this->_pagetype = 'site-index';
1924          } else {
1925              $this->_pagetype = str_replace('/', '-', $path);
1926          }
1927      }
1928  
1929      /**
1930       * Initialises the CSS classes that will be added to body tag of the page.
1931       *
1932       * The function is responsible for adding all of the critical CSS classes
1933       * that describe the current page, and its state.
1934       * This includes classes that describe the following for example:
1935       *    - Current language
1936       *    - Language direction
1937       *    - YUI CSS initialisation
1938       *    - Pagelayout
1939       * These are commonly used in CSS to target specific types of pages.
1940       */
1941      protected function initialise_standard_body_classes() {
1942          global $CFG, $USER;
1943  
1944          $pagetype = $this->pagetype;
1945          if ($pagetype == 'site-index') {
1946              $this->_legacyclass = 'course';
1947          } else if (substr($pagetype, 0, 6) == 'admin-') {
1948              $this->_legacyclass = 'admin';
1949          }
1950          $this->add_body_class($this->_legacyclass);
1951  
1952          $pathbits = explode('-', trim($pagetype));
1953          for ($i = 1; $i < count($pathbits); $i++) {
1954              $this->add_body_class('path-' . join('-', array_slice($pathbits, 0, $i)));
1955          }
1956  
1957          $this->add_body_classes(core_useragent::get_browser_version_classes());
1958          $this->add_body_class('dir-' . get_string('thisdirection', 'langconfig'));
1959          $this->add_body_class('lang-' . current_language());
1960          $this->add_body_class('yui-skin-sam'); // Make YUI happy, if it is used.
1961          $this->add_body_class('yui3-skin-sam'); // Make YUI3 happy, if it is used.
1962          $this->add_body_class($this->url_to_class_name($CFG->wwwroot));
1963  
1964          // Extra class describing current page layout.
1965          $this->add_body_class('pagelayout-' . $this->_pagelayout);
1966  
1967          if (!during_initial_install()) {
1968              $this->add_body_class('course-' . $this->_course->id);
1969              $this->add_body_class('context-' . $this->_context->id);
1970          }
1971  
1972          if (!empty($this->_cm)) {
1973              $this->add_body_class('cmid-' . $this->_cm->id);
1974              $this->add_body_class('cm-type-' . $this->_cm->modname);
1975          }
1976  
1977          if (!empty($CFG->allowcategorythemes) && !empty($this->_course)) {
1978              $this->ensure_category_loaded();
1979              foreach ($this->_categories as $catid => $notused) {
1980                  $this->add_body_class('category-' . $catid);
1981              }
1982          } else {
1983              $catid = 0;
1984              if (is_array($this->_categories)) {
1985                  $catids = array_keys($this->_categories);
1986                  $catid = reset($catids);
1987              } else if (!empty($this->_course->category)) {
1988                  $catid = $this->_course->category;
1989              }
1990              if ($catid) {
1991                  $this->add_body_class('category-' . $catid);
1992              }
1993          }
1994  
1995          if (!isloggedin()) {
1996              $this->add_body_class('notloggedin');
1997          }
1998  
1999          if ($this->user_is_editing()) {
2000              $this->add_body_class('editing');
2001              if (optional_param('bui_moveid', false, PARAM_INT)) {
2002                  $this->add_body_class('blocks-moving');
2003              }
2004          }
2005  
2006          if (!empty($CFG->blocksdrag)) {
2007              $this->add_body_class('drag');
2008          }
2009  
2010          if ($this->_devicetypeinuse != 'default') {
2011              $this->add_body_class($this->_devicetypeinuse . 'theme');
2012          }
2013  
2014          // Add class for behat site to apply behat related fixes.
2015          if (defined('BEHAT_SITE_RUNNING')) {
2016              $this->add_body_class('behat-site');
2017          }
2018      }
2019  
2020      /**
2021       * Loads the activity record for the current CM object associated with this
2022       * page.
2023       *
2024       * This will load {@link moodle_page::$_module} with a row from the related
2025       * module table in the database.
2026       * For instance if {@link moodle_page::$_cm} is a forum then a row from the
2027       * forum table will be loaded.
2028       */
2029      protected function load_activity_record() {
2030          global $DB;
2031          if (is_null($this->_cm)) {
2032              return;
2033          }
2034          $this->_module = $DB->get_record($this->_cm->modname, array('id' => $this->_cm->instance));
2035      }
2036  
2037      /**
2038       * This function ensures that the category of the current course has been
2039       * loaded, and if not, the function loads it now.
2040       *
2041       * @return void
2042       * @throws coding_exception
2043       */
2044      protected function ensure_category_loaded() {
2045          if (is_array($this->_categories)) {
2046              return; // Already done.
2047          }
2048          if (is_null($this->_course)) {
2049              throw new coding_exception('Attempt to get the course category for this page before the course was set.');
2050          }
2051          if ($this->_course->category == 0) {
2052              $this->_categories = array();
2053          } else {
2054              $this->load_category($this->_course->category);
2055          }
2056      }
2057  
2058      /**
2059       * Loads the requested category into the pages categories array.
2060       *
2061       * @param int $categoryid
2062       * @throws moodle_exception
2063       */
2064      protected function load_category($categoryid) {
2065          global $DB;
2066          $category = $DB->get_record('course_categories', array('id' => $categoryid));
2067          if (!$category) {
2068              throw new moodle_exception('unknowncategory');
2069          }
2070          $this->_categories[$category->id] = $category;
2071          $parentcategoryids = explode('/', trim($category->path, '/'));
2072          array_pop($parentcategoryids);
2073          foreach (array_reverse($parentcategoryids) as $catid) {
2074              $this->_categories[$catid] = null;
2075          }
2076      }
2077  
2078      /**
2079       * Ensures that the category the current course is within, as well as all of
2080       * its parent categories, have been loaded.
2081       *
2082       * @return void
2083       */
2084      protected function ensure_categories_loaded() {
2085          global $DB;
2086          $this->ensure_category_loaded();
2087          if (!is_null(end($this->_categories))) {
2088              return; // Already done.
2089          }
2090          $idstoload = array_keys($this->_categories);
2091          array_shift($idstoload);
2092          $categories = $DB->get_records_list('course_categories', 'id', $idstoload);
2093          foreach ($idstoload as $catid) {
2094              $this->_categories[$catid] = $categories[$catid];
2095          }
2096      }
2097  
2098      /**
2099       * Ensure the theme has not been loaded yet. If it has an exception is thrown.
2100       *
2101       * @throws coding_exception
2102       */
2103      protected function ensure_theme_not_set() {
2104          // This is explicitly allowed for webservices though which may process many course contexts in a single request.
2105          if (WS_SERVER) {
2106              return;
2107          }
2108  
2109          if (!is_null($this->_theme)) {
2110              throw new coding_exception('The theme has already been set up for this page ready for output. ' .
2111                      'Therefore, you can no longer change the theme, or anything that might affect what ' .
2112                      'the current theme is, for example, the course.',
2113                      'Stack trace when the theme was set up: ' . format_backtrace($this->_wherethemewasinitialised));
2114          }
2115      }
2116  
2117      /**
2118       * Converts the provided URL into a CSS class that be used within the page.
2119       * This is primarily used to add the wwwroot to the body tag as a CSS class.
2120       *
2121       * @param string $url
2122       * @return string
2123       */
2124      protected function url_to_class_name($url) {
2125          $bits = parse_url($url);
2126          $class = str_replace('.', '-', $bits['host']);
2127          if (!empty($bits['port'])) {
2128              $class .= '--' . $bits['port'];
2129          }
2130          if (!empty($bits['path'])) {
2131              $path = trim($bits['path'], '/');
2132              if ($path) {
2133                  $class .= '--' . str_replace('/', '-', $path);
2134              }
2135          }
2136          return $class;
2137      }
2138  
2139      /**
2140       * Combines all of the required editing caps for the page and returns them
2141       * as an array.
2142       *
2143       * @return array
2144       */
2145      protected function all_editing_caps() {
2146          $caps = $this->_othereditingcaps;
2147          $caps[] = $this->_blockseditingcap;
2148          return $caps;
2149      }
2150  
2151      /**
2152       * Returns true if the page URL has beem set.
2153       *
2154       * @return bool
2155       */
2156      public function has_set_url() {
2157          return ($this->_url!==null);
2158      }
2159  
2160      /**
2161       * Gets set when the block actions for the page have been processed.
2162       *
2163       * @param bool $setting
2164       */
2165      public function set_block_actions_done($setting = true) {
2166          $this->_block_actions_done = $setting;
2167      }
2168  
2169      /**
2170       * Are popup notifications allowed on this page?
2171       * Popup notifications may be disallowed in situations such as while upgrading or completing a quiz
2172       *
2173       * @return bool true if popup notifications may be displayed
2174       */
2175      public function get_popup_notification_allowed() {
2176          return $this->_popup_notification_allowed;
2177      }
2178  
2179      /**
2180       * Allow or disallow popup notifications on this page. Popups are allowed by default.
2181       *
2182       * @param bool $allowed true if notifications are allowed. False if not allowed. They are allowed by default.
2183       */
2184      public function set_popup_notification_allowed($allowed) {
2185          $this->_popup_notification_allowed = $allowed;
2186      }
2187  
2188      /**
2189       * Returns the block region having made any required theme manipulations.
2190       *
2191       * @since Moodle 2.5.1 2.6
2192       * @param string $region
2193       * @return string
2194       */
2195      public function apply_theme_region_manipulations($region) {
2196          if ($this->blockmanipulations && isset($this->blockmanipulations[$region])) {
2197              $regionwas = $region;
2198              $regionnow = $this->blockmanipulations[$region];
2199              if ($this->blocks->is_known_region($regionwas) && $this->blocks->is_known_region($regionnow)) {
2200                  // Both the before and after regions are known so we can swap them over.
2201                  return $regionnow;
2202              }
2203              // We didn't know about both, we won't swap them over.
2204              return $regionwas;
2205          }
2206          return $region;
2207      }
2208  
2209      /**
2210       * Add a report node and a specific report to the navigation.
2211       *
2212       * @param int $userid The user ID that we are looking to add this report node to.
2213       * @param array $nodeinfo Name and url of the final node that we are creating.
2214       */
2215      public function add_report_nodes($userid, $nodeinfo) {
2216          global $USER;
2217          // Try to find the specific user node.
2218          $newusernode = $this->navigation->find('user' . $userid, null);
2219          $reportnode = null;
2220          $navigationnodeerror =
2221                  'Could not find the navigation node requested. Please check that the node you are looking for exists.';
2222          if ($userid != $USER->id  || $this->context->contextlevel == CONTEXT_COURSE) {
2223              // Within a course context we need to properly indicate how we have come to the page,
2224              // regardless of whether it's currently logged in user or not.
2225              // Check that we have a valid node.
2226              if (empty($newusernode)) {
2227                  // Throw an error if we ever reach here.
2228                  throw new coding_exception($navigationnodeerror);
2229              }
2230              // Add 'Reports' to the user node.
2231              $reportnode = $newusernode->add(get_string('reports'));
2232          } else {
2233              // We are looking at our own profile.
2234              $myprofilenode = $this->settingsnav->find('myprofile', null);
2235              // Check that we do end up with a valid node.
2236              if (empty($myprofilenode)) {
2237                  // Throw an error if we ever reach here.
2238                  throw new coding_exception($navigationnodeerror);
2239              }
2240              // Add 'Reports' to our node.
2241              $reportnode = $myprofilenode->add(get_string('reports'));
2242          }
2243          // Finally add the report to the navigation tree.
2244          $reportnode->add($nodeinfo['name'], $nodeinfo['url'], navigation_node::TYPE_CUSTOM, null, null,
2245              new pix_icon('i/report', $nodeinfo['name']));
2246      }
2247  
2248      /**
2249       * Add some HTML to the list of actions to render in the header actions menu.
2250       *
2251       * @param string $html The HTML to add.
2252       */
2253      public function add_header_action(string $html) : void {
2254          $this->_headeractions[] = $html;
2255      }
2256  
2257      /**
2258       * Get the list of HTML for actions to render in the header actions menu.
2259       *
2260       * @return string[]
2261       */
2262      public function get_header_actions() : array {
2263          return $this->_headeractions;
2264      }
2265  
2266      /**
2267       * Set the flag to indicate if the region main settings should be rendered as an action
2268       * in the header actions menu rather than at the top of the content.
2269       *
2270       * @param bool $value If the settings should be in the header.
2271       */
2272      public function set_include_region_main_settings_in_header_actions(bool $value) : void {
2273          $this->_regionmainsettingsinheader = $value;
2274      }
2275  
2276      /**
2277       * Check if the  region main settings should be rendered as an action in the header actions
2278       * menu rather than at the top of the content.
2279       *
2280       * @return bool
2281       */
2282      public function include_region_main_settings_in_header_actions() : bool {
2283          return $this->_regionmainsettingsinheader;
2284      }
2285  
2286      /**
2287       * Set the flag to indicate if the secondary navigation should be rendered.
2288       *
2289       * @param bool $hassecondarynavigation If the secondary navigation should be rendered.
2290       * @param bool $istablist When true, the navigation bar should be rendered and behave with a tablist ARIA role.
2291       *                        If false, it's rendered with a menubar ARIA role. Defaults to false.
2292       */
2293      public function set_secondary_navigation(bool $hassecondarynavigation, bool $istablist = false): void {
2294          $this->_hassecondarynavigation = $hassecondarynavigation;
2295          $this->_hastablistsecondarynavigation = $istablist;
2296      }
2297  
2298      /**
2299       * Check if the secondary navigation should be rendered.
2300       *
2301       * @return bool
2302       */
2303      public function has_secondary_navigation(): bool {
2304          return $this->_hassecondarynavigation;
2305      }
2306  
2307      /**
2308       * Check if the secondary navigation should be rendered with a tablist as opposed to a menubar.
2309       *
2310       * @return bool
2311       */
2312      public function has_tablist_secondary_navigation(): bool {
2313          return $this->_hastablistsecondarynavigation;
2314      }
2315  
2316      /**
2317       * Set the key of the secondary nav node to be activated.
2318       *
2319       * @param string $navkey the key of the secondary nav node to be activated.
2320       */
2321      public function set_secondary_active_tab(string $navkey) : void {
2322          $this->_activekeysecondary = $navkey;
2323      }
2324  
2325      /**
2326       * The key of secondary nav node to activate.
2327       *
2328       * @return string|null get the key of the secondary node to activate.
2329       */
2330      public function get_secondary_active_tab(): ?string {
2331          return $this->_activekeysecondary;
2332      }
2333  
2334      /**
2335       * Set the key of the primary nav node to be activated.
2336       *
2337       * @param string $navkey
2338       */
2339      public function set_primary_active_tab(string $navkey): void {
2340          $this->_activenodeprimary = $navkey;
2341      }
2342  
2343      /**
2344       * The key of the primary nav node to activate.
2345       *
2346       * @return string|null get the key of the primary nav node to activate.
2347       */
2348      public function get_primary_activate_tab(): ?string {
2349          return $this->_activenodeprimary;
2350      }
2351  
2352      /**
2353       * Sets the navigation overflow state. This allows developers to turn off the overflow menu if they perhaps are using
2354       * some other navigation to show settings.
2355       *
2356       * @param bool  $state  The state of whether to show the navigation overflow.
2357       */
2358      public function set_navigation_overflow_state(bool $state): void {
2359          $this->_navigationoverflow = $state;
2360      }
2361  
2362      /**
2363       * Gets the navigation overflow state.
2364       *
2365       * @return bool The navigation overflow state.
2366       */
2367      public function get_navigation_overflow_state(): bool {
2368          return $this->_navigationoverflow;
2369      }
2370  }