MDL-65799 enrol: Final deprecations
[moodle.git] / lib / pagelib.php
blob189ece5d7630575aa2ee7dd03c590ed6a79ecfce
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.
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/>.
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.
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
28 defined('MOODLE_INTERNAL') || die();
29 use core\navigation\views\primary;
30 use core\navigation\views\secondary;
31 use core\navigation\output\primary as primaryoutput;
33 /**
34 * $PAGE is a central store of information about the current page we are
35 * generating in response to the user's request.
37 * It does not do very much itself
38 * except keep track of information, however, it serves as the access point to
39 * some more significant components like $PAGE->theme, $PAGE->requires,
40 * $PAGE->blocks, etc.
42 * @copyright 2009 Tim Hunt
43 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
44 * @since Moodle 2.0
45 * @package core
46 * @category page
48 * The following properties are alphabetical. Please keep it that way so that its
49 * easy to maintain.
51 * @property-read string $activityname The type of activity we are in, for example 'forum' or 'quiz'.
52 * Will be null if this page is not within a module.
53 * @property-read stdClass $activityrecord The row from the activities own database table (for example
54 * the forum or quiz table) that this page belongs to. Will be null
55 * if this page is not within a module.
56 * @property-read array $alternativeversions Mime type => object with ->url and ->title.
57 * @property-read block_manager $blocks The blocks manager object for this page.
58 * @property-read array $blockmanipulations
59 * @property-read string $bodyclasses A string to use within the class attribute on the body tag.
60 * @property-read string $bodyid A string to use as the id of the body tag.
61 * @property-read string $button The HTML to go where the Turn editing on button normally goes.
62 * @property-read bool $cacheable Defaults to true. Set to false to stop the page being cached at all.
63 * @property-read array $categories An array of all the categories the page course belongs to,
64 * starting with the immediately containing category, and working out to
65 * the top-level category. This may be the empty array if we are in the
66 * front page course.
67 * @property-read mixed $category The category that the page course belongs to.
68 * @property-read cm_info $cm The course_module that this page belongs to. Will be null
69 * if this page is not within a module. This is a full cm object, as loaded
70 * by get_coursemodule_from_id or get_coursemodule_from_instance,
71 * so the extra modname and name fields are present.
72 * @property-read context $context The main context to which this page belongs.
73 * @property-read stdClass $course The current course that we are inside - a row from the
74 * course table. (Also available as $COURSE global.) If we are not inside
75 * an actual course, this will be the site course.
76 * @property-read string $devicetypeinuse The name of the device type in use
77 * @property-read string $docspath The path to the Help and documentation.
78 * @property-read string $focuscontrol The id of the HTML element to be focused when the page has loaded.
79 * @property-read bool $headerprinted True if the page header has already been printed.
80 * @property-read string $heading The main heading that should be displayed at the top of the <body>.
81 * @property-read string $headingmenu The menu (or actions) to display in the heading
82 * @property-read array $layout_options An arrays with options for the layout file.
83 * @property-read array $legacythemeinuse True if the legacy browser theme is in use.
84 * @property-read navbar $navbar The navbar object used to display the navbar
85 * @property-read secondary $secondarynav The secondary navigation object
86 * used to display the secondarynav in boost
87 * @property-read primary $primarynav The primary navigation object used to display the primary nav in boost
88 * @property-read primaryoutput $primarynavcombined The primary navigation object used to display the primary nav in boost
89 * @property-read global_navigation $navigation The navigation structure for this page.
90 * @property-read xhtml_container_stack $opencontainers Tracks XHTML tags on this page that have been opened but not closed.
91 * mainly for internal use by the rendering code.
92 * @property-read string $pagelayout The general type of page this is. For example 'normal', 'popup', 'home'.
93 * Allows the theme to display things differently, if it wishes to.
94 * @property-read string $pagetype The page type string, should be used as the id for the body tag in the theme.
95 * @property-read int $periodicrefreshdelay The periodic refresh delay to use with meta refresh
96 * @property-read page_requirements_manager $requires Tracks the JavaScript, CSS files, etc. required by this page.
97 * @property-read string $requestip The IP address of the current request, null if unknown.
98 * @property-read string $requestorigin The type of request 'web', 'ws', 'cli', 'restore', etc.
99 * @property-read settings_navigation $settingsnav The settings navigation
100 * @property-read int $state One of the STATE_... constants
101 * @property-read string $subpage The subpage identifier, if any.
102 * @property-read theme_config $theme The theme for this page.
103 * @property-read string $title The title that should go in the <head> section of the HTML of this page.
104 * @property-read moodle_url $url The moodle url object for this page.
106 class moodle_page {
108 /** The state of the page before it has printed the header **/
109 const STATE_BEFORE_HEADER = 0;
111 /** The state the page is in temporarily while the header is being printed **/
112 const STATE_PRINTING_HEADER = 1;
114 /** The state the page is in while content is presumably being printed **/
115 const STATE_IN_BODY = 2;
118 * The state the page is when the footer has been printed and its function is
119 * complete.
121 const STATE_DONE = 3;
124 * @var int The current state of the page. The state a page is within
125 * determines what actions are possible for it.
127 protected $_state = self::STATE_BEFORE_HEADER;
130 * @var stdClass The course currently associated with this page.
131 * If not has been provided the front page course is used.
133 protected $_course = null;
136 * @var cm_info If this page belongs to a module, this is the cm_info module
137 * description object.
139 protected $_cm = null;
142 * @var stdClass If $_cm is not null, then this will hold the corresponding
143 * row from the modname table. For example, if $_cm->modname is 'quiz', this
144 * will be a row from the quiz table.
146 protected $_module = null;
149 * @var context The context that this page belongs to.
151 protected $_context = null;
154 * @var array This holds any categories that $_course belongs to, starting with the
155 * particular category it belongs to, and working out through any parent
156 * categories to the top level. These are loaded progressively, if needed.
157 * There are three states. $_categories = null initially when nothing is
158 * loaded; $_categories = array($id => $cat, $parentid => null) when we have
159 * loaded $_course->category, but not any parents; and a complete array once
160 * everything is loaded.
162 protected $_categories = null;
165 * @var array An array of CSS classes that should be added to the body tag in HTML.
167 protected $_bodyclasses = array();
170 * @var string The title for the page. Used within the title tag in the HTML head.
172 protected $_title = '';
175 * @var string The string to use as the heading of the page. Shown near the top of the
176 * page within most themes.
178 protected $_heading = '';
181 * @var string The pagetype is used to describe the page and defaults to a representation
182 * of the physical path to the page e.g. my-index, mod-quiz-attempt
184 protected $_pagetype = null;
187 * @var string The pagelayout to use when displaying this page. The
188 * pagelayout needs to have been defined by the theme in use, or one of its
189 * parents. By default base is used however standard is the more common layout.
190 * Note that this gets automatically set by core during operations like
191 * require_login.
193 protected $_pagelayout = 'base';
196 * @var array List of theme layout options, these are ignored by core.
197 * To be used in individual theme layout files only.
199 protected $_layout_options = null;
202 * @var string An optional arbitrary parameter that can be set on pages where the context
203 * and pagetype is not enough to identify the page.
205 protected $_subpage = '';
208 * @var string Set a different path to use for the 'Help and documentation' link.
209 * By default, it uses the path of the file for instance mod/quiz/attempt.
211 protected $_docspath = null;
214 * @var string A legacy class that will be added to the body tag
216 protected $_legacyclass = null;
219 * @var moodle_url The URL for this page. This is mandatory and must be set
220 * before output is started.
222 protected $_url = null;
225 * @var array An array of links to alternative versions of this page.
226 * Primarily used for RSS versions of the current page.
228 protected $_alternateversions = array();
231 * @var block_manager The blocks manager for this page. It is responsible for
232 * the blocks and there content on this page.
234 protected $_blocks = null;
237 * @var page_requirements_manager Page requirements manager. It is responsible
238 * for all JavaScript and CSS resources required by this page.
240 protected $_requires = null;
242 /** @var page_requirements_manager Saves the requirement manager object used before switching to to fragments one. */
243 protected $savedrequires = null;
246 * @var string The capability required by the user in order to edit blocks
247 * and block settings on this page.
249 protected $_blockseditingcap = 'moodle/site:manageblocks';
252 * @var bool An internal flag to record when block actions have been processed.
253 * Remember block actions occur on the current URL and it is important that
254 * even they are never executed more than once.
256 protected $_block_actions_done = false;
259 * @var array An array of any other capabilities the current user must have
260 * in order to editing the page and/or its content (not just blocks).
262 protected $_othereditingcaps = array();
265 * @var bool Sets whether this page should be cached by the browser or not.
266 * If it is set to true (default) the page is served with caching headers.
268 protected $_cacheable = true;
271 * @var string Can be set to the ID of an element on the page, if done that
272 * element receives focus when the page loads.
274 protected $_focuscontrol = '';
277 * @var string HTML to go where the turn on editing button is located. This
278 * is nearly a legacy item and not used very often any more.
280 protected $_button = '';
283 * @var theme_config The theme to use with this page. This has to be properly
284 * initialised via {@link moodle_page::initialise_theme_and_output()} which
285 * happens magically before any operation that requires it.
287 protected $_theme = null;
290 * @var global_navigation Contains the global navigation structure.
292 protected $_navigation = null;
295 * @var settings_navigation Contains the settings navigation structure.
297 protected $_settingsnav = null;
300 * @var flat_navigation Contains a list of nav nodes, most closely related to the current page.
302 protected $_flatnav = null;
305 * @var secondary Contains the nav nodes that will appear
306 * in the secondary navigation.
308 protected $_secondarynav = null;
311 * @var primary Contains the nav nodes that will appear
312 * in the primary navigation.
314 protected $_primarynav = null;
317 * @var primaryoutput Contains the combined nav nodes that will appear
318 * in the primary navigation. Includes - primarynav, langmenu, usermenu
320 protected $_primarynavcombined = null;
323 * @var navbar Contains the navbar structure.
325 protected $_navbar = null;
328 * @var string The menu (or actions) to display in the heading.
330 protected $_headingmenu = null;
333 * @var array stack trace. Then the theme is initialised, we save the stack
334 * trace, for use in error messages.
336 protected $_wherethemewasinitialised = null;
339 * @var xhtml_container_stack Tracks XHTML tags on this page that have been
340 * opened but not closed.
342 protected $_opencontainers;
345 * @var int Sets the page to refresh after a given delay (in seconds) using
346 * meta refresh in {@link standard_head_html()} in outputlib.php
347 * If set to null(default) the page is not refreshed
349 protected $_periodicrefreshdelay = null;
352 * @var array Associative array of browser shortnames (as used by check_browser_version)
353 * and their minimum required versions
355 protected $_legacybrowsers = array('MSIE' => 6.0);
358 * @var string Is set to the name of the device type in use.
359 * This will we worked out when it is first used.
361 protected $_devicetypeinuse = null;
364 * @var bool Used to determine if HTTPS should be required for login.
366 protected $_https_login_required = false;
369 * @var bool Determines if popup notifications allowed on this page.
370 * Code such as the quiz module disables popup notifications in situations
371 * such as upgrading or completing a quiz.
373 protected $_popup_notification_allowed = true;
376 * @var bool Is the settings menu being forced to display on this page (activities / resources only).
377 * This is only used by themes that use the settings menu.
379 protected $_forcesettingsmenu = false;
382 * @var array Array of header actions HTML to add to the page header actions menu.
384 protected $_headeractions = [];
387 * @var bool Should the region main settings menu be rendered in the header.
389 protected $_regionmainsettingsinheader = false;
392 * @var bool Should the secondary menu be rendered.
394 protected $_hassecondarynavigation = true;
397 * @var string the key of the secondary node to be activated.
399 protected $_activekeysecondary = null;
402 * @var string the key of the primary node to be activated.
404 protected $_activenodeprimary = null;
407 * Force the settings menu to be displayed on this page. This will only force the
408 * settings menu on an activity / resource page that is being displayed on a theme that
409 * uses a settings menu.
411 * @param bool $forced default of true, can be sent false to turn off the force.
413 public function force_settings_menu($forced = true) {
414 $this->_forcesettingsmenu = $forced;
418 * Check to see if the settings menu is forced to display on this activity / resource page.
419 * This only applies to themes that use the settings menu.
421 * @return bool True if the settings menu is forced to display.
423 public function is_settings_menu_forced() {
424 return $this->_forcesettingsmenu;
427 // Magic getter methods =============================================================
428 // Due to the __get magic below, you normally do not call these as $PAGE->magic_get_x
429 // methods, but instead use the $PAGE->x syntax.
432 * Please do not call this method directly, use the ->state syntax. {@link moodle_page::__get()}.
433 * @return integer one of the STATE_XXX constants. You should not normally need
434 * to use this in your code. It is intended for internal use by this class
435 * and its friends like print_header, to check that everything is working as
436 * expected. Also accessible as $PAGE->state.
438 protected function magic_get_state() {
439 return $this->_state;
443 * Please do not call this method directly, use the ->headerprinted syntax. {@link moodle_page::__get()}.
444 * @return bool has the header already been printed?
446 protected function magic_get_headerprinted() {
447 return $this->_state >= self::STATE_IN_BODY;
451 * Please do not call this method directly, use the ->course syntax. {@link moodle_page::__get()}.
452 * @return stdClass the current course that we are inside - a row from the
453 * course table. (Also available as $COURSE global.) If we are not inside
454 * an actual course, this will be the site course.
456 protected function magic_get_course() {
457 global $SITE;
458 if (is_null($this->_course)) {
459 return $SITE;
461 return $this->_course;
465 * Please do not call this method directly, use the ->cm syntax. {@link moodle_page::__get()}.
466 * @return cm_info the course_module that this page belongs to. Will be null
467 * if this page is not within a module. This is a full cm object, as loaded
468 * by get_coursemodule_from_id or get_coursemodule_from_instance,
469 * so the extra modname and name fields are present.
471 protected function magic_get_cm() {
472 return $this->_cm;
476 * Please do not call this method directly, use the ->activityrecord syntax. {@link moodle_page::__get()}.
477 * @return stdClass the row from the activities own database table (for example
478 * the forum or quiz table) that this page belongs to. Will be null
479 * if this page is not within a module.
481 protected function magic_get_activityrecord() {
482 if (is_null($this->_module) && !is_null($this->_cm)) {
483 $this->load_activity_record();
485 return $this->_module;
489 * Please do not call this method directly, use the ->activityname syntax. {@link moodle_page::__get()}.
490 * @return string the The type of activity we are in, for example 'forum' or 'quiz'.
491 * Will be null if this page is not within a module.
493 protected function magic_get_activityname() {
494 if (is_null($this->_cm)) {
495 return null;
497 return $this->_cm->modname;
501 * Please do not call this method directly, use the ->category syntax. {@link moodle_page::__get()}.
502 * @return stdClass the category that the page course belongs to. If there isn't one
503 * (that is, if this is the front page course) returns null.
505 protected function magic_get_category() {
506 $this->ensure_category_loaded();
507 if (!empty($this->_categories)) {
508 return reset($this->_categories);
509 } else {
510 return null;
515 * Please do not call this method directly, use the ->categories syntax. {@link moodle_page::__get()}.
516 * @return array an array of all the categories the page course belongs to,
517 * starting with the immediately containing category, and working out to
518 * the top-level category. This may be the empty array if we are in the
519 * front page course.
521 protected function magic_get_categories() {
522 $this->ensure_categories_loaded();
523 return $this->_categories;
527 * Please do not call this method directly, use the ->context syntax. {@link moodle_page::__get()}.
528 * @return context the main context to which this page belongs.
530 protected function magic_get_context() {
531 global $CFG;
532 if (is_null($this->_context)) {
533 if (CLI_SCRIPT or NO_MOODLE_COOKIES) {
534 // Cli scripts work in system context, do not annoy devs with debug info.
535 // Very few scripts do not use cookies, we can safely use system as default context there.
536 } else if (AJAX_SCRIPT && $CFG->debugdeveloper) {
537 // Throw exception inside AJAX script in developer mode, otherwise the debugging message may be missed.
538 throw new coding_exception('$PAGE->context was not set. You may have forgotten '
539 .'to call require_login() or $PAGE->set_context()');
540 } else {
541 debugging('Coding problem: $PAGE->context was not set. You may have forgotten '
542 .'to call require_login() or $PAGE->set_context(). The page may not display '
543 .'correctly as a result');
545 $this->_context = context_system::instance();
547 return $this->_context;
551 * Please do not call this method directly, use the ->pagetype syntax. {@link moodle_page::__get()}.
552 * @return string e.g. 'my-index' or 'mod-quiz-attempt'.
554 protected function magic_get_pagetype() {
555 global $CFG;
556 if (is_null($this->_pagetype) || isset($CFG->pagepath)) {
557 $this->initialise_default_pagetype();
559 return $this->_pagetype;
563 * Please do not call this method directly, use the ->pagetype syntax. {@link moodle_page::__get()}.
564 * @return string The id to use on the body tag, uses {@link magic_get_pagetype()}.
566 protected function magic_get_bodyid() {
567 return 'page-'.$this->pagetype;
571 * Please do not call this method directly, use the ->pagelayout syntax. {@link moodle_page::__get()}.
572 * @return string the general type of page this is. For example 'standard', 'popup', 'home'.
573 * Allows the theme to display things differently, if it wishes to.
575 protected function magic_get_pagelayout() {
576 return $this->_pagelayout;
580 * Please do not call this method directly, use the ->layout_options syntax. {@link moodle_page::__get()}.
581 * @return array returns arrays with options for layout file
583 protected function magic_get_layout_options() {
584 if (!is_array($this->_layout_options)) {
585 $this->_layout_options = $this->_theme->pagelayout_options($this->pagelayout);
587 return $this->_layout_options;
591 * Please do not call this method directly, use the ->subpage syntax. {@link moodle_page::__get()}.
592 * @return string The subpage identifier, if any.
594 protected function magic_get_subpage() {
595 return $this->_subpage;
599 * Please do not call this method directly, use the ->bodyclasses syntax. {@link moodle_page::__get()}.
600 * @return string the class names to put on the body element in the HTML.
602 protected function magic_get_bodyclasses() {
603 return implode(' ', array_keys($this->_bodyclasses));
607 * Please do not call this method directly, use the ->title syntax. {@link moodle_page::__get()}.
608 * @return string the title that should go in the <head> section of the HTML of this page.
610 protected function magic_get_title() {
611 return $this->_title;
615 * Please do not call this method directly, use the ->heading syntax. {@link moodle_page::__get()}.
616 * @return string the main heading that should be displayed at the top of the <body>.
618 protected function magic_get_heading() {
619 return $this->_heading;
623 * Please do not call this method directly, use the ->heading syntax. {@link moodle_page::__get()}.
624 * @return string The menu (or actions) to display in the heading
626 protected function magic_get_headingmenu() {
627 return $this->_headingmenu;
631 * Please do not call this method directly, use the ->docspath syntax. {@link moodle_page::__get()}.
632 * @return string the path to the Help and documentation.
634 protected function magic_get_docspath() {
635 if (is_string($this->_docspath)) {
636 return $this->_docspath;
637 } else {
638 return str_replace('-', '/', $this->pagetype);
643 * Please do not call this method directly, use the ->url syntax. {@link moodle_page::__get()}.
644 * @return moodle_url the clean URL required to load the current page. (You
645 * should normally use this in preference to $ME or $FULLME.)
647 protected function magic_get_url() {
648 global $FULLME;
649 if (is_null($this->_url)) {
650 debugging('This page did not call $PAGE->set_url(...). Using '.s($FULLME), DEBUG_DEVELOPER);
651 $this->_url = new moodle_url($FULLME);
652 // Make sure the guessed URL cannot lead to dangerous redirects.
653 $this->_url->remove_params('sesskey');
655 return new moodle_url($this->_url); // Return a clone for safety.
659 * The list of alternate versions of this page.
660 * @return array mime type => object with ->url and ->title.
662 protected function magic_get_alternateversions() {
663 return $this->_alternateversions;
667 * Please do not call this method directly, use the ->blocks syntax. {@link moodle_page::__get()}.
668 * @return block_manager the blocks manager object for this page.
670 protected function magic_get_blocks() {
671 global $CFG;
672 if (is_null($this->_blocks)) {
673 if (!empty($CFG->blockmanagerclass)) {
674 if (!empty($CFG->blockmanagerclassfile)) {
675 require_once($CFG->blockmanagerclassfile);
677 $classname = $CFG->blockmanagerclass;
678 } else {
679 $classname = 'block_manager';
681 $this->_blocks = new $classname($this);
683 return $this->_blocks;
687 * Please do not call this method directly, use the ->requires syntax. {@link moodle_page::__get()}.
688 * @return page_requirements_manager tracks the JavaScript, CSS files, etc. required by this page.
690 protected function magic_get_requires() {
691 if (is_null($this->_requires)) {
692 $this->_requires = new page_requirements_manager();
694 return $this->_requires;
698 * Please do not call this method directly, use the ->cacheable syntax. {@link moodle_page::__get()}.
699 * @return bool can this page be cached by the user's browser.
701 protected function magic_get_cacheable() {
702 return $this->_cacheable;
706 * Please do not call this method directly, use the ->focuscontrol syntax. {@link moodle_page::__get()}.
707 * @return string the id of the HTML element to be focused when the page has loaded.
709 protected function magic_get_focuscontrol() {
710 return $this->_focuscontrol;
714 * Please do not call this method directly, use the ->button syntax. {@link moodle_page::__get()}.
715 * @return string the HTML to go where the Turn editing on button normally goes.
717 protected function magic_get_button() {
718 return $this->_button;
722 * Please do not call this method directly, use the ->theme syntax. {@link moodle_page::__get()}.
723 * @return theme_config the initialised theme for this page.
725 protected function magic_get_theme() {
726 if (is_null($this->_theme)) {
727 $this->initialise_theme_and_output();
729 return $this->_theme;
733 * Returns an array of minipulations or false if there are none to make.
735 * @since Moodle 2.5.1 2.6
736 * @return bool|array
738 protected function magic_get_blockmanipulations() {
739 if (!right_to_left()) {
740 return false;
742 if (is_null($this->_theme)) {
743 $this->initialise_theme_and_output();
745 return $this->_theme->blockrtlmanipulations;
749 * Please do not call this method directly, use the ->devicetypeinuse syntax. {@link moodle_page::__get()}.
750 * @return string The device type being used.
752 protected function magic_get_devicetypeinuse() {
753 if (empty($this->_devicetypeinuse)) {
754 $this->_devicetypeinuse = core_useragent::get_user_device_type();
756 return $this->_devicetypeinuse;
760 * Please do not call this method directly use the ->periodicrefreshdelay syntax
761 * {@link moodle_page::__get()}
762 * @return int The periodic refresh delay to use with meta refresh
764 protected function magic_get_periodicrefreshdelay() {
765 return $this->_periodicrefreshdelay;
769 * Please do not call this method directly use the ->opencontainers syntax. {@link moodle_page::__get()}
770 * @return xhtml_container_stack tracks XHTML tags on this page that have been opened but not closed.
771 * mainly for internal use by the rendering code.
773 protected function magic_get_opencontainers() {
774 if (is_null($this->_opencontainers)) {
775 $this->_opencontainers = new xhtml_container_stack();
777 return $this->_opencontainers;
781 * Return the navigation object
782 * @return global_navigation
784 protected function magic_get_navigation() {
785 if ($this->_navigation === null) {
786 $this->_navigation = new global_navigation($this);
788 return $this->_navigation;
792 * Return a navbar object
793 * @return navbar
795 protected function magic_get_navbar() {
796 if ($this->_navbar === null) {
797 $this->_navbar = new navbar($this);
799 return $this->_navbar;
803 * Returns the settings navigation object
804 * @return settings_navigation
806 protected function magic_get_settingsnav() {
807 if ($this->_settingsnav === null) {
808 $this->_settingsnav = new settings_navigation($this);
809 $this->_settingsnav->initialise();
811 return $this->_settingsnav;
815 * Returns the flat navigation object
816 * @return flat_navigation
818 protected function magic_get_flatnav() {
819 if ($this->_flatnav === null) {
820 $this->_flatnav = new flat_navigation($this);
821 $this->_flatnav->initialise();
823 return $this->_flatnav;
827 * Returns the secondary navigation object
828 * @return secondary
830 protected function magic_get_secondarynav() {
831 if ($this->_secondarynav === null) {
832 $class = 'core\navigation\views\secondary';
833 // Try and load a custom class first.
834 if (class_exists("mod_{$this->activityname}\\local\\views\\secondary")) {
835 $class = "mod_{$this->activityname}\\local\\views\\secondary";
838 $this->_secondarynav = new $class($this);
839 $this->_secondarynav->initialise();
841 return $this->_secondarynav;
845 * Returns the primary navigation object
846 * @return primary
848 protected function magic_get_primarynav() {
849 if ($this->_primarynav === null) {
850 $this->_primarynav = new primary($this);
851 $this->_primarynav->initialise();
853 return $this->_primarynav;
857 * Returns the primary navigation object
858 * @return primary
860 protected function magic_get_primarynavcombined() {
861 if ($this->_primarynavcombined === null) {
862 $this->_primarynavcombined = new primaryoutput($this);
864 return $this->_primarynavcombined;
868 * Returns request IP address.
870 * @return string IP address or null if unknown
872 protected function magic_get_requestip() {
873 return getremoteaddr(null);
877 * Returns the origin of current request.
879 * Note: constants are not required because we need to use these values in logging and reports.
881 * @return string 'web', 'ws', 'cli', 'restore', etc.
883 protected function magic_get_requestorigin() {
884 if (class_exists('restore_controller', false) && restore_controller::is_executing()) {
885 return 'restore';
888 if (WS_SERVER) {
889 return 'ws';
892 if (CLI_SCRIPT) {
893 return 'cli';
896 return 'web';
900 * PHP overloading magic to make the $PAGE->course syntax work by redirecting
901 * it to the corresponding $PAGE->magic_get_course() method if there is one, and
902 * throwing an exception if not.
904 * @param string $name property name
905 * @return mixed
906 * @throws coding_exception
908 public function __get($name) {
909 $getmethod = 'magic_get_' . $name;
910 if (method_exists($this, $getmethod)) {
911 return $this->$getmethod();
912 } else {
913 throw new coding_exception('Unknown property ' . $name . ' of $PAGE.');
918 * PHP overloading magic to catch obvious coding errors.
920 * This method has been created to catch obvious coding errors where the
921 * developer has tried to set a page property using $PAGE->key = $value.
922 * In the moodle_page class all properties must be set using the appropriate
923 * $PAGE->set_something($value) method.
925 * @param string $name property name
926 * @param mixed $value Value
927 * @return void Throws exception if field not defined in page class
928 * @throws coding_exception
930 public function __set($name, $value) {
931 if (method_exists($this, 'set_' . $name)) {
932 throw new coding_exception('Invalid attempt to modify page object', "Use \$PAGE->set_$name() instead.");
933 } else {
934 throw new coding_exception('Invalid attempt to modify page object', "Unknown property $name");
938 // Other information getting methods ==========================================.
941 * Returns instance of page renderer
943 * @param string $component name such as 'core', 'mod_forum' or 'qtype_multichoice'.
944 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
945 * @param string $target one of rendering target constants
946 * @return renderer_base
948 public function get_renderer($component, $subtype = null, $target = null) {
949 if ($this->pagelayout === 'maintenance') {
950 // If the page is using the maintenance layout then we're going to force target to maintenance.
951 // This leads to a special core renderer that is designed to block access to API's that are likely unavailable for this
952 // page layout.
953 $target = RENDERER_TARGET_MAINTENANCE;
955 return $this->magic_get_theme()->get_renderer($this, $component, $subtype, $target);
959 * Checks to see if there are any items on the navbar object
961 * @return bool true if there are, false if not
963 public function has_navbar() {
964 if ($this->_navbar === null) {
965 $this->_navbar = new navbar($this);
967 return $this->_navbar->has_items();
971 * Switches from the regular requirements manager to the fragment requirements manager to
972 * capture all necessary JavaScript to display a chunk of HTML such as an mform. This is for use
973 * by the get_fragment() web service and not for use elsewhere.
975 public function start_collecting_javascript_requirements() {
976 global $CFG;
977 require_once($CFG->libdir.'/outputfragmentrequirementslib.php');
979 // Check that the requirements manager has not already been switched.
980 if (get_class($this->_requires) == 'fragment_requirements_manager') {
981 throw new coding_exception('JavaScript collection has already been started.');
983 // The header needs to have been called to flush out the generic JavaScript for the page. This allows only
984 // JavaScript for the fragment to be collected. _wherethemewasinitialised is set when header() is called.
985 if (!empty($this->_wherethemewasinitialised)) {
986 // Change the current requirements manager over to the fragment manager to capture JS.
987 $this->savedrequires = $this->_requires;
988 $this->_requires = new fragment_requirements_manager();
989 } else {
990 throw new coding_exception('$OUTPUT->header() needs to be called before collecting JavaScript requirements.');
995 * Switches back from collecting fragment JS requirement to the original requirement manager
997 public function end_collecting_javascript_requirements() {
998 if ($this->savedrequires === null) {
999 throw new coding_exception('JavaScript collection has not been started.');
1001 $this->_requires = $this->savedrequires;
1002 $this->savedrequires = null;
1006 * Should the current user see this page in editing mode.
1007 * That is, are they allowed to edit this page, and are they currently in
1008 * editing mode.
1009 * @return bool
1011 public function user_is_editing() {
1012 global $USER;
1013 return !empty($USER->editing) && $this->user_allowed_editing();
1017 * Does the user have permission to edit blocks on this page.
1018 * @return bool
1020 public function user_can_edit_blocks() {
1021 return has_capability($this->_blockseditingcap, $this->_context);
1025 * Does the user have permission to see this page in editing mode.
1026 * @return bool
1028 public function user_allowed_editing() {
1029 return has_any_capability($this->all_editing_caps(), $this->_context);
1033 * Get a description of this page. Normally displayed in the footer in developer debug mode.
1034 * @return string
1036 public function debug_summary() {
1037 $summary = '';
1038 $summary .= 'General type: ' . $this->pagelayout . '. ';
1039 if (!during_initial_install()) {
1040 $summary .= 'Context ' . $this->context->get_context_name() . ' (context id ' . $this->_context->id . '). ';
1042 $summary .= 'Page type ' . $this->pagetype . '. ';
1043 if ($this->subpage) {
1044 $summary .= 'Sub-page ' . $this->subpage . '. ';
1046 return $summary;
1049 // Setter methods =============================================================.
1052 * Set the state.
1054 * The state must be one of that STATE_... constants, and the state is only allowed to advance one step at a time.
1056 * @param int $state The new state.
1057 * @throws coding_exception
1059 public function set_state($state) {
1060 if ($state != $this->_state + 1 || $state > self::STATE_DONE) {
1061 throw new coding_exception('Invalid state passed to moodle_page::set_state. We are in state ' .
1062 $this->_state . ' and state ' . $state . ' was requested.');
1065 if ($state == self::STATE_PRINTING_HEADER) {
1066 $this->starting_output();
1069 $this->_state = $state;
1073 * Set the current course. This sets both $PAGE->course and $COURSE. It also
1074 * sets the right theme and locale.
1076 * Normally you don't need to call this function yourself, require_login will
1077 * call it for you if you pass a $course to it. You can use this function
1078 * on pages that do need to call require_login().
1080 * Sets $PAGE->context to the course context, if it is not already set.
1082 * @param stdClass $course the course to set as the global course.
1083 * @throws coding_exception
1085 public function set_course($course) {
1086 global $COURSE, $PAGE, $CFG, $SITE;
1088 if (empty($course->id)) {
1089 throw new coding_exception('$course passed to moodle_page::set_course does not look like a proper course object.');
1092 $this->ensure_theme_not_set();
1094 if (!empty($this->_course->id) && $this->_course->id != $course->id) {
1095 $this->_categories = null;
1098 $this->_course = clone($course);
1100 if ($this === $PAGE) {
1101 $COURSE = $this->_course;
1102 moodle_setlocale();
1105 if (!$this->_context) {
1106 $this->set_context(context_course::instance($this->_course->id));
1109 // Notify course format that this page is set for the course.
1110 if ($this->_course->id != $SITE->id) {
1111 require_once($CFG->dirroot.'/course/lib.php');
1112 $courseformat = course_get_format($this->_course);
1113 $this->add_body_class('format-'. $courseformat->get_format());
1114 $courseformat->page_set_course($this);
1115 } else {
1116 $this->add_body_class('format-site');
1121 * Set the main context to which this page belongs.
1123 * @param context $context a context object. You normally get this with context_xxxx::instance().
1125 public function set_context($context) {
1126 if ($context === null) {
1127 // Extremely ugly hack which sets context to some value in order to prevent warnings,
1128 // use only for core error handling!!!!
1129 if (!$this->_context) {
1130 $this->_context = context_system::instance();
1132 return;
1134 // Ideally we should set context only once.
1135 if (isset($this->_context) && $context->id !== $this->_context->id) {
1136 $current = $this->_context->contextlevel;
1137 if ($current == CONTEXT_SYSTEM or $current == CONTEXT_COURSE) {
1138 // Hmm - not ideal, but it might produce too many warnings due to the design of require_login.
1139 } else if ($current == CONTEXT_MODULE and ($parentcontext = $context->get_parent_context()) and
1140 $this->_context->id == $parentcontext->id) {
1141 // Hmm - most probably somebody did require_login() and after that set the block context.
1142 } else {
1143 // We do not want devs to do weird switching of context levels on the fly because we might have used
1144 // the context already such as in text filter in page title.
1145 debugging("Coding problem: unsupported modification of PAGE->context from {$current} to {$context->contextlevel}");
1149 $this->_context = $context;
1153 * The course module that this page belongs to (if it does belong to one).
1155 * @param stdClass|cm_info $cm a record from course_modules table or cm_info from get_fast_modinfo().
1156 * @param stdClass $course
1157 * @param stdClass $module
1158 * @return void
1159 * @throws coding_exception
1161 public function set_cm($cm, $course = null, $module = null) {
1162 global $DB, $CFG, $SITE;
1164 if (!isset($cm->id) || !isset($cm->course)) {
1165 throw new coding_exception('Invalid $cm. It has to be instance of cm_info or record from the course_modules table.');
1168 if (!$this->_course || $this->_course->id != $cm->course) {
1169 if (!$course) {
1170 $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
1172 if ($course->id != $cm->course) {
1173 throw new coding_exception('The course you passed to $PAGE->set_cm does not correspond to the $cm.');
1175 $this->set_course($course);
1178 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
1179 if (!($cm instanceof cm_info)) {
1180 $modinfo = get_fast_modinfo($this->_course);
1181 $cm = $modinfo->get_cm($cm->id);
1183 $this->_cm = $cm;
1185 // Unfortunately the context setting is a mess.
1186 // Let's try to work around some common block problems and show some debug messages.
1187 if (empty($this->_context) or $this->_context->contextlevel != CONTEXT_BLOCK) {
1188 $context = context_module::instance($cm->id);
1189 $this->set_context($context);
1192 if ($module) {
1193 $this->set_activity_record($module);
1196 // Notify course format that this page is set for the course module.
1197 if ($this->_course->id != $SITE->id) {
1198 require_once($CFG->dirroot.'/course/lib.php');
1199 course_get_format($this->_course)->page_set_cm($this);
1204 * Sets the activity record. This could be a row from the main table for a
1205 * module. For instance if the current module (cm) is a forum this should be a row
1206 * from the forum table.
1208 * @param stdClass $module A row from the main database table for the module that this page belongs to.
1209 * @throws coding_exception
1211 public function set_activity_record($module) {
1212 if (is_null($this->_cm)) {
1213 throw new coding_exception('You cannot call $PAGE->set_activity_record until after $PAGE->cm has been set.');
1215 if ($module->id != $this->_cm->instance || $module->course != $this->_course->id) {
1216 throw new coding_exception('The activity record does not seem to correspond to the cm that has been set.');
1218 $this->_module = $module;
1222 * Sets the pagetype to use for this page.
1224 * Normally you do not need to set this manually, it is automatically created
1225 * from the script name. However, on some pages this is overridden.
1226 * For example the page type for course/view.php includes the course format,
1227 * for example 'course-view-weeks'. This gets used as the id attribute on
1228 * <body> and also for determining which blocks are displayed.
1230 * @param string $pagetype e.g. 'my-index' or 'mod-quiz-attempt'.
1232 public function set_pagetype($pagetype) {
1233 $this->_pagetype = $pagetype;
1237 * Sets the layout to use for this page.
1239 * The page layout determines how the page will be displayed, things such as
1240 * block regions, content areas, etc are controlled by the layout.
1241 * The theme in use for the page will determine that the layout contains.
1243 * This properly defaults to 'base', so you only need to call this function if
1244 * you want something different. The exact range of supported layouts is specified
1245 * in the standard theme.
1247 * For an idea of the common page layouts see
1248 * {@link http://docs.moodle.org/dev/Themes_2.0#The_different_layouts_as_of_August_17th.2C_2010}
1249 * But please keep in mind that it may be (and normally is) out of date.
1250 * The only place to find an accurate up-to-date list of the page layouts
1251 * available for your version of Moodle is {@link theme/base/config.php}
1253 * @param string $pagelayout the page layout this is. For example 'popup', 'home'.
1255 public function set_pagelayout($pagelayout) {
1256 global $SESSION;
1258 if (!empty($SESSION->forcepagelayout)) {
1259 $this->_pagelayout = $SESSION->forcepagelayout;
1260 } else {
1261 // Uncomment this to debug theme pagelayout issues like missing blocks.
1262 // if (!empty($this->_wherethemewasinitialised) && $pagelayout != $this->_pagelayout)
1263 // debugging('Page layout has already been set and cannot be changed.', DEBUG_DEVELOPER);
1264 $this->_pagelayout = $pagelayout;
1269 * If context->id and pagetype are not enough to uniquely identify this page,
1270 * then you can set a subpage id as well. For example, the tags page sets
1272 * @param string $subpage an arbitrary identifier that, along with context->id
1273 * and pagetype, uniquely identifies this page.
1275 public function set_subpage($subpage) {
1276 if (empty($subpage)) {
1277 $this->_subpage = '';
1278 } else {
1279 $this->_subpage = $subpage;
1284 * Force set secondary_nav. Useful in cases where we dealing with non course modules. e.g. blocks, tools.
1285 * @param secondary $nav
1287 public function set_secondarynav(secondary $nav) {
1288 $this->_secondarynav = $nav;
1292 * Adds a CSS class to the body tag of the page.
1294 * @param string $class add this class name ot the class attribute on the body tag.
1295 * @throws coding_exception
1297 public function add_body_class($class) {
1298 if ($this->_state > self::STATE_BEFORE_HEADER) {
1299 throw new coding_exception('Cannot call moodle_page::add_body_class after output has been started.');
1301 $this->_bodyclasses[$class] = 1;
1305 * Adds an array of body classes to the body tag of this page.
1307 * @param array $classes this utility method calls add_body_class for each array element.
1309 public function add_body_classes($classes) {
1310 foreach ($classes as $class) {
1311 $this->add_body_class($class);
1316 * Sets the title for the page.
1317 * This is normally used within the title tag in the head of the page.
1319 * @param string $title the title that should go in the <head> section of the HTML of this page.
1321 public function set_title($title) {
1322 $title = format_string($title);
1323 $title = strip_tags($title);
1324 $title = str_replace('"', '&quot;', $title);
1325 $this->_title = $title;
1329 * Sets the heading to use for the page.
1330 * This is normally used as the main heading at the top of the content.
1332 * @param string $heading the main heading that should be displayed at the top of the <body>.
1333 * @param bool $applyformatting apply format_string() - by default true.
1335 public function set_heading($heading, bool $applyformatting = true) {
1336 $this->_heading = $applyformatting ? format_string($heading) : clean_text($heading);
1340 * Sets some HTML to use next to the heading {@link moodle_page::set_heading()}
1342 * @param string $menu The menu/content to show in the heading
1344 public function set_headingmenu($menu) {
1345 $this->_headingmenu = $menu;
1349 * Set the course category this page belongs to manually.
1351 * This automatically sets $PAGE->course to be the site course. You cannot
1352 * use this method if you have already set $PAGE->course - in that case,
1353 * the category must be the one that the course belongs to. This also
1354 * automatically sets the page context to the category context.
1356 * @param int $categoryid The id of the category to set.
1357 * @throws coding_exception
1359 public function set_category_by_id($categoryid) {
1360 global $SITE;
1361 if (!is_null($this->_course)) {
1362 throw new coding_exception('Course has already been set. You cannot change the category now.');
1364 if (is_array($this->_categories)) {
1365 throw new coding_exception('Course category has already been set. You cannot to change it now.');
1367 $this->ensure_theme_not_set();
1368 $this->set_course($SITE);
1369 $this->load_category($categoryid);
1370 $this->set_context(context_coursecat::instance($categoryid));
1374 * Set a different path to use for the 'Help and documentation' link.
1376 * By default, it uses the pagetype, which is normally the same as the
1377 * script name. So, for example, for mod/quiz/attempt.php, pagetype is
1378 * mod-quiz-attempt, and so docspath is mod/quiz/attempt.
1380 * @param string $path the path to use at the end of the moodle docs URL.
1382 public function set_docs_path($path) {
1383 $this->_docspath = $path;
1387 * You should call this method from every page to set the URL that should be used to return to this page.
1389 * Used, for example, by the blocks editing UI to know where to return the
1390 * user after an action.
1391 * For example, course/view.php does:
1392 * $id = optional_param('id', 0, PARAM_INT);
1393 * $PAGE->set_url('/course/view.php', array('id' => $id));
1395 * @param moodle_url|string $url URL relative to $CFG->wwwroot or {@link moodle_url} instance
1396 * @param array $params parameters to add to the URL
1397 * @throws coding_exception
1399 public function set_url($url, array $params = null) {
1400 global $CFG;
1402 if (is_string($url) && strpos($url, 'http') !== 0) {
1403 if (strpos($url, '/') === 0) {
1404 // Add the wwwroot to the relative url.
1405 $url = $CFG->wwwroot . $url;
1406 } else {
1407 throw new coding_exception('Invalid parameter $url, has to be full url or in shortened form starting with /.');
1411 $this->_url = new moodle_url($url, $params);
1413 $fullurl = $this->_url->out_omit_querystring();
1414 if (strpos($fullurl, "$CFG->wwwroot/") !== 0) {
1415 debugging('Most probably incorrect set_page() url argument, it does not match the wwwroot!');
1417 $shorturl = str_replace("$CFG->wwwroot/", '', $fullurl);
1419 if (is_null($this->_pagetype)) {
1420 $this->initialise_default_pagetype($shorturl);
1425 * Make sure page URL does not contain the given URL parameter.
1427 * This should not be necessary if the script has called set_url properly.
1428 * However, in some situations like the block editing actions; when the URL
1429 * has been guessed, it will contain dangerous block-related actions.
1430 * Therefore, the blocks code calls this function to clean up such parameters
1431 * before doing any redirect.
1433 * @param string $param the name of the parameter to make sure is not in the
1434 * page URL.
1436 public function ensure_param_not_in_url($param) {
1437 $this->_url->remove_params($param);
1441 * Sets an alternative version of this page.
1443 * There can be alternate versions of some pages (for example an RSS feed version).
1444 * Call this method for each alternative version available.
1445 * For each alternative version a link will be included in the <head> tag.
1447 * @param string $title The title to give the alternate version.
1448 * @param string|moodle_url $url The URL of the alternate version.
1449 * @param string $mimetype The mime-type of the alternate version.
1450 * @throws coding_exception
1452 public function add_alternate_version($title, $url, $mimetype) {
1453 if ($this->_state > self::STATE_BEFORE_HEADER) {
1454 throw new coding_exception('Cannot call moodle_page::add_alternate_version after output has been started.');
1456 $alt = new stdClass;
1457 $alt->title = $title;
1458 $alt->url = $url;
1459 $this->_alternateversions[$mimetype] = $alt;
1463 * Specify a form control should be focused when the page has loaded.
1465 * @param string $controlid the id of the HTML element to be focused.
1467 public function set_focuscontrol($controlid) {
1468 $this->_focuscontrol = $controlid;
1472 * Specify a fragment of HTML that goes where the 'Turn editing on' button normally goes.
1474 * @param string $html the HTML to display there.
1476 public function set_button($html) {
1477 $this->_button = $html;
1481 * Set the capability that allows users to edit blocks on this page.
1483 * Normally the default of 'moodle/site:manageblocks' is used, but a few
1484 * pages like the My Moodle page need to use a different capability
1485 * like 'moodle/my:manageblocks'.
1487 * @param string $capability a capability.
1489 public function set_blocks_editing_capability($capability) {
1490 $this->_blockseditingcap = $capability;
1494 * Some pages let you turn editing on for reasons other than editing blocks.
1495 * If that is the case, you can pass other capabilities that let the user
1496 * edit this page here.
1498 * @param string|array $capability either a capability, or an array of capabilities.
1500 public function set_other_editing_capability($capability) {
1501 if (is_array($capability)) {
1502 $this->_othereditingcaps = array_unique($this->_othereditingcaps + $capability);
1503 } else {
1504 $this->_othereditingcaps[] = $capability;
1509 * Sets whether the browser should cache this page or not.
1511 * @param bool $cacheable can this page be cached by the user's browser.
1513 public function set_cacheable($cacheable) {
1514 $this->_cacheable = $cacheable;
1518 * Sets the page to periodically refresh
1520 * This function must be called before $OUTPUT->header has been called or
1521 * a coding exception will be thrown.
1523 * @param int $delay Sets the delay before refreshing the page, if set to null refresh is cancelled.
1524 * @throws coding_exception
1526 public function set_periodic_refresh_delay($delay = null) {
1527 if ($this->_state > self::STATE_BEFORE_HEADER) {
1528 throw new coding_exception('You cannot set a periodic refresh delay after the header has been printed');
1530 if ($delay === null) {
1531 $this->_periodicrefreshdelay = null;
1532 } else if (is_int($delay)) {
1533 $this->_periodicrefreshdelay = $delay;
1538 * Force this page to use a particular theme.
1540 * Please use this cautiously.
1541 * It is only intended to be used by the themes selector admin page.
1543 * @param string $themename the name of the theme to use.
1545 public function force_theme($themename) {
1546 $this->ensure_theme_not_set();
1547 $this->_theme = theme_config::load($themename);
1551 * Reload theme settings.
1553 * This is used when we need to reset settings
1554 * because they are now double cached in theme.
1556 public function reload_theme() {
1557 if (!is_null($this->_theme)) {
1558 $this->_theme = theme_config::load($this->_theme->name);
1563 * @deprecated since Moodle 3.4
1565 public function https_required() {
1566 throw new coding_exception('https_required() cannot be used anymore.');
1570 * @deprecated since Moodle 3.4
1572 public function verify_https_required() {
1573 throw new coding_exception('verify_https_required() cannot be used anymore.');
1576 // Initialisation methods =====================================================
1577 // These set various things up in a default way.
1580 * This method is called when the page first moves out of the STATE_BEFORE_HEADER
1581 * state. This is our last change to initialise things.
1583 protected function starting_output() {
1584 global $CFG;
1586 if (!during_initial_install()) {
1587 $this->blocks->load_blocks();
1588 if (empty($this->_block_actions_done)) {
1589 $this->_block_actions_done = true;
1590 if ($this->blocks->process_url_actions($this)) {
1591 redirect($this->url->out(false));
1594 $this->blocks->create_all_block_instances();
1597 // If maintenance mode is on, change the page header.
1598 if (!empty($CFG->maintenance_enabled)) {
1599 $this->set_button('<a href="' . $CFG->wwwroot . '/' . $CFG->admin .
1600 '/settings.php?section=maintenancemode">' . get_string('maintenancemode', 'admin') .
1601 '</a> ' . $this->button);
1603 $title = $this->title;
1604 if ($title) {
1605 $title .= ' - ';
1607 $this->set_title($title . get_string('maintenancemode', 'admin'));
1610 $this->initialise_standard_body_classes();
1614 * Method for use by Moodle core to set up the theme. Do not
1615 * use this in your own code.
1617 * Make sure the right theme for this page is loaded. Tell our
1618 * blocks_manager about the theme block regions, and then, if
1619 * we are $PAGE, set up the global $OUTPUT.
1621 * @return void
1623 public function initialise_theme_and_output() {
1624 global $OUTPUT, $PAGE, $SITE, $CFG;
1626 if (!empty($this->_wherethemewasinitialised)) {
1627 return;
1630 if (!during_initial_install()) {
1631 // Detect PAGE->context mess.
1632 $this->magic_get_context();
1635 if (!$this->_course && !during_initial_install()) {
1636 $this->set_course($SITE);
1639 if (is_null($this->_theme)) {
1640 $themename = $this->resolve_theme();
1641 $this->_theme = theme_config::load($themename);
1644 $this->_theme->setup_blocks($this->pagelayout, $this->blocks);
1646 if ($this === $PAGE) {
1647 $target = null;
1648 if ($this->pagelayout === 'maintenance') {
1649 // If the page is using the maintenance layout then we're going to force target to maintenance.
1650 // This leads to a special core renderer that is designed to block access to API's that are likely unavailable for this
1651 // page layout.
1652 $target = RENDERER_TARGET_MAINTENANCE;
1654 $OUTPUT = $this->get_renderer('core', null, $target);
1657 if (!during_initial_install()) {
1658 $filtermanager = filter_manager::instance();
1659 $filtermanager->setup_page_for_globally_available_filters($this);
1662 $this->_wherethemewasinitialised = debug_backtrace();
1666 * For diagnostic/debugging purposes, find where the theme setup was triggered.
1668 * @return null|array null if theme not yet setup. Stacktrace if it was.
1670 public function get_where_theme_was_initialised() {
1671 return $this->_wherethemewasinitialised;
1675 * Reset the theme and output for a new context. This only makes sense from
1676 * external::validate_context(). Do not cheat.
1678 * @return string the name of the theme that should be used on this page.
1680 public function reset_theme_and_output() {
1681 global $COURSE, $SITE;
1683 $COURSE = clone($SITE);
1684 $this->_theme = null;
1685 $this->_wherethemewasinitialised = null;
1686 $this->_course = null;
1687 $this->_cm = null;
1688 $this->_module = null;
1689 $this->_context = null;
1693 * Work out the theme this page should use.
1695 * This depends on numerous $CFG settings, and the properties of this page.
1697 * @return string the name of the theme that should be used on this page.
1699 protected function resolve_theme() {
1700 global $CFG, $USER, $SESSION;
1702 if (empty($CFG->themeorder)) {
1703 $themeorder = array('course', 'category', 'session', 'user', 'cohort', 'site');
1704 } else {
1705 $themeorder = $CFG->themeorder;
1706 // Just in case, make sure we always use the site theme if nothing else matched.
1707 $themeorder[] = 'site';
1710 $mnetpeertheme = '';
1711 $mnetvarsok = isset($CFG->mnet_localhost_id) && isset($USER->mnethostid);
1712 if (isloggedin() and $mnetvarsok and $USER->mnethostid != $CFG->mnet_localhost_id) {
1713 require_once($CFG->dirroot.'/mnet/peer.php');
1714 $mnetpeer = new mnet_peer();
1715 $mnetpeer->set_id($USER->mnethostid);
1716 if ($mnetpeer->force_theme == 1 && $mnetpeer->theme != '') {
1717 $mnetpeertheme = $mnetpeer->theme;
1721 $devicetheme = core_useragent::get_device_type_theme($this->devicetypeinuse);
1723 // The user is using another device than default, and we have a theme for that, we should use it.
1724 $hascustomdevicetheme = core_useragent::DEVICETYPE_DEFAULT != $this->devicetypeinuse && !empty($devicetheme);
1726 foreach ($themeorder as $themetype) {
1728 switch ($themetype) {
1729 case 'course':
1730 if (!empty($CFG->allowcoursethemes) && !empty($this->_course->theme) && !$hascustomdevicetheme) {
1731 return $this->_course->theme;
1733 break;
1735 case 'category':
1736 if (!empty($CFG->allowcategorythemes) && !$hascustomdevicetheme) {
1737 $categories = $this->categories;
1738 foreach ($categories as $category) {
1739 if (!empty($category->theme)) {
1740 return $category->theme;
1744 break;
1746 case 'session':
1747 if (!empty($SESSION->theme)) {
1748 return $SESSION->theme;
1750 break;
1752 case 'user':
1753 if (!empty($CFG->allowuserthemes) && !empty($USER->theme) && !$hascustomdevicetheme) {
1754 if ($mnetpeertheme) {
1755 return $mnetpeertheme;
1756 } else {
1757 return $USER->theme;
1760 break;
1762 case 'cohort':
1763 if (!empty($CFG->allowcohortthemes) && !empty($USER->cohorttheme) && !$hascustomdevicetheme) {
1764 return $USER->cohorttheme;
1766 break;
1768 case 'site':
1769 if ($mnetpeertheme) {
1770 return $mnetpeertheme;
1772 // First try for the device the user is using.
1773 if (!empty($devicetheme)) {
1774 return $devicetheme;
1776 // Next try for the default device (as a fallback).
1777 $devicetheme = core_useragent::get_device_type_theme(core_useragent::DEVICETYPE_DEFAULT);
1778 if (!empty($devicetheme)) {
1779 return $devicetheme;
1781 // The default device theme isn't set up - use the overall default theme.
1782 return theme_config::DEFAULT_THEME;
1786 // We should most certainly have resolved a theme by now. Something has gone wrong.
1787 debugging('Error resolving the theme to use for this page.', DEBUG_DEVELOPER);
1788 return theme_config::DEFAULT_THEME;
1793 * Sets ->pagetype from the script name. For example, if the script that was
1794 * run is mod/quiz/view.php, ->pagetype will be set to 'mod-quiz-view'.
1796 * @param string $script the path to the script that should be used to
1797 * initialise ->pagetype. If not passed the $SCRIPT global will be used.
1798 * If legacy code has set $CFG->pagepath that will be used instead, and a
1799 * developer warning issued.
1801 protected function initialise_default_pagetype($script = null) {
1802 global $CFG, $SCRIPT;
1804 if (isset($CFG->pagepath)) {
1805 debugging('Some code appears to have set $CFG->pagepath. That was a horrible deprecated thing. ' .
1806 'Don\'t do it! Try calling $PAGE->set_pagetype() instead.');
1807 $script = $CFG->pagepath;
1808 unset($CFG->pagepath);
1811 if (is_null($script)) {
1812 $script = ltrim($SCRIPT, '/');
1813 $len = strlen($CFG->admin);
1814 if (substr($script, 0, $len) == $CFG->admin) {
1815 $script = 'admin' . substr($script, $len);
1819 $path = str_replace('.php', '', $script);
1820 if (substr($path, -1) == '/') {
1821 $path .= 'index';
1824 if (empty($path) || $path == 'index') {
1825 $this->_pagetype = 'site-index';
1826 } else {
1827 $this->_pagetype = str_replace('/', '-', $path);
1832 * Initialises the CSS classes that will be added to body tag of the page.
1834 * The function is responsible for adding all of the critical CSS classes
1835 * that describe the current page, and its state.
1836 * This includes classes that describe the following for example:
1837 * - Current language
1838 * - Language direction
1839 * - YUI CSS initialisation
1840 * - Pagelayout
1841 * These are commonly used in CSS to target specific types of pages.
1843 protected function initialise_standard_body_classes() {
1844 global $CFG, $USER;
1846 $pagetype = $this->pagetype;
1847 if ($pagetype == 'site-index') {
1848 $this->_legacyclass = 'course';
1849 } else if (substr($pagetype, 0, 6) == 'admin-') {
1850 $this->_legacyclass = 'admin';
1852 $this->add_body_class($this->_legacyclass);
1854 $pathbits = explode('-', trim($pagetype));
1855 for ($i = 1; $i < count($pathbits); $i++) {
1856 $this->add_body_class('path-' . join('-', array_slice($pathbits, 0, $i)));
1859 $this->add_body_classes(core_useragent::get_browser_version_classes());
1860 $this->add_body_class('dir-' . get_string('thisdirection', 'langconfig'));
1861 $this->add_body_class('lang-' . current_language());
1862 $this->add_body_class('yui-skin-sam'); // Make YUI happy, if it is used.
1863 $this->add_body_class('yui3-skin-sam'); // Make YUI3 happy, if it is used.
1864 $this->add_body_class($this->url_to_class_name($CFG->wwwroot));
1866 // Extra class describing current page layout.
1867 $this->add_body_class('pagelayout-' . $this->_pagelayout);
1869 if (!during_initial_install()) {
1870 $this->add_body_class('course-' . $this->_course->id);
1871 $this->add_body_class('context-' . $this->_context->id);
1874 if (!empty($this->_cm)) {
1875 $this->add_body_class('cmid-' . $this->_cm->id);
1878 if (!empty($CFG->allowcategorythemes)) {
1879 $this->ensure_category_loaded();
1880 foreach ($this->_categories as $catid => $notused) {
1881 $this->add_body_class('category-' . $catid);
1883 } else {
1884 $catid = 0;
1885 if (is_array($this->_categories)) {
1886 $catids = array_keys($this->_categories);
1887 $catid = reset($catids);
1888 } else if (!empty($this->_course->category)) {
1889 $catid = $this->_course->category;
1891 if ($catid) {
1892 $this->add_body_class('category-' . $catid);
1896 if (!isloggedin()) {
1897 $this->add_body_class('notloggedin');
1900 if ($this->user_is_editing()) {
1901 $this->add_body_class('editing');
1902 if (optional_param('bui_moveid', false, PARAM_INT)) {
1903 $this->add_body_class('blocks-moving');
1907 if (!empty($CFG->blocksdrag)) {
1908 $this->add_body_class('drag');
1911 if ($this->_devicetypeinuse != 'default') {
1912 $this->add_body_class($this->_devicetypeinuse . 'theme');
1915 // Add class for behat site to apply behat related fixes.
1916 if (defined('BEHAT_SITE_RUNNING')) {
1917 $this->add_body_class('behat-site');
1922 * Loads the activity record for the current CM object associated with this
1923 * page.
1925 * This will load {@link moodle_page::$_module} with a row from the related
1926 * module table in the database.
1927 * For instance if {@link moodle_page::$_cm} is a forum then a row from the
1928 * forum table will be loaded.
1930 protected function load_activity_record() {
1931 global $DB;
1932 if (is_null($this->_cm)) {
1933 return;
1935 $this->_module = $DB->get_record($this->_cm->modname, array('id' => $this->_cm->instance));
1939 * This function ensures that the category of the current course has been
1940 * loaded, and if not, the function loads it now.
1942 * @return void
1943 * @throws coding_exception
1945 protected function ensure_category_loaded() {
1946 if (is_array($this->_categories)) {
1947 return; // Already done.
1949 if (is_null($this->_course)) {
1950 throw new coding_exception('Attempt to get the course category for this page before the course was set.');
1952 if ($this->_course->category == 0) {
1953 $this->_categories = array();
1954 } else {
1955 $this->load_category($this->_course->category);
1960 * Loads the requested category into the pages categories array.
1962 * @param int $categoryid
1963 * @throws moodle_exception
1965 protected function load_category($categoryid) {
1966 global $DB;
1967 $category = $DB->get_record('course_categories', array('id' => $categoryid));
1968 if (!$category) {
1969 throw new moodle_exception('unknowncategory');
1971 $this->_categories[$category->id] = $category;
1972 $parentcategoryids = explode('/', trim($category->path, '/'));
1973 array_pop($parentcategoryids);
1974 foreach (array_reverse($parentcategoryids) as $catid) {
1975 $this->_categories[$catid] = null;
1980 * Ensures that the category the current course is within, as well as all of
1981 * its parent categories, have been loaded.
1983 * @return void
1985 protected function ensure_categories_loaded() {
1986 global $DB;
1987 $this->ensure_category_loaded();
1988 if (!is_null(end($this->_categories))) {
1989 return; // Already done.
1991 $idstoload = array_keys($this->_categories);
1992 array_shift($idstoload);
1993 $categories = $DB->get_records_list('course_categories', 'id', $idstoload);
1994 foreach ($idstoload as $catid) {
1995 $this->_categories[$catid] = $categories[$catid];
2000 * Ensure the theme has not been loaded yet. If it has an exception is thrown.
2002 * @throws coding_exception
2004 protected function ensure_theme_not_set() {
2005 // This is explicitly allowed for webservices though which may process many course contexts in a single request.
2006 if (WS_SERVER) {
2007 return;
2010 if (!is_null($this->_theme)) {
2011 throw new coding_exception('The theme has already been set up for this page ready for output. ' .
2012 'Therefore, you can no longer change the theme, or anything that might affect what ' .
2013 'the current theme is, for example, the course.',
2014 'Stack trace when the theme was set up: ' . format_backtrace($this->_wherethemewasinitialised));
2019 * Converts the provided URL into a CSS class that be used within the page.
2020 * This is primarily used to add the wwwroot to the body tag as a CSS class.
2022 * @param string $url
2023 * @return string
2025 protected function url_to_class_name($url) {
2026 $bits = parse_url($url);
2027 $class = str_replace('.', '-', $bits['host']);
2028 if (!empty($bits['port'])) {
2029 $class .= '--' . $bits['port'];
2031 if (!empty($bits['path'])) {
2032 $path = trim($bits['path'], '/');
2033 if ($path) {
2034 $class .= '--' . str_replace('/', '-', $path);
2037 return $class;
2041 * Combines all of the required editing caps for the page and returns them
2042 * as an array.
2044 * @return array
2046 protected function all_editing_caps() {
2047 $caps = $this->_othereditingcaps;
2048 $caps[] = $this->_blockseditingcap;
2049 return $caps;
2053 * Returns true if the page URL has beem set.
2055 * @return bool
2057 public function has_set_url() {
2058 return ($this->_url!==null);
2062 * Gets set when the block actions for the page have been processed.
2064 * @param bool $setting
2066 public function set_block_actions_done($setting = true) {
2067 $this->_block_actions_done = $setting;
2071 * Are popup notifications allowed on this page?
2072 * Popup notifications may be disallowed in situations such as while upgrading or completing a quiz
2074 * @return bool true if popup notifications may be displayed
2076 public function get_popup_notification_allowed() {
2077 return $this->_popup_notification_allowed;
2081 * Allow or disallow popup notifications on this page. Popups are allowed by default.
2083 * @param bool $allowed true if notifications are allowed. False if not allowed. They are allowed by default.
2085 public function set_popup_notification_allowed($allowed) {
2086 $this->_popup_notification_allowed = $allowed;
2090 * Returns the block region having made any required theme manipulations.
2092 * @since Moodle 2.5.1 2.6
2093 * @param string $region
2094 * @return string
2096 public function apply_theme_region_manipulations($region) {
2097 if ($this->blockmanipulations && isset($this->blockmanipulations[$region])) {
2098 $regionwas = $region;
2099 $regionnow = $this->blockmanipulations[$region];
2100 if ($this->blocks->is_known_region($regionwas) && $this->blocks->is_known_region($regionnow)) {
2101 // Both the before and after regions are known so we can swap them over.
2102 return $regionnow;
2104 // We didn't know about both, we won't swap them over.
2105 return $regionwas;
2107 return $region;
2111 * Add a report node and a specific report to the navigation.
2113 * @param int $userid The user ID that we are looking to add this report node to.
2114 * @param array $nodeinfo Name and url of the final node that we are creating.
2116 public function add_report_nodes($userid, $nodeinfo) {
2117 global $USER;
2118 // Try to find the specific user node.
2119 $newusernode = $this->navigation->find('user' . $userid, null);
2120 $reportnode = null;
2121 $navigationnodeerror =
2122 'Could not find the navigation node requested. Please check that the node you are looking for exists.';
2123 if ($userid != $USER->id) {
2124 // Check that we have a valid node.
2125 if (empty($newusernode)) {
2126 // Throw an error if we ever reach here.
2127 throw new coding_exception($navigationnodeerror);
2129 // Add 'Reports' to the user node.
2130 $reportnode = $newusernode->add(get_string('reports'));
2131 } else {
2132 // We are looking at our own profile.
2133 $myprofilenode = $this->settingsnav->find('myprofile', null);
2134 // Check that we do end up with a valid node.
2135 if (empty($myprofilenode)) {
2136 // Throw an error if we ever reach here.
2137 throw new coding_exception($navigationnodeerror);
2139 // Add 'Reports' to our node.
2140 $reportnode = $myprofilenode->add(get_string('reports'));
2142 // Finally add the report to the navigation tree.
2143 $reportnode->add($nodeinfo['name'], $nodeinfo['url'], navigation_node::TYPE_CUSTOM, null, null,
2144 new pix_icon('i/report', $nodeinfo['name']));
2148 * Add some HTML to the list of actions to render in the header actions menu.
2150 * @param string $html The HTML to add.
2152 public function add_header_action(string $html) : void {
2153 $this->_headeractions[] = $html;
2157 * Get the list of HTML for actions to render in the header actions menu.
2159 * @return string[]
2161 public function get_header_actions() : array {
2162 return $this->_headeractions;
2166 * Set the flag to indicate if the region main settings should be rendered as an action
2167 * in the header actions menu rather than at the top of the content.
2169 * @param bool $value If the settings should be in the header.
2171 public function set_include_region_main_settings_in_header_actions(bool $value) : void {
2172 $this->_regionmainsettingsinheader = $value;
2176 * Check if the region main settings should be rendered as an action in the header actions
2177 * menu rather than at the top of the content.
2179 * @return bool
2181 public function include_region_main_settings_in_header_actions() : bool {
2182 return $this->_regionmainsettingsinheader;
2186 * Set the flag to indicate if the secondary navigation should be rendered.
2188 * @param bool $value If the secondary navigation should be rendered.
2190 public function has_secondary_navigation_setter(bool $value) : void {
2191 $this->_hassecondarynavigation = $value;
2195 * Check if the secondary navigation should be rendered.
2197 * @return bool
2199 public function has_secondary_navigation() : bool {
2200 return $this->_hassecondarynavigation;
2204 * Set the key of the secondary nav node to be activated.
2206 * @param string $navkey the key of the secondary nav node to be activated.
2208 public function set_secondary_active_tab(string $navkey) : void {
2209 $this->_activekeysecondary = $navkey;
2213 * The key of secondary nav node to activate.
2215 * @return string|null get the key of the secondary node to activate.
2217 public function get_secondary_active_tab(): ?string {
2218 return $this->_activekeysecondary;
2222 * Set the key of the primary nav node to be activated.
2224 * @param string $navkey
2226 public function set_primary_active_tab(string $navkey): void {
2227 $this->_activenodeprimary = $navkey;
2231 * The key of the primary nav node to activate.
2233 * @return string|null get the key of the primary nav node to activate.
2235 public function get_primary_activate_tab(): ?string {
2236 return $this->_activenodeprimary;