Moodle release 4.0
[moodle.git] / lib / pagelib.php
blob26cc6e5f86d2324a446e17ba73320f3f1be2137e
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();
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;
35 /**
36 * $PAGE is a central store of information about the current page we are
37 * generating in response to the user's request.
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.
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
50 * The following properties are alphabetical. Please keep it that way so that its
51 * easy to maintain.
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.
110 class moodle_page {
112 /** The state of the page before it has printed the header **/
113 const STATE_BEFORE_HEADER = 0;
115 /** The state the page is in temporarily while the header is being printed **/
116 const STATE_PRINTING_HEADER = 1;
118 /** The state the page is in while content is presumably being printed **/
119 const STATE_IN_BODY = 2;
122 * The state the page is when the footer has been printed and its function is
123 * complete.
125 const STATE_DONE = 3;
128 * @var int The current state of the page. The state a page is within
129 * determines what actions are possible for it.
131 protected $_state = self::STATE_BEFORE_HEADER;
134 * @var stdClass The course currently associated with this page.
135 * If not has been provided the front page course is used.
137 protected $_course = null;
140 * @var cm_info If this page belongs to a module, this is the cm_info module
141 * description object.
143 protected $_cm = null;
146 * @var stdClass If $_cm is not null, then this will hold the corresponding
147 * row from the modname table. For example, if $_cm->modname is 'quiz', this
148 * will be a row from the quiz table.
150 protected $_module = null;
153 * @var context The context that this page belongs to.
155 protected $_context = null;
158 * @var array This holds any categories that $_course belongs to, starting with the
159 * particular category it belongs to, and working out through any parent
160 * categories to the top level. These are loaded progressively, if needed.
161 * There are three states. $_categories = null initially when nothing is
162 * loaded; $_categories = array($id => $cat, $parentid => null) when we have
163 * loaded $_course->category, but not any parents; and a complete array once
164 * everything is loaded.
166 protected $_categories = null;
169 * @var array An array of CSS classes that should be added to the body tag in HTML.
171 protected $_bodyclasses = array();
174 * @var string The title for the page. Used within the title tag in the HTML head.
176 protected $_title = '';
179 * @var string The string to use as the heading of the page. Shown near the top of the
180 * page within most themes.
182 protected $_heading = '';
185 * @var string The pagetype is used to describe the page and defaults to a representation
186 * of the physical path to the page e.g. my-index, mod-quiz-attempt
188 protected $_pagetype = null;
191 * @var string The pagelayout to use when displaying this page. The
192 * pagelayout needs to have been defined by the theme in use, or one of its
193 * parents. By default base is used however standard is the more common layout.
194 * Note that this gets automatically set by core during operations like
195 * require_login.
197 protected $_pagelayout = 'base';
200 * @var array List of theme layout options, these are ignored by core.
201 * To be used in individual theme layout files only.
203 protected $_layout_options = null;
206 * @var string An optional arbitrary parameter that can be set on pages where the context
207 * and pagetype is not enough to identify the page.
209 protected $_subpage = '';
212 * @var string Set a different path to use for the 'Help and documentation' link.
213 * By default, it uses the path of the file for instance mod/quiz/attempt.
215 protected $_docspath = null;
218 * @var string A legacy class that will be added to the body tag
220 protected $_legacyclass = null;
223 * @var moodle_url The URL for this page. This is mandatory and must be set
224 * before output is started.
226 protected $_url = null;
229 * @var array An array of links to alternative versions of this page.
230 * Primarily used for RSS versions of the current page.
232 protected $_alternateversions = array();
235 * @var block_manager The blocks manager for this page. It is responsible for
236 * the blocks and there content on this page.
238 protected $_blocks = null;
241 * @var page_requirements_manager Page requirements manager. It is responsible
242 * for all JavaScript and CSS resources required by this page.
244 protected $_requires = null;
246 /** @var page_requirements_manager Saves the requirement manager object used before switching to to fragments one. */
247 protected $savedrequires = null;
250 * @var string The capability required by the user in order to edit blocks
251 * and block settings on this page.
253 protected $_blockseditingcap = 'moodle/site:manageblocks';
256 * @var bool An internal flag to record when block actions have been processed.
257 * Remember block actions occur on the current URL and it is important that
258 * even they are never executed more than once.
260 protected $_block_actions_done = false;
263 * @var array An array of any other capabilities the current user must have
264 * in order to editing the page and/or its content (not just blocks).
266 protected $_othereditingcaps = array();
269 * @var bool Sets whether this page should be cached by the browser or not.
270 * If it is set to true (default) the page is served with caching headers.
272 protected $_cacheable = true;
275 * @var string Can be set to the ID of an element on the page, if done that
276 * element receives focus when the page loads.
278 protected $_focuscontrol = '';
281 * @var string HTML to go where the turn on editing button is located. This
282 * is nearly a legacy item and not used very often any more.
284 protected $_button = '';
287 * @var theme_config The theme to use with this page. This has to be properly
288 * initialised via {@link moodle_page::initialise_theme_and_output()} which
289 * happens magically before any operation that requires it.
291 protected $_theme = null;
294 * @var global_navigation Contains the global navigation structure.
296 protected $_navigation = null;
299 * @var settings_navigation Contains the settings navigation structure.
301 protected $_settingsnav = null;
304 * @var flat_navigation Contains a list of nav nodes, most closely related to the current page.
306 protected $_flatnav = null;
309 * @var secondary Contains the nav nodes that will appear
310 * in the secondary navigation.
312 protected $_secondarynav = null;
315 * @var primary Contains the nav nodes that will appear
316 * in the primary navigation.
318 protected $_primarynav = null;
321 * @var primaryoutput Contains the combined nav nodes that will appear
322 * in the primary navigation. Includes - primarynav, langmenu, usermenu
324 protected $_primarynavcombined = null;
327 * @var navbar Contains the navbar structure.
329 protected $_navbar = null;
332 * @var string The menu (or actions) to display in the heading.
334 protected $_headingmenu = null;
337 * @var array stack trace. Then the theme is initialised, we save the stack
338 * trace, for use in error messages.
340 protected $_wherethemewasinitialised = null;
343 * @var xhtml_container_stack Tracks XHTML tags on this page that have been
344 * opened but not closed.
346 protected $_opencontainers;
349 * @var int Sets the page to refresh after a given delay (in seconds) using
350 * meta refresh in {@link standard_head_html()} in outputlib.php
351 * If set to null(default) the page is not refreshed
353 protected $_periodicrefreshdelay = null;
356 * @var array Associative array of browser shortnames (as used by check_browser_version)
357 * and their minimum required versions
359 protected $_legacybrowsers = array('MSIE' => 6.0);
362 * @var string Is set to the name of the device type in use.
363 * This will we worked out when it is first used.
365 protected $_devicetypeinuse = null;
368 * @var bool Used to determine if HTTPS should be required for login.
370 protected $_https_login_required = false;
373 * @var bool Determines if popup notifications allowed on this page.
374 * Code such as the quiz module disables popup notifications in situations
375 * such as upgrading or completing a quiz.
377 protected $_popup_notification_allowed = true;
380 * @var bool Is the settings menu being forced to display on this page (activities / resources only).
381 * This is only used by themes that use the settings menu.
383 protected $_forcesettingsmenu = false;
386 * @var array Array of header actions HTML to add to the page header actions menu.
388 protected $_headeractions = [];
391 * @var bool Should the region main settings menu be rendered in the header.
393 protected $_regionmainsettingsinheader = false;
396 * @var bool Should the secondary menu be rendered.
398 protected $_hassecondarynavigation = true;
401 * @var bool Should the secondary menu be rendered as a tablist as opposed to a menubar.
403 protected $_hastablistsecondarynavigation = false;
406 * @var string the key of the secondary node to be activated.
408 protected $_activekeysecondary = null;
411 * @var string the key of the primary node to be activated.
413 protected $_activenodeprimary = null;
416 * @var activity_header The activity header for the page.
418 protected $_activityheader;
421 * @var bool The value of displaying the navigation overflow.
423 protected $_navigationoverflow = true;
426 * @var bool Whether to override/remove all editing capabilities for blocks on the page.
428 protected $_forcelockallblocks = false;
431 * Force the settings menu to be displayed on this page. This will only force the
432 * settings menu on an activity / resource page that is being displayed on a theme that
433 * uses a settings menu.
435 * @param bool $forced default of true, can be sent false to turn off the force.
437 public function force_settings_menu($forced = true) {
438 $this->_forcesettingsmenu = $forced;
442 * Check to see if the settings menu is forced to display on this activity / resource page.
443 * This only applies to themes that use the settings menu.
445 * @return bool True if the settings menu is forced to display.
447 public function is_settings_menu_forced() {
448 return $this->_forcesettingsmenu;
451 // Magic getter methods =============================================================
452 // Due to the __get magic below, you normally do not call these as $PAGE->magic_get_x
453 // methods, but instead use the $PAGE->x syntax.
456 * Please do not call this method directly, use the ->state syntax. {@link moodle_page::__get()}.
457 * @return integer one of the STATE_XXX constants. You should not normally need
458 * to use this in your code. It is intended for internal use by this class
459 * and its friends like print_header, to check that everything is working as
460 * expected. Also accessible as $PAGE->state.
462 protected function magic_get_state() {
463 return $this->_state;
467 * Please do not call this method directly, use the ->headerprinted syntax. {@link moodle_page::__get()}.
468 * @return bool has the header already been printed?
470 protected function magic_get_headerprinted() {
471 return $this->_state >= self::STATE_IN_BODY;
475 * Please do not call this method directly, use the ->course syntax. {@link moodle_page::__get()}.
476 * @return stdClass the current course that we are inside - a row from the
477 * course table. (Also available as $COURSE global.) If we are not inside
478 * an actual course, this will be the site course.
480 protected function magic_get_course() {
481 global $SITE;
482 if (is_null($this->_course)) {
483 return $SITE;
485 return $this->_course;
489 * Please do not call this method directly, use the ->cm syntax. {@link moodle_page::__get()}.
490 * @return cm_info the course_module that this page belongs to. Will be null
491 * if this page is not within a module. This is a full cm object, as loaded
492 * by get_coursemodule_from_id or get_coursemodule_from_instance,
493 * so the extra modname and name fields are present.
495 protected function magic_get_cm() {
496 return $this->_cm;
500 * Please do not call this method directly, use the ->activityrecord syntax. {@link moodle_page::__get()}.
501 * @return stdClass the row from the activities own database table (for example
502 * the forum or quiz table) that this page belongs to. Will be null
503 * if this page is not within a module.
505 protected function magic_get_activityrecord() {
506 if (is_null($this->_module) && !is_null($this->_cm)) {
507 $this->load_activity_record();
509 return $this->_module;
513 * Please do not call this method directly, use the ->activityname syntax. {@link moodle_page::__get()}.
514 * @return string the The type of activity we are in, for example 'forum' or 'quiz'.
515 * Will be null if this page is not within a module.
517 protected function magic_get_activityname() {
518 if (is_null($this->_cm)) {
519 return null;
521 return $this->_cm->modname;
525 * Please do not call this method directly, use the ->category syntax. {@link moodle_page::__get()}.
526 * @return stdClass the category that the page course belongs to. If there isn't one
527 * (that is, if this is the front page course) returns null.
529 protected function magic_get_category() {
530 $this->ensure_category_loaded();
531 if (!empty($this->_categories)) {
532 return reset($this->_categories);
533 } else {
534 return null;
539 * Please do not call this method directly, use the ->categories syntax. {@link moodle_page::__get()}.
540 * @return array an array of all the categories the page course belongs to,
541 * starting with the immediately containing category, and working out to
542 * the top-level category. This may be the empty array if we are in the
543 * front page course.
545 protected function magic_get_categories() {
546 $this->ensure_categories_loaded();
547 return $this->_categories;
551 * Please do not call this method directly, use the ->context syntax. {@link moodle_page::__get()}.
552 * @return context the main context to which this page belongs.
554 protected function magic_get_context() {
555 global $CFG;
556 if (is_null($this->_context)) {
557 if (CLI_SCRIPT or NO_MOODLE_COOKIES) {
558 // Cli scripts work in system context, do not annoy devs with debug info.
559 // Very few scripts do not use cookies, we can safely use system as default context there.
560 } else if (AJAX_SCRIPT && $CFG->debugdeveloper) {
561 // Throw exception inside AJAX script in developer mode, otherwise the debugging message may be missed.
562 throw new coding_exception('$PAGE->context was not set. You may have forgotten '
563 .'to call require_login() or $PAGE->set_context()');
564 } else {
565 debugging('Coding problem: $PAGE->context was not set. You may have forgotten '
566 .'to call require_login() or $PAGE->set_context(). The page may not display '
567 .'correctly as a result');
569 $this->_context = context_system::instance();
571 return $this->_context;
575 * Please do not call this method directly, use the ->pagetype syntax. {@link moodle_page::__get()}.
576 * @return string e.g. 'my-index' or 'mod-quiz-attempt'.
578 protected function magic_get_pagetype() {
579 global $CFG;
580 if (is_null($this->_pagetype) || isset($CFG->pagepath)) {
581 $this->initialise_default_pagetype();
583 return $this->_pagetype;
587 * Please do not call this method directly, use the ->pagetype syntax. {@link moodle_page::__get()}.
588 * @return string The id to use on the body tag, uses {@link magic_get_pagetype()}.
590 protected function magic_get_bodyid() {
591 return 'page-'.$this->pagetype;
595 * Please do not call this method directly, use the ->pagelayout syntax. {@link moodle_page::__get()}.
596 * @return string the general type of page this is. For example 'standard', 'popup', 'home'.
597 * Allows the theme to display things differently, if it wishes to.
599 protected function magic_get_pagelayout() {
600 return $this->_pagelayout;
604 * Please do not call this method directly, use the ->layout_options syntax. {@link moodle_page::__get()}.
605 * @return array returns arrays with options for layout file
607 protected function magic_get_layout_options() {
608 if (!is_array($this->_layout_options)) {
609 $this->_layout_options = $this->_theme->pagelayout_options($this->pagelayout);
611 return $this->_layout_options;
615 * Please do not call this method directly, use the ->subpage syntax. {@link moodle_page::__get()}.
616 * @return string The subpage identifier, if any.
618 protected function magic_get_subpage() {
619 return $this->_subpage;
623 * Please do not call this method directly, use the ->bodyclasses syntax. {@link moodle_page::__get()}.
624 * @return string the class names to put on the body element in the HTML.
626 protected function magic_get_bodyclasses() {
627 return implode(' ', array_keys($this->_bodyclasses));
631 * Please do not call this method directly, use the ->title syntax. {@link moodle_page::__get()}.
632 * @return string the title that should go in the <head> section of the HTML of this page.
634 protected function magic_get_title() {
635 return $this->_title;
639 * Please do not call this method directly, use the ->heading syntax. {@link moodle_page::__get()}.
640 * @return string the main heading that should be displayed at the top of the <body>.
642 protected function magic_get_heading() {
643 return $this->_heading;
647 * Please do not call this method directly, use the ->heading syntax. {@link moodle_page::__get()}.
648 * @return string The menu (or actions) to display in the heading
650 protected function magic_get_headingmenu() {
651 return $this->_headingmenu;
655 * Please do not call this method directly, use the ->docspath syntax. {@link moodle_page::__get()}.
656 * @return string the path to the Help and documentation.
658 protected function magic_get_docspath() {
659 if (is_string($this->_docspath)) {
660 return $this->_docspath;
661 } else {
662 return str_replace('-', '/', $this->pagetype);
667 * Please do not call this method directly, use the ->url syntax. {@link moodle_page::__get()}.
668 * @return moodle_url the clean URL required to load the current page. (You
669 * should normally use this in preference to $ME or $FULLME.)
671 protected function magic_get_url() {
672 global $FULLME;
673 if (is_null($this->_url)) {
674 debugging('This page did not call $PAGE->set_url(...). Using '.s($FULLME), DEBUG_DEVELOPER);
675 $this->_url = new moodle_url($FULLME);
676 // Make sure the guessed URL cannot lead to dangerous redirects.
677 $this->_url->remove_params('sesskey');
679 return new moodle_url($this->_url); // Return a clone for safety.
683 * The list of alternate versions of this page.
684 * @return array mime type => object with ->url and ->title.
686 protected function magic_get_alternateversions() {
687 return $this->_alternateversions;
691 * Please do not call this method directly, use the ->blocks syntax. {@link moodle_page::__get()}.
692 * @return block_manager the blocks manager object for this page.
694 protected function magic_get_blocks() {
695 global $CFG;
696 if (is_null($this->_blocks)) {
697 if (!empty($CFG->blockmanagerclass)) {
698 if (!empty($CFG->blockmanagerclassfile)) {
699 require_once($CFG->blockmanagerclassfile);
701 $classname = $CFG->blockmanagerclass;
702 } else {
703 $classname = 'block_manager';
705 $this->_blocks = new $classname($this);
707 return $this->_blocks;
711 * Please do not call this method directly, use the ->requires syntax. {@link moodle_page::__get()}.
712 * @return page_requirements_manager tracks the JavaScript, CSS files, etc. required by this page.
714 protected function magic_get_requires() {
715 if (is_null($this->_requires)) {
716 $this->_requires = new page_requirements_manager();
718 return $this->_requires;
722 * Please do not call this method directly, use the ->cacheable syntax. {@link moodle_page::__get()}.
723 * @return bool can this page be cached by the user's browser.
725 protected function magic_get_cacheable() {
726 return $this->_cacheable;
730 * Please do not call this method directly, use the ->focuscontrol syntax. {@link moodle_page::__get()}.
731 * @return string the id of the HTML element to be focused when the page has loaded.
733 protected function magic_get_focuscontrol() {
734 return $this->_focuscontrol;
738 * Please do not call this method directly, use the ->button syntax. {@link moodle_page::__get()}.
739 * @return string the HTML to go where the Turn editing on button normally goes.
741 protected function magic_get_button() {
742 return $this->_button;
746 * Please do not call this method directly, use the ->theme syntax. {@link moodle_page::__get()}.
747 * @return theme_config the initialised theme for this page.
749 protected function magic_get_theme() {
750 if (is_null($this->_theme)) {
751 $this->initialise_theme_and_output();
753 return $this->_theme;
757 * Returns an array of minipulations or false if there are none to make.
759 * @since Moodle 2.5.1 2.6
760 * @return bool|array
762 protected function magic_get_blockmanipulations() {
763 if (!right_to_left()) {
764 return false;
766 if (is_null($this->_theme)) {
767 $this->initialise_theme_and_output();
769 return $this->_theme->blockrtlmanipulations;
773 * Please do not call this method directly, use the ->devicetypeinuse syntax. {@link moodle_page::__get()}.
774 * @return string The device type being used.
776 protected function magic_get_devicetypeinuse() {
777 if (empty($this->_devicetypeinuse)) {
778 $this->_devicetypeinuse = core_useragent::get_user_device_type();
780 return $this->_devicetypeinuse;
784 * Please do not call this method directly use the ->periodicrefreshdelay syntax
785 * {@link moodle_page::__get()}
786 * @return int The periodic refresh delay to use with meta refresh
788 protected function magic_get_periodicrefreshdelay() {
789 return $this->_periodicrefreshdelay;
793 * Please do not call this method directly use the ->opencontainers syntax. {@link moodle_page::__get()}
794 * @return xhtml_container_stack tracks XHTML tags on this page that have been opened but not closed.
795 * mainly for internal use by the rendering code.
797 protected function magic_get_opencontainers() {
798 if (is_null($this->_opencontainers)) {
799 $this->_opencontainers = new xhtml_container_stack();
801 return $this->_opencontainers;
805 * Return the navigation object
806 * @return global_navigation
808 protected function magic_get_navigation() {
809 if ($this->_navigation === null) {
810 $this->_navigation = new global_navigation($this);
812 return $this->_navigation;
816 * Return a navbar object
817 * @return navbar
819 protected function magic_get_navbar() {
820 if ($this->_navbar === null) {
821 $this->_navbar = new navbar($this);
823 return $this->_navbar;
827 * Returns the settings navigation object
828 * @return settings_navigation
830 protected function magic_get_settingsnav() {
831 if ($this->_settingsnav === null) {
832 $this->_settingsnav = new settings_navigation($this);
833 $this->_settingsnav->initialise();
835 return $this->_settingsnav;
839 * Returns the flat navigation object
840 * @return flat_navigation
842 protected function magic_get_flatnav() {
843 if ($this->_flatnav === null) {
844 $this->_flatnav = new flat_navigation($this);
845 $this->_flatnav->initialise();
847 return $this->_flatnav;
851 * Returns the activity header object
852 * @return activity_header
854 protected function magic_get_activityheader(): activity_header {
855 global $USER;
856 if ($this->_activityheader === null) {
857 $class = activity_header::class;
858 // Try and load a custom class first.
859 if (class_exists("mod_{$this->activityname}\\output\\activity_header")) {
860 $class = "mod_{$this->activityname}\\output\\activity_header";
863 $this->_activityheader = new $class($this, $USER);
865 return $this->_activityheader;
869 * Returns the secondary navigation object
870 * @return secondary
872 protected function magic_get_secondarynav() {
873 if ($this->_secondarynav === null) {
874 $class = 'core\navigation\views\secondary';
875 // Try and load a custom class first.
876 if (class_exists("mod_{$this->activityname}\\local\\views\\secondary")) {
877 $class = "mod_{$this->activityname}\\local\\views\\secondary";
880 $this->_secondarynav = new $class($this);
881 $this->_secondarynav->initialise();
883 return $this->_secondarynav;
887 * Returns the primary navigation object
888 * @return primary
890 protected function magic_get_primarynav() {
891 if ($this->_primarynav === null) {
892 $this->_primarynav = new primary($this);
893 $this->_primarynav->initialise();
895 return $this->_primarynav;
899 * Returns the primary navigation object
900 * @return primary
902 protected function magic_get_primarynavcombined() {
903 if ($this->_primarynavcombined === null) {
904 $this->_primarynavcombined = new primaryoutput($this);
906 return $this->_primarynavcombined;
910 * Returns request IP address.
912 * @return string IP address or null if unknown
914 protected function magic_get_requestip() {
915 return getremoteaddr(null);
919 * Returns the origin of current request.
921 * Note: constants are not required because we need to use these values in logging and reports.
923 * @return string 'web', 'ws', 'cli', 'restore', etc.
925 protected function magic_get_requestorigin() {
926 if (class_exists('restore_controller', false) && restore_controller::is_executing()) {
927 return 'restore';
930 if (WS_SERVER) {
931 return 'ws';
934 if (CLI_SCRIPT) {
935 return 'cli';
938 return 'web';
942 * PHP overloading magic to make the $PAGE->course syntax work by redirecting
943 * it to the corresponding $PAGE->magic_get_course() method if there is one, and
944 * throwing an exception if not.
946 * @param string $name property name
947 * @return mixed
948 * @throws coding_exception
950 public function __get($name) {
951 $getmethod = 'magic_get_' . $name;
952 if (method_exists($this, $getmethod)) {
953 return $this->$getmethod();
954 } else {
955 throw new coding_exception('Unknown property ' . $name . ' of $PAGE.');
960 * PHP overloading magic to catch obvious coding errors.
962 * This method has been created to catch obvious coding errors where the
963 * developer has tried to set a page property using $PAGE->key = $value.
964 * In the moodle_page class all properties must be set using the appropriate
965 * $PAGE->set_something($value) method.
967 * @param string $name property name
968 * @param mixed $value Value
969 * @return void Throws exception if field not defined in page class
970 * @throws coding_exception
972 public function __set($name, $value) {
973 if (method_exists($this, 'set_' . $name)) {
974 throw new coding_exception('Invalid attempt to modify page object', "Use \$PAGE->set_$name() instead.");
975 } else {
976 throw new coding_exception('Invalid attempt to modify page object', "Unknown property $name");
980 // Other information getting methods ==========================================.
983 * Returns instance of page renderer
985 * @param string $component name such as 'core', 'mod_forum' or 'qtype_multichoice'.
986 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
987 * @param string $target one of rendering target constants
988 * @return renderer_base
990 public function get_renderer($component, $subtype = null, $target = null) {
991 if ($this->pagelayout === 'maintenance') {
992 // If the page is using the maintenance layout then we're going to force target to maintenance.
993 // This leads to a special core renderer that is designed to block access to API's that are likely unavailable for this
994 // page layout.
995 $target = RENDERER_TARGET_MAINTENANCE;
997 return $this->magic_get_theme()->get_renderer($this, $component, $subtype, $target);
1001 * Checks to see if there are any items on the navbar object
1003 * @return bool true if there are, false if not
1005 public function has_navbar() {
1006 if ($this->_navbar === null) {
1007 $this->_navbar = new navbar($this);
1009 return $this->_navbar->has_items();
1013 * Switches from the regular requirements manager to the fragment requirements manager to
1014 * capture all necessary JavaScript to display a chunk of HTML such as an mform. This is for use
1015 * by the get_fragment() web service and not for use elsewhere.
1017 public function start_collecting_javascript_requirements() {
1018 global $CFG;
1019 require_once($CFG->libdir.'/outputfragmentrequirementslib.php');
1021 // Check that the requirements manager has not already been switched.
1022 if (get_class($this->_requires) == 'fragment_requirements_manager') {
1023 throw new coding_exception('JavaScript collection has already been started.');
1025 // The header needs to have been called to flush out the generic JavaScript for the page. This allows only
1026 // JavaScript for the fragment to be collected. _wherethemewasinitialised is set when header() is called.
1027 if (!empty($this->_wherethemewasinitialised)) {
1028 // Change the current requirements manager over to the fragment manager to capture JS.
1029 $this->savedrequires = $this->_requires;
1030 $this->_requires = new fragment_requirements_manager();
1031 } else {
1032 throw new coding_exception('$OUTPUT->header() needs to be called before collecting JavaScript requirements.');
1037 * Switches back from collecting fragment JS requirement to the original requirement manager
1039 public function end_collecting_javascript_requirements() {
1040 if ($this->savedrequires === null) {
1041 throw new coding_exception('JavaScript collection has not been started.');
1043 $this->_requires = $this->savedrequires;
1044 $this->savedrequires = null;
1048 * Should the current user see this page in editing mode.
1049 * That is, are they allowed to edit this page, and are they currently in
1050 * editing mode.
1051 * @return bool
1053 public function user_is_editing() {
1054 global $USER;
1055 return !empty($USER->editing) && $this->user_allowed_editing();
1059 * Does the user have permission to edit blocks on this page.
1060 * Can be forced to false by calling the force_lock_all_blocks() method.
1062 * @return bool
1064 public function user_can_edit_blocks() {
1065 return $this->_forcelockallblocks ? false : has_capability($this->_blockseditingcap, $this->_context);
1069 * Does the user have permission to see this page in editing mode.
1070 * @return bool
1072 public function user_allowed_editing() {
1073 return has_any_capability($this->all_editing_caps(), $this->_context);
1077 * Get a description of this page. Normally displayed in the footer in developer debug mode.
1078 * @return string
1080 public function debug_summary() {
1081 $summary = '';
1082 $summary .= 'General type: ' . $this->pagelayout . '. ';
1083 if (!during_initial_install()) {
1084 $summary .= 'Context ' . $this->context->get_context_name() . ' (context id ' . $this->_context->id . '). ';
1086 $summary .= 'Page type ' . $this->pagetype . '. ';
1087 if ($this->subpage) {
1088 $summary .= 'Sub-page ' . $this->subpage . '. ';
1090 return $summary;
1093 // Setter methods =============================================================.
1096 * Set the state.
1098 * The state must be one of that STATE_... constants, and the state is only allowed to advance one step at a time.
1100 * @param int $state The new state.
1101 * @throws coding_exception
1103 public function set_state($state) {
1104 if ($state != $this->_state + 1 || $state > self::STATE_DONE) {
1105 throw new coding_exception('Invalid state passed to moodle_page::set_state. We are in state ' .
1106 $this->_state . ' and state ' . $state . ' was requested.');
1109 if ($state == self::STATE_PRINTING_HEADER) {
1110 $this->starting_output();
1113 $this->_state = $state;
1117 * Set the current course. This sets both $PAGE->course and $COURSE. It also
1118 * sets the right theme and locale.
1120 * Normally you don't need to call this function yourself, require_login will
1121 * call it for you if you pass a $course to it. You can use this function
1122 * on pages that do need to call require_login().
1124 * Sets $PAGE->context to the course context, if it is not already set.
1126 * @param stdClass $course the course to set as the global course.
1127 * @throws coding_exception
1129 public function set_course($course) {
1130 global $COURSE, $PAGE, $CFG, $SITE;
1132 if (empty($course->id)) {
1133 throw new coding_exception('$course passed to moodle_page::set_course does not look like a proper course object.');
1136 $this->ensure_theme_not_set();
1138 if (!empty($this->_course->id) && $this->_course->id != $course->id) {
1139 $this->_categories = null;
1142 $this->_course = clone($course);
1144 if ($this === $PAGE) {
1145 $COURSE = $this->_course;
1146 moodle_setlocale();
1149 if (!$this->_context) {
1150 $this->set_context(context_course::instance($this->_course->id));
1153 // Notify course format that this page is set for the course.
1154 if ($this->_course->id != $SITE->id) {
1155 require_once($CFG->dirroot.'/course/lib.php');
1156 $courseformat = course_get_format($this->_course);
1157 $this->add_body_class('format-'. $courseformat->get_format());
1158 $courseformat->page_set_course($this);
1159 } else {
1160 $this->add_body_class('format-site');
1165 * Set the main context to which this page belongs.
1167 * @param context $context a context object. You normally get this with context_xxxx::instance().
1169 public function set_context($context) {
1170 if ($context === null) {
1171 // Extremely ugly hack which sets context to some value in order to prevent warnings,
1172 // use only for core error handling!!!!
1173 if (!$this->_context) {
1174 $this->_context = context_system::instance();
1176 return;
1178 // Ideally we should set context only once.
1179 if (isset($this->_context) && $context->id !== $this->_context->id) {
1180 $current = $this->_context->contextlevel;
1181 if ($current == CONTEXT_SYSTEM or $current == CONTEXT_COURSE) {
1182 // Hmm - not ideal, but it might produce too many warnings due to the design of require_login.
1183 } else if ($current == CONTEXT_MODULE and ($parentcontext = $context->get_parent_context()) and
1184 $this->_context->id == $parentcontext->id) {
1185 // Hmm - most probably somebody did require_login() and after that set the block context.
1186 } else {
1187 // We do not want devs to do weird switching of context levels on the fly because we might have used
1188 // the context already such as in text filter in page title.
1189 debugging("Coding problem: unsupported modification of PAGE->context from {$current} to {$context->contextlevel}");
1193 $this->_context = $context;
1197 * The course module that this page belongs to (if it does belong to one).
1199 * @param stdClass|cm_info $cm a record from course_modules table or cm_info from get_fast_modinfo().
1200 * @param stdClass $course
1201 * @param stdClass $module
1202 * @return void
1203 * @throws coding_exception
1205 public function set_cm($cm, $course = null, $module = null) {
1206 global $DB, $CFG, $SITE;
1208 if (!isset($cm->id) || !isset($cm->course)) {
1209 throw new coding_exception('Invalid $cm. It has to be instance of cm_info or record from the course_modules table.');
1212 if (!$this->_course || $this->_course->id != $cm->course) {
1213 if (!$course) {
1214 $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
1216 if ($course->id != $cm->course) {
1217 throw new coding_exception('The course you passed to $PAGE->set_cm does not correspond to the $cm.');
1219 $this->set_course($course);
1222 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
1223 if (!($cm instanceof cm_info)) {
1224 $modinfo = get_fast_modinfo($this->_course);
1225 $cm = $modinfo->get_cm($cm->id);
1227 $this->_cm = $cm;
1229 // Unfortunately the context setting is a mess.
1230 // Let's try to work around some common block problems and show some debug messages.
1231 if (empty($this->_context) or $this->_context->contextlevel != CONTEXT_BLOCK) {
1232 $context = context_module::instance($cm->id);
1233 $this->set_context($context);
1236 if ($module) {
1237 $this->set_activity_record($module);
1240 // Notify course format that this page is set for the course module.
1241 if ($this->_course->id != $SITE->id) {
1242 require_once($CFG->dirroot.'/course/lib.php');
1243 course_get_format($this->_course)->page_set_cm($this);
1248 * Sets the activity record. This could be a row from the main table for a
1249 * module. For instance if the current module (cm) is a forum this should be a row
1250 * from the forum table.
1252 * @param stdClass $module A row from the main database table for the module that this page belongs to.
1253 * @throws coding_exception
1255 public function set_activity_record($module) {
1256 if (is_null($this->_cm)) {
1257 throw new coding_exception('You cannot call $PAGE->set_activity_record until after $PAGE->cm has been set.');
1259 if ($module->id != $this->_cm->instance || $module->course != $this->_course->id) {
1260 throw new coding_exception('The activity record does not seem to correspond to the cm that has been set.');
1262 $this->_module = $module;
1266 * Sets the pagetype to use for this page.
1268 * Normally you do not need to set this manually, it is automatically created
1269 * from the script name. However, on some pages this is overridden.
1270 * For example the page type for course/view.php includes the course format,
1271 * for example 'course-view-weeks'. This gets used as the id attribute on
1272 * <body> and also for determining which blocks are displayed.
1274 * @param string $pagetype e.g. 'my-index' or 'mod-quiz-attempt'.
1276 public function set_pagetype($pagetype) {
1277 $this->_pagetype = $pagetype;
1281 * Sets the layout to use for this page.
1283 * The page layout determines how the page will be displayed, things such as
1284 * block regions, content areas, etc are controlled by the layout.
1285 * The theme in use for the page will determine that the layout contains.
1287 * This properly defaults to 'base', so you only need to call this function if
1288 * you want something different. The exact range of supported layouts is specified
1289 * in the standard theme.
1291 * For an idea of the common page layouts see
1292 * {@link http://docs.moodle.org/dev/Themes_2.0#The_different_layouts_as_of_August_17th.2C_2010}
1293 * But please keep in mind that it may be (and normally is) out of date.
1294 * The only place to find an accurate up-to-date list of the page layouts
1295 * available for your version of Moodle is {@link theme/base/config.php}
1297 * @param string $pagelayout the page layout this is. For example 'popup', 'home'.
1299 public function set_pagelayout($pagelayout) {
1300 global $SESSION;
1302 if (!empty($SESSION->forcepagelayout)) {
1303 $this->_pagelayout = $SESSION->forcepagelayout;
1304 } else {
1305 // Uncomment this to debug theme pagelayout issues like missing blocks.
1306 // if (!empty($this->_wherethemewasinitialised) && $pagelayout != $this->_pagelayout)
1307 // debugging('Page layout has already been set and cannot be changed.', DEBUG_DEVELOPER);
1308 $this->_pagelayout = $pagelayout;
1313 * If context->id and pagetype are not enough to uniquely identify this page,
1314 * then you can set a subpage id as well. For example, the tags page sets
1316 * @param string $subpage an arbitrary identifier that, along with context->id
1317 * and pagetype, uniquely identifies this page.
1319 public function set_subpage($subpage) {
1320 if (empty($subpage)) {
1321 $this->_subpage = '';
1322 } else {
1323 $this->_subpage = $subpage;
1328 * Force set secondary_nav. Useful in cases where we dealing with non course modules. e.g. blocks, tools.
1329 * @param secondary $nav
1331 public function set_secondarynav(secondary $nav) {
1332 $this->_secondarynav = $nav;
1336 * Adds a CSS class to the body tag of the page.
1338 * @param string $class add this class name ot the class attribute on the body tag.
1339 * @throws coding_exception
1341 public function add_body_class($class) {
1342 if ($this->_state > self::STATE_BEFORE_HEADER) {
1343 throw new coding_exception('Cannot call moodle_page::add_body_class after output has been started.');
1345 $this->_bodyclasses[$class] = 1;
1349 * Adds an array of body classes to the body tag of this page.
1351 * @param array $classes this utility method calls add_body_class for each array element.
1353 public function add_body_classes($classes) {
1354 foreach ($classes as $class) {
1355 $this->add_body_class($class);
1360 * Sets the title for the page.
1361 * This is normally used within the title tag in the head of the page.
1363 * @param string $title the title that should go in the <head> section of the HTML of this page.
1365 public function set_title($title) {
1366 $title = format_string($title);
1367 $title = strip_tags($title);
1368 $title = str_replace('"', '&quot;', $title);
1369 $this->_title = $title;
1373 * Sets the heading to use for the page.
1374 * This is normally used as the main heading at the top of the content.
1376 * @param string $heading the main heading that should be displayed at the top of the <body>.
1377 * @param bool $applyformatting apply format_string() - by default true.
1379 public function set_heading($heading, bool $applyformatting = true) {
1380 $this->_heading = $applyformatting ? format_string($heading) : clean_text($heading);
1384 * Sets some HTML to use next to the heading {@link moodle_page::set_heading()}
1386 * @param string $menu The menu/content to show in the heading
1388 public function set_headingmenu($menu) {
1389 $this->_headingmenu = $menu;
1393 * Set the course category this page belongs to manually.
1395 * This automatically sets $PAGE->course to be the site course. You cannot
1396 * use this method if you have already set $PAGE->course - in that case,
1397 * the category must be the one that the course belongs to. This also
1398 * automatically sets the page context to the category context.
1400 * @param int $categoryid The id of the category to set.
1401 * @throws coding_exception
1403 public function set_category_by_id($categoryid) {
1404 global $SITE;
1405 if (!is_null($this->_course)) {
1406 throw new coding_exception('Course has already been set. You cannot change the category now.');
1408 if (is_array($this->_categories)) {
1409 throw new coding_exception('Course category has already been set. You cannot to change it now.');
1411 $this->ensure_theme_not_set();
1412 $this->set_course($SITE);
1413 $this->load_category($categoryid);
1414 $this->set_context(context_coursecat::instance($categoryid));
1418 * Set a different path to use for the 'Help and documentation' link.
1420 * By default, it uses the pagetype, which is normally the same as the
1421 * script name. So, for example, for mod/quiz/attempt.php, pagetype is
1422 * mod-quiz-attempt, and so docspath is mod/quiz/attempt.
1424 * @param string $path the path to use at the end of the moodle docs URL.
1426 public function set_docs_path($path) {
1427 $this->_docspath = $path;
1431 * You should call this method from every page to set the URL that should be used to return to this page.
1433 * Used, for example, by the blocks editing UI to know where to return the
1434 * user after an action.
1435 * For example, course/view.php does:
1436 * $id = optional_param('id', 0, PARAM_INT);
1437 * $PAGE->set_url('/course/view.php', array('id' => $id));
1439 * @param moodle_url|string $url URL relative to $CFG->wwwroot or {@link moodle_url} instance
1440 * @param array $params parameters to add to the URL
1441 * @throws coding_exception
1443 public function set_url($url, array $params = null) {
1444 global $CFG;
1446 if (is_string($url) && strpos($url, 'http') !== 0) {
1447 if (strpos($url, '/') === 0) {
1448 // Add the wwwroot to the relative url.
1449 $url = $CFG->wwwroot . $url;
1450 } else {
1451 throw new coding_exception('Invalid parameter $url, has to be full url or in shortened form starting with /.');
1455 $this->_url = new moodle_url($url, $params);
1457 $fullurl = $this->_url->out_omit_querystring();
1458 if (strpos($fullurl, "$CFG->wwwroot/") !== 0) {
1459 debugging('Most probably incorrect set_page() url argument, it does not match the wwwroot!');
1461 $shorturl = str_replace("$CFG->wwwroot/", '', $fullurl);
1463 if (is_null($this->_pagetype)) {
1464 $this->initialise_default_pagetype($shorturl);
1469 * Make sure page URL does not contain the given URL parameter.
1471 * This should not be necessary if the script has called set_url properly.
1472 * However, in some situations like the block editing actions; when the URL
1473 * has been guessed, it will contain dangerous block-related actions.
1474 * Therefore, the blocks code calls this function to clean up such parameters
1475 * before doing any redirect.
1477 * @param string $param the name of the parameter to make sure is not in the
1478 * page URL.
1480 public function ensure_param_not_in_url($param) {
1481 $this->_url->remove_params($param);
1485 * Sets an alternative version of this page.
1487 * There can be alternate versions of some pages (for example an RSS feed version).
1488 * Call this method for each alternative version available.
1489 * For each alternative version a link will be included in the <head> tag.
1491 * @param string $title The title to give the alternate version.
1492 * @param string|moodle_url $url The URL of the alternate version.
1493 * @param string $mimetype The mime-type of the alternate version.
1494 * @throws coding_exception
1496 public function add_alternate_version($title, $url, $mimetype) {
1497 if ($this->_state > self::STATE_BEFORE_HEADER) {
1498 throw new coding_exception('Cannot call moodle_page::add_alternate_version after output has been started.');
1500 $alt = new stdClass;
1501 $alt->title = $title;
1502 $alt->url = $url;
1503 $this->_alternateversions[$mimetype] = $alt;
1507 * Specify a form control should be focused when the page has loaded.
1509 * @param string $controlid the id of the HTML element to be focused.
1511 public function set_focuscontrol($controlid) {
1512 $this->_focuscontrol = $controlid;
1516 * Specify a fragment of HTML that goes where the 'Turn editing on' button normally goes.
1518 * @param string $html the HTML to display there.
1520 public function set_button($html) {
1521 $this->_button = $html;
1525 * Set the capability that allows users to edit blocks on this page.
1527 * Normally the default of 'moodle/site:manageblocks' is used, but a few
1528 * pages like the My Moodle page need to use a different capability
1529 * like 'moodle/my:manageblocks'.
1531 * @param string $capability a capability.
1533 public function set_blocks_editing_capability($capability) {
1534 $this->_blockseditingcap = $capability;
1538 * Some pages let you turn editing on for reasons other than editing blocks.
1539 * If that is the case, you can pass other capabilities that let the user
1540 * edit this page here.
1542 * @param string|array $capability either a capability, or an array of capabilities.
1544 public function set_other_editing_capability($capability) {
1545 if (is_array($capability)) {
1546 $this->_othereditingcaps = array_unique($this->_othereditingcaps + $capability);
1547 } else {
1548 $this->_othereditingcaps[] = $capability;
1553 * Sets whether the browser should cache this page or not.
1555 * @param bool $cacheable can this page be cached by the user's browser.
1557 public function set_cacheable($cacheable) {
1558 $this->_cacheable = $cacheable;
1562 * Sets the page to periodically refresh
1564 * This function must be called before $OUTPUT->header has been called or
1565 * a coding exception will be thrown.
1567 * @param int $delay Sets the delay before refreshing the page, if set to null refresh is cancelled.
1568 * @throws coding_exception
1570 public function set_periodic_refresh_delay($delay = null) {
1571 if ($this->_state > self::STATE_BEFORE_HEADER) {
1572 throw new coding_exception('You cannot set a periodic refresh delay after the header has been printed');
1574 if ($delay === null) {
1575 $this->_periodicrefreshdelay = null;
1576 } else if (is_int($delay)) {
1577 $this->_periodicrefreshdelay = $delay;
1582 * Force this page to use a particular theme.
1584 * Please use this cautiously.
1585 * It is only intended to be used by the themes selector admin page.
1587 * @param string $themename the name of the theme to use.
1589 public function force_theme($themename) {
1590 $this->ensure_theme_not_set();
1591 $this->_theme = theme_config::load($themename);
1595 * Reload theme settings.
1597 * This is used when we need to reset settings
1598 * because they are now double cached in theme.
1600 public function reload_theme() {
1601 if (!is_null($this->_theme)) {
1602 $this->_theme = theme_config::load($this->_theme->name);
1607 * Remove access to editing/moving on all blocks on a page.
1608 * This overrides any capabilities and is intended only for pages where no user (including admins) should be able to
1609 * modify blocks on the page (eg My Courses).
1611 * @return void
1613 public function force_lock_all_blocks(): void {
1614 $this->_forcelockallblocks = true;
1618 * @deprecated since Moodle 3.4
1620 public function https_required() {
1621 throw new coding_exception('https_required() cannot be used anymore.');
1625 * @deprecated since Moodle 3.4
1627 public function verify_https_required() {
1628 throw new coding_exception('verify_https_required() cannot be used anymore.');
1631 // Initialisation methods =====================================================
1632 // These set various things up in a default way.
1635 * This method is called when the page first moves out of the STATE_BEFORE_HEADER
1636 * state. This is our last change to initialise things.
1638 protected function starting_output() {
1639 global $CFG;
1641 if (!during_initial_install()) {
1642 $this->blocks->load_blocks();
1643 if (empty($this->_block_actions_done)) {
1644 $this->_block_actions_done = true;
1645 if ($this->blocks->process_url_actions($this)) {
1646 redirect($this->url->out(false));
1649 $this->blocks->create_all_block_instances();
1652 // If maintenance mode is on, change the page header.
1653 if (!empty($CFG->maintenance_enabled)) {
1654 $this->set_button('<a href="' . $CFG->wwwroot . '/' . $CFG->admin .
1655 '/settings.php?section=maintenancemode">' . get_string('maintenancemode', 'admin') .
1656 '</a> ' . $this->button);
1658 $title = $this->title;
1659 if ($title) {
1660 $title .= ' - ';
1662 $this->set_title($title . get_string('maintenancemode', 'admin'));
1665 $this->initialise_standard_body_classes();
1669 * Method for use by Moodle core to set up the theme. Do not
1670 * use this in your own code.
1672 * Make sure the right theme for this page is loaded. Tell our
1673 * blocks_manager about the theme block regions, and then, if
1674 * we are $PAGE, set up the global $OUTPUT.
1676 * @return void
1678 public function initialise_theme_and_output() {
1679 global $OUTPUT, $PAGE, $SITE, $CFG;
1681 if (!empty($this->_wherethemewasinitialised)) {
1682 return;
1685 if (!during_initial_install()) {
1686 // Detect PAGE->context mess.
1687 $this->magic_get_context();
1690 if (!$this->_course && !during_initial_install()) {
1691 $this->set_course($SITE);
1694 if (is_null($this->_theme)) {
1695 $themename = $this->resolve_theme();
1696 $this->_theme = theme_config::load($themename);
1699 $this->_theme->setup_blocks($this->pagelayout, $this->blocks);
1701 if ($this === $PAGE) {
1702 $target = null;
1703 if ($this->pagelayout === 'maintenance') {
1704 // If the page is using the maintenance layout then we're going to force target to maintenance.
1705 // This leads to a special core renderer that is designed to block access to API's that are likely unavailable for this
1706 // page layout.
1707 $target = RENDERER_TARGET_MAINTENANCE;
1709 $OUTPUT = $this->get_renderer('core', null, $target);
1712 if (!during_initial_install()) {
1713 $filtermanager = filter_manager::instance();
1714 $filtermanager->setup_page_for_globally_available_filters($this);
1717 $this->_wherethemewasinitialised = debug_backtrace();
1721 * For diagnostic/debugging purposes, find where the theme setup was triggered.
1723 * @return null|array null if theme not yet setup. Stacktrace if it was.
1725 public function get_where_theme_was_initialised() {
1726 return $this->_wherethemewasinitialised;
1730 * Reset the theme and output for a new context. This only makes sense from
1731 * external::validate_context(). Do not cheat.
1733 * @return string the name of the theme that should be used on this page.
1735 public function reset_theme_and_output() {
1736 global $COURSE, $SITE;
1738 $COURSE = clone($SITE);
1739 $this->_theme = null;
1740 $this->_wherethemewasinitialised = null;
1741 $this->_course = null;
1742 $this->_cm = null;
1743 $this->_module = null;
1744 $this->_context = null;
1748 * Work out the theme this page should use.
1750 * This depends on numerous $CFG settings, and the properties of this page.
1752 * @return string the name of the theme that should be used on this page.
1754 protected function resolve_theme() {
1755 global $CFG, $USER, $SESSION;
1757 if (empty($CFG->themeorder)) {
1758 $themeorder = array('course', 'category', 'session', 'user', 'cohort', 'site');
1759 } else {
1760 $themeorder = $CFG->themeorder;
1761 // Just in case, make sure we always use the site theme if nothing else matched.
1762 $themeorder[] = 'site';
1765 $mnetpeertheme = '';
1766 $mnetvarsok = isset($CFG->mnet_localhost_id) && isset($USER->mnethostid);
1767 if (isloggedin() and $mnetvarsok and $USER->mnethostid != $CFG->mnet_localhost_id) {
1768 require_once($CFG->dirroot.'/mnet/peer.php');
1769 $mnetpeer = new mnet_peer();
1770 $mnetpeer->set_id($USER->mnethostid);
1771 if ($mnetpeer->force_theme == 1 && $mnetpeer->theme != '') {
1772 $mnetpeertheme = $mnetpeer->theme;
1776 $devicetheme = core_useragent::get_device_type_theme($this->devicetypeinuse);
1778 // The user is using another device than default, and we have a theme for that, we should use it.
1779 $hascustomdevicetheme = core_useragent::DEVICETYPE_DEFAULT != $this->devicetypeinuse && !empty($devicetheme);
1781 foreach ($themeorder as $themetype) {
1783 switch ($themetype) {
1784 case 'course':
1785 if (!empty($CFG->allowcoursethemes) && !empty($this->_course->theme) && !$hascustomdevicetheme) {
1786 return $this->_course->theme;
1788 break;
1790 case 'category':
1791 if (!empty($CFG->allowcategorythemes) && !$hascustomdevicetheme) {
1792 $categories = $this->categories;
1793 foreach ($categories as $category) {
1794 if (!empty($category->theme)) {
1795 return $category->theme;
1799 break;
1801 case 'session':
1802 if (!empty($SESSION->theme)) {
1803 return $SESSION->theme;
1805 break;
1807 case 'user':
1808 if (!empty($CFG->allowuserthemes) && !empty($USER->theme) && !$hascustomdevicetheme) {
1809 if ($mnetpeertheme) {
1810 return $mnetpeertheme;
1811 } else {
1812 return $USER->theme;
1815 break;
1817 case 'cohort':
1818 if (!empty($CFG->allowcohortthemes) && !empty($USER->cohorttheme) && !$hascustomdevicetheme) {
1819 return $USER->cohorttheme;
1821 break;
1823 case 'site':
1824 if ($mnetpeertheme) {
1825 return $mnetpeertheme;
1827 // First try for the device the user is using.
1828 if (!empty($devicetheme)) {
1829 return $devicetheme;
1831 // Next try for the default device (as a fallback).
1832 $devicetheme = core_useragent::get_device_type_theme(core_useragent::DEVICETYPE_DEFAULT);
1833 if (!empty($devicetheme)) {
1834 return $devicetheme;
1836 // The default device theme isn't set up - use the overall default theme.
1837 return theme_config::DEFAULT_THEME;
1841 // We should most certainly have resolved a theme by now. Something has gone wrong.
1842 debugging('Error resolving the theme to use for this page.', DEBUG_DEVELOPER);
1843 return theme_config::DEFAULT_THEME;
1848 * Sets ->pagetype from the script name. For example, if the script that was
1849 * run is mod/quiz/view.php, ->pagetype will be set to 'mod-quiz-view'.
1851 * @param string $script the path to the script that should be used to
1852 * initialise ->pagetype. If not passed the $SCRIPT global will be used.
1853 * If legacy code has set $CFG->pagepath that will be used instead, and a
1854 * developer warning issued.
1856 protected function initialise_default_pagetype($script = null) {
1857 global $CFG, $SCRIPT;
1859 if (isset($CFG->pagepath)) {
1860 debugging('Some code appears to have set $CFG->pagepath. That was a horrible deprecated thing. ' .
1861 'Don\'t do it! Try calling $PAGE->set_pagetype() instead.');
1862 $script = $CFG->pagepath;
1863 unset($CFG->pagepath);
1866 if (is_null($script)) {
1867 $script = ltrim($SCRIPT, '/');
1868 $len = strlen($CFG->admin);
1869 if (substr($script, 0, $len) == $CFG->admin) {
1870 $script = 'admin' . substr($script, $len);
1874 $path = str_replace('.php', '', $script);
1875 if (substr($path, -1) == '/') {
1876 $path .= 'index';
1879 if (empty($path) || $path == 'index') {
1880 $this->_pagetype = 'site-index';
1881 } else {
1882 $this->_pagetype = str_replace('/', '-', $path);
1887 * Initialises the CSS classes that will be added to body tag of the page.
1889 * The function is responsible for adding all of the critical CSS classes
1890 * that describe the current page, and its state.
1891 * This includes classes that describe the following for example:
1892 * - Current language
1893 * - Language direction
1894 * - YUI CSS initialisation
1895 * - Pagelayout
1896 * These are commonly used in CSS to target specific types of pages.
1898 protected function initialise_standard_body_classes() {
1899 global $CFG, $USER;
1901 $pagetype = $this->pagetype;
1902 if ($pagetype == 'site-index') {
1903 $this->_legacyclass = 'course';
1904 } else if (substr($pagetype, 0, 6) == 'admin-') {
1905 $this->_legacyclass = 'admin';
1907 $this->add_body_class($this->_legacyclass);
1909 $pathbits = explode('-', trim($pagetype));
1910 for ($i = 1; $i < count($pathbits); $i++) {
1911 $this->add_body_class('path-' . join('-', array_slice($pathbits, 0, $i)));
1914 $this->add_body_classes(core_useragent::get_browser_version_classes());
1915 $this->add_body_class('dir-' . get_string('thisdirection', 'langconfig'));
1916 $this->add_body_class('lang-' . current_language());
1917 $this->add_body_class('yui-skin-sam'); // Make YUI happy, if it is used.
1918 $this->add_body_class('yui3-skin-sam'); // Make YUI3 happy, if it is used.
1919 $this->add_body_class($this->url_to_class_name($CFG->wwwroot));
1921 // Extra class describing current page layout.
1922 $this->add_body_class('pagelayout-' . $this->_pagelayout);
1924 if (!during_initial_install()) {
1925 $this->add_body_class('course-' . $this->_course->id);
1926 $this->add_body_class('context-' . $this->_context->id);
1929 if (!empty($this->_cm)) {
1930 $this->add_body_class('cmid-' . $this->_cm->id);
1933 if (!empty($CFG->allowcategorythemes)) {
1934 $this->ensure_category_loaded();
1935 foreach ($this->_categories as $catid => $notused) {
1936 $this->add_body_class('category-' . $catid);
1938 } else {
1939 $catid = 0;
1940 if (is_array($this->_categories)) {
1941 $catids = array_keys($this->_categories);
1942 $catid = reset($catids);
1943 } else if (!empty($this->_course->category)) {
1944 $catid = $this->_course->category;
1946 if ($catid) {
1947 $this->add_body_class('category-' . $catid);
1951 if (!isloggedin()) {
1952 $this->add_body_class('notloggedin');
1955 if ($this->user_is_editing()) {
1956 $this->add_body_class('editing');
1957 if (optional_param('bui_moveid', false, PARAM_INT)) {
1958 $this->add_body_class('blocks-moving');
1962 if (!empty($CFG->blocksdrag)) {
1963 $this->add_body_class('drag');
1966 if ($this->_devicetypeinuse != 'default') {
1967 $this->add_body_class($this->_devicetypeinuse . 'theme');
1970 // Add class for behat site to apply behat related fixes.
1971 if (defined('BEHAT_SITE_RUNNING')) {
1972 $this->add_body_class('behat-site');
1977 * Loads the activity record for the current CM object associated with this
1978 * page.
1980 * This will load {@link moodle_page::$_module} with a row from the related
1981 * module table in the database.
1982 * For instance if {@link moodle_page::$_cm} is a forum then a row from the
1983 * forum table will be loaded.
1985 protected function load_activity_record() {
1986 global $DB;
1987 if (is_null($this->_cm)) {
1988 return;
1990 $this->_module = $DB->get_record($this->_cm->modname, array('id' => $this->_cm->instance));
1994 * This function ensures that the category of the current course has been
1995 * loaded, and if not, the function loads it now.
1997 * @return void
1998 * @throws coding_exception
2000 protected function ensure_category_loaded() {
2001 if (is_array($this->_categories)) {
2002 return; // Already done.
2004 if (is_null($this->_course)) {
2005 throw new coding_exception('Attempt to get the course category for this page before the course was set.');
2007 if ($this->_course->category == 0) {
2008 $this->_categories = array();
2009 } else {
2010 $this->load_category($this->_course->category);
2015 * Loads the requested category into the pages categories array.
2017 * @param int $categoryid
2018 * @throws moodle_exception
2020 protected function load_category($categoryid) {
2021 global $DB;
2022 $category = $DB->get_record('course_categories', array('id' => $categoryid));
2023 if (!$category) {
2024 throw new moodle_exception('unknowncategory');
2026 $this->_categories[$category->id] = $category;
2027 $parentcategoryids = explode('/', trim($category->path, '/'));
2028 array_pop($parentcategoryids);
2029 foreach (array_reverse($parentcategoryids) as $catid) {
2030 $this->_categories[$catid] = null;
2035 * Ensures that the category the current course is within, as well as all of
2036 * its parent categories, have been loaded.
2038 * @return void
2040 protected function ensure_categories_loaded() {
2041 global $DB;
2042 $this->ensure_category_loaded();
2043 if (!is_null(end($this->_categories))) {
2044 return; // Already done.
2046 $idstoload = array_keys($this->_categories);
2047 array_shift($idstoload);
2048 $categories = $DB->get_records_list('course_categories', 'id', $idstoload);
2049 foreach ($idstoload as $catid) {
2050 $this->_categories[$catid] = $categories[$catid];
2055 * Ensure the theme has not been loaded yet. If it has an exception is thrown.
2057 * @throws coding_exception
2059 protected function ensure_theme_not_set() {
2060 // This is explicitly allowed for webservices though which may process many course contexts in a single request.
2061 if (WS_SERVER) {
2062 return;
2065 if (!is_null($this->_theme)) {
2066 throw new coding_exception('The theme has already been set up for this page ready for output. ' .
2067 'Therefore, you can no longer change the theme, or anything that might affect what ' .
2068 'the current theme is, for example, the course.',
2069 'Stack trace when the theme was set up: ' . format_backtrace($this->_wherethemewasinitialised));
2074 * Converts the provided URL into a CSS class that be used within the page.
2075 * This is primarily used to add the wwwroot to the body tag as a CSS class.
2077 * @param string $url
2078 * @return string
2080 protected function url_to_class_name($url) {
2081 $bits = parse_url($url);
2082 $class = str_replace('.', '-', $bits['host']);
2083 if (!empty($bits['port'])) {
2084 $class .= '--' . $bits['port'];
2086 if (!empty($bits['path'])) {
2087 $path = trim($bits['path'], '/');
2088 if ($path) {
2089 $class .= '--' . str_replace('/', '-', $path);
2092 return $class;
2096 * Combines all of the required editing caps for the page and returns them
2097 * as an array.
2099 * @return array
2101 protected function all_editing_caps() {
2102 $caps = $this->_othereditingcaps;
2103 $caps[] = $this->_blockseditingcap;
2104 return $caps;
2108 * Returns true if the page URL has beem set.
2110 * @return bool
2112 public function has_set_url() {
2113 return ($this->_url!==null);
2117 * Gets set when the block actions for the page have been processed.
2119 * @param bool $setting
2121 public function set_block_actions_done($setting = true) {
2122 $this->_block_actions_done = $setting;
2126 * Are popup notifications allowed on this page?
2127 * Popup notifications may be disallowed in situations such as while upgrading or completing a quiz
2129 * @return bool true if popup notifications may be displayed
2131 public function get_popup_notification_allowed() {
2132 return $this->_popup_notification_allowed;
2136 * Allow or disallow popup notifications on this page. Popups are allowed by default.
2138 * @param bool $allowed true if notifications are allowed. False if not allowed. They are allowed by default.
2140 public function set_popup_notification_allowed($allowed) {
2141 $this->_popup_notification_allowed = $allowed;
2145 * Returns the block region having made any required theme manipulations.
2147 * @since Moodle 2.5.1 2.6
2148 * @param string $region
2149 * @return string
2151 public function apply_theme_region_manipulations($region) {
2152 if ($this->blockmanipulations && isset($this->blockmanipulations[$region])) {
2153 $regionwas = $region;
2154 $regionnow = $this->blockmanipulations[$region];
2155 if ($this->blocks->is_known_region($regionwas) && $this->blocks->is_known_region($regionnow)) {
2156 // Both the before and after regions are known so we can swap them over.
2157 return $regionnow;
2159 // We didn't know about both, we won't swap them over.
2160 return $regionwas;
2162 return $region;
2166 * Add a report node and a specific report to the navigation.
2168 * @param int $userid The user ID that we are looking to add this report node to.
2169 * @param array $nodeinfo Name and url of the final node that we are creating.
2171 public function add_report_nodes($userid, $nodeinfo) {
2172 global $USER;
2173 // Try to find the specific user node.
2174 $newusernode = $this->navigation->find('user' . $userid, null);
2175 $reportnode = null;
2176 $navigationnodeerror =
2177 'Could not find the navigation node requested. Please check that the node you are looking for exists.';
2178 if ($userid != $USER->id || $this->context->contextlevel == CONTEXT_COURSE) {
2179 // Within a course context we need to properly indicate how we have come to the page,
2180 // regardless of whether it's currently logged in user or not.
2181 // Check that we have a valid node.
2182 if (empty($newusernode)) {
2183 // Throw an error if we ever reach here.
2184 throw new coding_exception($navigationnodeerror);
2186 // Add 'Reports' to the user node.
2187 $reportnode = $newusernode->add(get_string('reports'));
2188 } else {
2189 // We are looking at our own profile.
2190 $myprofilenode = $this->settingsnav->find('myprofile', null);
2191 // Check that we do end up with a valid node.
2192 if (empty($myprofilenode)) {
2193 // Throw an error if we ever reach here.
2194 throw new coding_exception($navigationnodeerror);
2196 // Add 'Reports' to our node.
2197 $reportnode = $myprofilenode->add(get_string('reports'));
2199 // Finally add the report to the navigation tree.
2200 $reportnode->add($nodeinfo['name'], $nodeinfo['url'], navigation_node::TYPE_CUSTOM, null, null,
2201 new pix_icon('i/report', $nodeinfo['name']));
2205 * Add some HTML to the list of actions to render in the header actions menu.
2207 * @param string $html The HTML to add.
2209 public function add_header_action(string $html) : void {
2210 $this->_headeractions[] = $html;
2214 * Get the list of HTML for actions to render in the header actions menu.
2216 * @return string[]
2218 public function get_header_actions() : array {
2219 return $this->_headeractions;
2223 * Set the flag to indicate if the region main settings should be rendered as an action
2224 * in the header actions menu rather than at the top of the content.
2226 * @param bool $value If the settings should be in the header.
2228 public function set_include_region_main_settings_in_header_actions(bool $value) : void {
2229 $this->_regionmainsettingsinheader = $value;
2233 * Check if the region main settings should be rendered as an action in the header actions
2234 * menu rather than at the top of the content.
2236 * @return bool
2238 public function include_region_main_settings_in_header_actions() : bool {
2239 return $this->_regionmainsettingsinheader;
2243 * Set the flag to indicate if the secondary navigation should be rendered.
2245 * @param bool $hassecondarynavigation If the secondary navigation should be rendered.
2246 * @param bool $istablist When true, the navigation bar should be rendered and behave with a tablist ARIA role.
2247 * If false, it's rendered with a menubar ARIA role. Defaults to false.
2249 public function set_secondary_navigation(bool $hassecondarynavigation, bool $istablist = false): void {
2250 $this->_hassecondarynavigation = $hassecondarynavigation;
2251 $this->_hastablistsecondarynavigation = $istablist;
2255 * Check if the secondary navigation should be rendered.
2257 * @return bool
2259 public function has_secondary_navigation(): bool {
2260 return $this->_hassecondarynavigation;
2264 * Check if the secondary navigation should be rendered with a tablist as opposed to a menubar.
2266 * @return bool
2268 public function has_tablist_secondary_navigation(): bool {
2269 return $this->_hastablistsecondarynavigation;
2273 * Set the key of the secondary nav node to be activated.
2275 * @param string $navkey the key of the secondary nav node to be activated.
2277 public function set_secondary_active_tab(string $navkey) : void {
2278 $this->_activekeysecondary = $navkey;
2282 * The key of secondary nav node to activate.
2284 * @return string|null get the key of the secondary node to activate.
2286 public function get_secondary_active_tab(): ?string {
2287 return $this->_activekeysecondary;
2291 * Set the key of the primary nav node to be activated.
2293 * @param string $navkey
2295 public function set_primary_active_tab(string $navkey): void {
2296 $this->_activenodeprimary = $navkey;
2300 * The key of the primary nav node to activate.
2302 * @return string|null get the key of the primary nav node to activate.
2304 public function get_primary_activate_tab(): ?string {
2305 return $this->_activenodeprimary;
2309 * Sets the navigation overflow state. This allows developers to turn off the overflow menu if they perhaps are using
2310 * some other navigation to show settings.
2312 * @param bool $state The state of whether to show the navigation overflow.
2314 public function set_navigation_overflow_state(bool $state): void {
2315 $this->_navigationoverflow = $state;
2319 * Gets the navigation overflow state.
2321 * @return bool The navigation overflow state.
2323 public function get_navigation_overflow_state(): bool {
2324 return $this->_navigationoverflow;