2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
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.
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();
31 * $PAGE is a central store of information about the current page we are
32 * generating in response to the user's request.
34 * It does not do very much itself
35 * except keep track of information, however, it serves as the access point to
36 * some more significant components like $PAGE->theme, $PAGE->requires,
39 * @copyright 2009 Tim Hunt
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
45 * The following properties are alphabetical. Please keep it that way so that its
48 * @property-read string $activityname The type of activity we are in, for example 'forum' or 'quiz'.
49 * Will be null if this page is not within a module.
50 * @property-read stdClass $activityrecord The row from the activities own database table (for example
51 * the forum or quiz table) that this page belongs to. Will be null
52 * if this page is not within a module.
53 * @property-read array $alternativeversions Mime type => object with ->url and ->title.
54 * @property-read block_manager $blocks The blocks manager object for this page.
55 * @property-read array $blockmanipulations
56 * @property-read string $bodyclasses A string to use within the class attribute on the body tag.
57 * @property-read string $bodyid A string to use as the id of the body tag.
58 * @property-read string $button The HTML to go where the Turn editing on button normally goes.
59 * @property-read bool $cacheable Defaults to true. Set to false to stop the page being cached at all.
60 * @property-read array $categories An array of all the categories the page course belongs to,
61 * starting with the immediately containing category, and working out to
62 * the top-level category. This may be the empty array if we are in the
64 * @property-read mixed $category The category that the page course belongs to.
65 * @property-read cm_info $cm The course_module that this page belongs to. Will be null
66 * if this page is not within a module. This is a full cm object, as loaded
67 * by get_coursemodule_from_id or get_coursemodule_from_instance,
68 * so the extra modname and name fields are present.
69 * @property-read context $context The main context to which this page belongs.
70 * @property-read stdClass $course The current course that we are inside - a row from the
71 * course table. (Also available as $COURSE global.) If we are not inside
72 * an actual course, this will be the site course.
73 * @property-read string $devicetypeinuse The name of the device type in use
74 * @property-read string $docspath The path to the Moodle docs for this page.
75 * @property-read string $focuscontrol The id of the HTML element to be focused when the page has loaded.
76 * @property-read bool $headerprinted True if the page header has already been printed.
77 * @property-read string $heading The main heading that should be displayed at the top of the <body>.
78 * @property-read string $headingmenu The menu (or actions) to display in the heading
79 * @property-read array $layout_options An arrays with options for the layout file.
80 * @property-read array $legacythemeinuse True if the legacy browser theme is in use.
81 * @property-read navbar $navbar The navbar object used to display the navbar
82 * @property-read global_navigation $navigation The navigation structure for this page.
83 * @property-read xhtml_container_stack $opencontainers Tracks XHTML tags on this page that have been opened but not closed.
84 * mainly for internal use by the rendering code.
85 * @property-read string $pagelayout The general type of page this is. For example 'normal', 'popup', 'home'.
86 * Allows the theme to display things differently, if it wishes to.
87 * @property-read string $pagetype The page type string, should be used as the id for the body tag in the theme.
88 * @property-read int $periodicrefreshdelay The periodic refresh delay to use with meta refresh
89 * @property-read page_requirements_manager $requires Tracks the JavaScript, CSS files, etc. required by this page.
90 * @property-read string $requestip The IP address of the current request, null if unknown.
91 * @property-read string $requestorigin The type of request 'web', 'ws', 'cli', 'restore', etc.
92 * @property-read settings_navigation $settingsnav The settings navigation
93 * @property-read int $state One of the STATE_... constants
94 * @property-read string $subpage The subpage identifier, if any.
95 * @property-read theme_config $theme The theme for this page.
96 * @property-read string $title The title that should go in the <head> section of the HTML of this page.
97 * @property-read moodle_url $url The moodle url object for this page.
101 /** The state of the page before it has printed the header **/
102 const STATE_BEFORE_HEADER
= 0;
104 /** The state the page is in temporarily while the header is being printed **/
105 const STATE_PRINTING_HEADER
= 1;
107 /** The state the page is in while content is presumably being printed **/
108 const STATE_IN_BODY
= 2;
111 * The state the page is when the footer has been printed and its function is
114 const STATE_DONE
= 3;
117 * @var int The current state of the page. The state a page is within
118 * determines what actions are possible for it.
120 protected $_state = self
::STATE_BEFORE_HEADER
;
123 * @var stdClass The course currently associated with this page.
124 * If not has been provided the front page course is used.
126 protected $_course = null;
129 * @var cm_info If this page belongs to a module, this is the cm_info module
130 * description object.
132 protected $_cm = null;
135 * @var stdClass If $_cm is not null, then this will hold the corresponding
136 * row from the modname table. For example, if $_cm->modname is 'quiz', this
137 * will be a row from the quiz table.
139 protected $_module = null;
142 * @var context The context that this page belongs to.
144 protected $_context = null;
147 * @var array This holds any categories that $_course belongs to, starting with the
148 * particular category it belongs to, and working out through any parent
149 * categories to the top level. These are loaded progressively, if needed.
150 * There are three states. $_categories = null initially when nothing is
151 * loaded; $_categories = array($id => $cat, $parentid => null) when we have
152 * loaded $_course->category, but not any parents; and a complete array once
153 * everything is loaded.
155 protected $_categories = null;
158 * @var array An array of CSS classes that should be added to the body tag in HTML.
160 protected $_bodyclasses = array();
163 * @var string The title for the page. Used within the title tag in the HTML head.
165 protected $_title = '';
168 * @var string The string to use as the heading of the page. Shown near the top of the
169 * page within most themes.
171 protected $_heading = '';
174 * @var string The pagetype is used to describe the page and defaults to a representation
175 * of the physical path to the page e.g. my-index, mod-quiz-attempt
177 protected $_pagetype = null;
180 * @var string The pagelayout to use when displaying this page. The
181 * pagelayout needs to have been defined by the theme in use, or one of its
182 * parents. By default base is used however standard is the more common layout.
183 * Note that this gets automatically set by core during operations like
186 protected $_pagelayout = 'base';
189 * @var array List of theme layout options, these are ignored by core.
190 * To be used in individual theme layout files only.
192 protected $_layout_options = null;
195 * @var string An optional arbitrary parameter that can be set on pages where the context
196 * and pagetype is not enough to identify the page.
198 protected $_subpage = '';
201 * @var string Set a different path to use for the 'Moodle docs for this page' link.
202 * By default, it uses the path of the file for instance mod/quiz/attempt.
204 protected $_docspath = null;
207 * @var string A legacy class that will be added to the body tag
209 protected $_legacyclass = null;
212 * @var moodle_url The URL for this page. This is mandatory and must be set
213 * before output is started.
215 protected $_url = null;
218 * @var array An array of links to alternative versions of this page.
219 * Primarily used for RSS versions of the current page.
221 protected $_alternateversions = array();
224 * @var block_manager The blocks manager for this page. It is responsible for
225 * the blocks and there content on this page.
227 protected $_blocks = null;
230 * @var page_requirements_manager Page requirements manager. It is responsible
231 * for all JavaScript and CSS resources required by this page.
233 protected $_requires = null;
236 * @var string The capability required by the user in order to edit blocks
237 * and block settings on this page.
239 protected $_blockseditingcap = 'moodle/site:manageblocks';
242 * @var bool An internal flag to record when block actions have been processed.
243 * Remember block actions occur on the current URL and it is important that
244 * even they are never executed more than once.
246 protected $_block_actions_done = false;
249 * @var array An array of any other capabilities the current user must have
250 * in order to editing the page and/or its content (not just blocks).
252 protected $_othereditingcaps = array();
255 * @var bool Sets whether this page should be cached by the browser or not.
256 * If it is set to true (default) the page is served with caching headers.
258 protected $_cacheable = true;
261 * @var string Can be set to the ID of an element on the page, if done that
262 * element receives focus when the page loads.
264 protected $_focuscontrol = '';
267 * @var string HTML to go where the turn on editing button is located. This
268 * is nearly a legacy item and not used very often any more.
270 protected $_button = '';
273 * @var theme_config The theme to use with this page. This has to be properly
274 * initialised via {@link moodle_page::initialise_theme_and_output()} which
275 * happens magically before any operation that requires it.
277 protected $_theme = null;
280 * @var global_navigation Contains the global navigation structure.
282 protected $_navigation = null;
285 * @var settings_navigation Contains the settings navigation structure.
287 protected $_settingsnav = null;
290 * @var flat_navigation Contains a list of nav nodes, most closely related to the current page.
292 protected $_flatnav = null;
295 * @var navbar Contains the navbar structure.
297 protected $_navbar = null;
300 * @var string The menu (or actions) to display in the heading.
302 protected $_headingmenu = null;
305 * @var array stack trace. Then the theme is initialised, we save the stack
306 * trace, for use in error messages.
308 protected $_wherethemewasinitialised = null;
311 * @var xhtml_container_stack Tracks XHTML tags on this page that have been
312 * opened but not closed.
314 protected $_opencontainers;
317 * @var int Sets the page to refresh after a given delay (in seconds) using
318 * meta refresh in {@link standard_head_html()} in outputlib.php
319 * If set to null(default) the page is not refreshed
321 protected $_periodicrefreshdelay = null;
324 * @var array Associative array of browser shortnames (as used by check_browser_version)
325 * and their minimum required versions
327 protected $_legacybrowsers = array('MSIE' => 6.0);
330 * @var string Is set to the name of the device type in use.
331 * This will we worked out when it is first used.
333 protected $_devicetypeinuse = null;
336 * @var bool Used to determine if HTTPS should be required for login.
338 protected $_https_login_required = false;
341 * @var bool Determines if popup notifications allowed on this page.
342 * Code such as the quiz module disables popup notifications in situations
343 * such as upgrading or completing a quiz.
345 protected $_popup_notification_allowed = true;
348 * @var bool Is the settings menu being forced to display on this page (activities / resources only).
349 * This is only used by themes that use the settings menu.
351 protected $_forcesettingsmenu = false;
354 * Force the settings menu to be displayed on this page. This will only force the
355 * settings menu on an activity / resource page that is being displayed on a theme that
356 * uses a settings menu.
358 * @param bool $forced default of true, can be sent false to turn off the force.
360 public function force_settings_menu($forced = true) {
361 $this->_forcesettingsmenu
= $forced;
365 * Check to see if the settings menu is forced to display on this activity / resource page.
366 * This only applies to themes that use the settings menu.
368 * @return bool True if the settings menu is forced to display.
370 public function is_settings_menu_forced() {
371 return $this->_forcesettingsmenu
;
374 // Magic getter methods =============================================================
375 // Due to the __get magic below, you normally do not call these as $PAGE->magic_get_x
376 // methods, but instead use the $PAGE->x syntax.
379 * Please do not call this method directly, use the ->state syntax. {@link moodle_page::__get()}.
380 * @return integer one of the STATE_XXX constants. You should not normally need
381 * to use this in your code. It is intended for internal use by this class
382 * and its friends like print_header, to check that everything is working as
383 * expected. Also accessible as $PAGE->state.
385 protected function magic_get_state() {
386 return $this->_state
;
390 * Please do not call this method directly, use the ->headerprinted syntax. {@link moodle_page::__get()}.
391 * @return bool has the header already been printed?
393 protected function magic_get_headerprinted() {
394 return $this->_state
>= self
::STATE_IN_BODY
;
398 * Please do not call this method directly, use the ->course syntax. {@link moodle_page::__get()}.
399 * @return stdClass the current course that we are inside - a row from the
400 * course table. (Also available as $COURSE global.) If we are not inside
401 * an actual course, this will be the site course.
403 protected function magic_get_course() {
405 if (is_null($this->_course
)) {
408 return $this->_course
;
412 * Please do not call this method directly, use the ->cm syntax. {@link moodle_page::__get()}.
413 * @return cm_info the course_module that this page belongs to. Will be null
414 * if this page is not within a module. This is a full cm object, as loaded
415 * by get_coursemodule_from_id or get_coursemodule_from_instance,
416 * so the extra modname and name fields are present.
418 protected function magic_get_cm() {
423 * Please do not call this method directly, use the ->activityrecord syntax. {@link moodle_page::__get()}.
424 * @return stdClass the row from the activities own database table (for example
425 * the forum or quiz table) that this page belongs to. Will be null
426 * if this page is not within a module.
428 protected function magic_get_activityrecord() {
429 if (is_null($this->_module
) && !is_null($this->_cm
)) {
430 $this->load_activity_record();
432 return $this->_module
;
436 * Please do not call this method directly, use the ->activityname syntax. {@link moodle_page::__get()}.
437 * @return string the The type of activity we are in, for example 'forum' or 'quiz'.
438 * Will be null if this page is not within a module.
440 protected function magic_get_activityname() {
441 if (is_null($this->_cm
)) {
444 return $this->_cm
->modname
;
448 * Please do not call this method directly, use the ->category syntax. {@link moodle_page::__get()}.
449 * @return stdClass the category that the page course belongs to. If there isn't one
450 * (that is, if this is the front page course) returns null.
452 protected function magic_get_category() {
453 $this->ensure_category_loaded();
454 if (!empty($this->_categories
)) {
455 return reset($this->_categories
);
462 * Please do not call this method directly, use the ->categories syntax. {@link moodle_page::__get()}.
463 * @return array an array of all the categories the page course belongs to,
464 * starting with the immediately containing category, and working out to
465 * the top-level category. This may be the empty array if we are in the
468 protected function magic_get_categories() {
469 $this->ensure_categories_loaded();
470 return $this->_categories
;
474 * Please do not call this method directly, use the ->context syntax. {@link moodle_page::__get()}.
475 * @return context the main context to which this page belongs.
477 protected function magic_get_context() {
479 if (is_null($this->_context
)) {
480 if (CLI_SCRIPT
or NO_MOODLE_COOKIES
) {
481 // Cli scripts work in system context, do not annoy devs with debug info.
482 // Very few scripts do not use cookies, we can safely use system as default context there.
483 } else if (AJAX_SCRIPT
&& $CFG->debugdeveloper
) {
484 // Throw exception inside AJAX script in developer mode, otherwise the debugging message may be missed.
485 throw new coding_exception('$PAGE->context was not set. You may have forgotten '
486 .'to call require_login() or $PAGE->set_context()');
488 debugging('Coding problem: $PAGE->context was not set. You may have forgotten '
489 .'to call require_login() or $PAGE->set_context(). The page may not display '
490 .'correctly as a result');
492 $this->_context
= context_system
::instance();
494 return $this->_context
;
498 * Please do not call this method directly, use the ->pagetype syntax. {@link moodle_page::__get()}.
499 * @return string e.g. 'my-index' or 'mod-quiz-attempt'.
501 protected function magic_get_pagetype() {
503 if (is_null($this->_pagetype
) ||
isset($CFG->pagepath
)) {
504 $this->initialise_default_pagetype();
506 return $this->_pagetype
;
510 * Please do not call this method directly, use the ->pagetype syntax. {@link moodle_page::__get()}.
511 * @return string The id to use on the body tag, uses {@link magic_get_pagetype()}.
513 protected function magic_get_bodyid() {
514 return 'page-'.$this->pagetype
;
518 * Please do not call this method directly, use the ->pagelayout syntax. {@link moodle_page::__get()}.
519 * @return string the general type of page this is. For example 'standard', 'popup', 'home'.
520 * Allows the theme to display things differently, if it wishes to.
522 protected function magic_get_pagelayout() {
523 return $this->_pagelayout
;
527 * Please do not call this method directly, use the ->layout_options syntax. {@link moodle_page::__get()}.
528 * @return array returns arrays with options for layout file
530 protected function magic_get_layout_options() {
531 if (!is_array($this->_layout_options
)) {
532 $this->_layout_options
= $this->_theme
->pagelayout_options($this->pagelayout
);
534 return $this->_layout_options
;
538 * Please do not call this method directly, use the ->subpage syntax. {@link moodle_page::__get()}.
539 * @return string The subpage identifier, if any.
541 protected function magic_get_subpage() {
542 return $this->_subpage
;
546 * Please do not call this method directly, use the ->bodyclasses syntax. {@link moodle_page::__get()}.
547 * @return string the class names to put on the body element in the HTML.
549 protected function magic_get_bodyclasses() {
550 return implode(' ', array_keys($this->_bodyclasses
));
554 * Please do not call this method directly, use the ->title syntax. {@link moodle_page::__get()}.
555 * @return string the title that should go in the <head> section of the HTML of this page.
557 protected function magic_get_title() {
558 return $this->_title
;
562 * Please do not call this method directly, use the ->heading syntax. {@link moodle_page::__get()}.
563 * @return string the main heading that should be displayed at the top of the <body>.
565 protected function magic_get_heading() {
566 return $this->_heading
;
570 * Please do not call this method directly, use the ->heading syntax. {@link moodle_page::__get()}.
571 * @return string The menu (or actions) to display in the heading
573 protected function magic_get_headingmenu() {
574 return $this->_headingmenu
;
578 * Please do not call this method directly, use the ->docspath syntax. {@link moodle_page::__get()}.
579 * @return string the path to the Moodle docs for this page.
581 protected function magic_get_docspath() {
582 if (is_string($this->_docspath
)) {
583 return $this->_docspath
;
585 return str_replace('-', '/', $this->pagetype
);
590 * Please do not call this method directly, use the ->url syntax. {@link moodle_page::__get()}.
591 * @return moodle_url the clean URL required to load the current page. (You
592 * should normally use this in preference to $ME or $FULLME.)
594 protected function magic_get_url() {
596 if (is_null($this->_url
)) {
597 debugging('This page did not call $PAGE->set_url(...). Using '.s($FULLME), DEBUG_DEVELOPER
);
598 $this->_url
= new moodle_url($FULLME);
599 // Make sure the guessed URL cannot lead to dangerous redirects.
600 $this->_url
->remove_params('sesskey');
602 return new moodle_url($this->_url
); // Return a clone for safety.
606 * The list of alternate versions of this page.
607 * @return array mime type => object with ->url and ->title.
609 protected function magic_get_alternateversions() {
610 return $this->_alternateversions
;
614 * Please do not call this method directly, use the ->blocks syntax. {@link moodle_page::__get()}.
615 * @return block_manager the blocks manager object for this page.
617 protected function magic_get_blocks() {
619 if (is_null($this->_blocks
)) {
620 if (!empty($CFG->blockmanagerclass
)) {
621 if (!empty($CFG->blockmanagerclassfile
)) {
622 require_once($CFG->blockmanagerclassfile
);
624 $classname = $CFG->blockmanagerclass
;
626 $classname = 'block_manager';
628 $this->_blocks
= new $classname($this);
630 return $this->_blocks
;
634 * Please do not call this method directly, use the ->requires syntax. {@link moodle_page::__get()}.
635 * @return page_requirements_manager tracks the JavaScript, CSS files, etc. required by this page.
637 protected function magic_get_requires() {
638 if (is_null($this->_requires
)) {
639 $this->_requires
= new page_requirements_manager();
641 return $this->_requires
;
645 * Please do not call this method directly, use the ->cacheable syntax. {@link moodle_page::__get()}.
646 * @return bool can this page be cached by the user's browser.
648 protected function magic_get_cacheable() {
649 return $this->_cacheable
;
653 * Please do not call this method directly, use the ->focuscontrol syntax. {@link moodle_page::__get()}.
654 * @return string the id of the HTML element to be focused when the page has loaded.
656 protected function magic_get_focuscontrol() {
657 return $this->_focuscontrol
;
661 * Please do not call this method directly, use the ->button syntax. {@link moodle_page::__get()}.
662 * @return string the HTML to go where the Turn editing on button normally goes.
664 protected function magic_get_button() {
665 return $this->_button
;
669 * Please do not call this method directly, use the ->theme syntax. {@link moodle_page::__get()}.
670 * @return theme_config the initialised theme for this page.
672 protected function magic_get_theme() {
673 if (is_null($this->_theme
)) {
674 $this->initialise_theme_and_output();
676 return $this->_theme
;
680 * Returns an array of minipulations or false if there are none to make.
682 * @since Moodle 2.5.1 2.6
685 protected function magic_get_blockmanipulations() {
686 if (!right_to_left()) {
689 if (is_null($this->_theme
)) {
690 $this->initialise_theme_and_output();
692 return $this->_theme
->blockrtlmanipulations
;
696 * Please do not call this method directly, use the ->devicetypeinuse syntax. {@link moodle_page::__get()}.
697 * @return string The device type being used.
699 protected function magic_get_devicetypeinuse() {
700 if (empty($this->_devicetypeinuse
)) {
701 $this->_devicetypeinuse
= core_useragent
::get_user_device_type();
703 return $this->_devicetypeinuse
;
707 * Please do not call this method directly use the ->periodicrefreshdelay syntax
708 * {@link moodle_page::__get()}
709 * @return int The periodic refresh delay to use with meta refresh
711 protected function magic_get_periodicrefreshdelay() {
712 return $this->_periodicrefreshdelay
;
716 * Please do not call this method directly use the ->opencontainers syntax. {@link moodle_page::__get()}
717 * @return xhtml_container_stack tracks XHTML tags on this page that have been opened but not closed.
718 * mainly for internal use by the rendering code.
720 protected function magic_get_opencontainers() {
721 if (is_null($this->_opencontainers
)) {
722 $this->_opencontainers
= new xhtml_container_stack();
724 return $this->_opencontainers
;
728 * Return the navigation object
729 * @return global_navigation
731 protected function magic_get_navigation() {
732 if ($this->_navigation
=== null) {
733 $this->_navigation
= new global_navigation($this);
735 return $this->_navigation
;
739 * Return a navbar object
742 protected function magic_get_navbar() {
743 if ($this->_navbar
=== null) {
744 $this->_navbar
= new navbar($this);
746 return $this->_navbar
;
750 * Returns the settings navigation object
751 * @return settings_navigation
753 protected function magic_get_settingsnav() {
754 if ($this->_settingsnav
=== null) {
755 $this->_settingsnav
= new settings_navigation($this);
756 $this->_settingsnav
->initialise();
758 return $this->_settingsnav
;
762 * Returns the flat navigation object
763 * @return flat_navigation
765 protected function magic_get_flatnav() {
766 if ($this->_flatnav
=== null) {
767 $this->_flatnav
= new flat_navigation($this);
768 $this->_flatnav
->initialise();
770 return $this->_flatnav
;
774 * Returns request IP address.
776 * @return string IP address or null if unknown
778 protected function magic_get_requestip() {
779 return getremoteaddr(null);
783 * Returns the origin of current request.
785 * Note: constants are not required because we need to use these values in logging and reports.
787 * @return string 'web', 'ws', 'cli', 'restore', etc.
789 protected function magic_get_requestorigin() {
790 if (class_exists('restore_controller', false) && restore_controller
::is_executing()) {
806 * PHP overloading magic to make the $PAGE->course syntax work by redirecting
807 * it to the corresponding $PAGE->magic_get_course() method if there is one, and
808 * throwing an exception if not.
810 * @param string $name property name
812 * @throws coding_exception
814 public function __get($name) {
815 $getmethod = 'magic_get_' . $name;
816 if (method_exists($this, $getmethod)) {
817 return $this->$getmethod();
819 throw new coding_exception('Unknown property ' . $name . ' of $PAGE.');
824 * PHP overloading magic to catch obvious coding errors.
826 * This method has been created to catch obvious coding errors where the
827 * developer has tried to set a page property using $PAGE->key = $value.
828 * In the moodle_page class all properties must be set using the appropriate
829 * $PAGE->set_something($value) method.
831 * @param string $name property name
832 * @param mixed $value Value
833 * @return void Throws exception if field not defined in page class
834 * @throws coding_exception
836 public function __set($name, $value) {
837 if (method_exists($this, 'set_' . $name)) {
838 throw new coding_exception('Invalid attempt to modify page object', "Use \$PAGE->set_$name() instead.");
840 throw new coding_exception('Invalid attempt to modify page object', "Unknown property $name");
844 // Other information getting methods ==========================================.
847 * Returns instance of page renderer
849 * @param string $component name such as 'core', 'mod_forum' or 'qtype_multichoice'.
850 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
851 * @param string $target one of rendering target constants
852 * @return renderer_base
854 public function get_renderer($component, $subtype = null, $target = null) {
855 if ($this->pagelayout
=== 'maintenance') {
856 // If the page is using the maintenance layout then we're going to force target to maintenance.
857 // This leads to a special core renderer that is designed to block access to API's that are likely unavailable for this
859 $target = RENDERER_TARGET_MAINTENANCE
;
861 return $this->magic_get_theme()->get_renderer($this, $component, $subtype, $target);
865 * Checks to see if there are any items on the navbar object
867 * @return bool true if there are, false if not
869 public function has_navbar() {
870 if ($this->_navbar
=== null) {
871 $this->_navbar
= new navbar($this);
873 return $this->_navbar
->has_items();
877 * Switches from the regular requirements manager to the fragment requirements manager to
878 * capture all necessary JavaScript to display a chunk of HTML such as an mform. This is for use
879 * by the get_fragment() web service and not for use elsewhere.
881 public function start_collecting_javascript_requirements() {
883 require_once($CFG->libdir
.'/outputfragmentrequirementslib.php');
885 // Check that the requirements manager has not already been switched.
886 if (get_class($this->_requires
) == 'fragment_requirements_manager') {
887 throw new coding_exception('JavaScript collection has already been started.');
889 // The header needs to have been called to flush out the generic JavaScript for the page. This allows only
890 // JavaScript for the fragment to be collected. _wherethemewasinitialised is set when header() is called.
891 if (!empty($this->_wherethemewasinitialised
)) {
892 // Change the current requirements manager over to the fragment manager to capture JS.
893 $this->_requires
= new fragment_requirements_manager();
895 throw new coding_exception('$OUTPUT->header() needs to be called before collecting JavaScript requirements.');
900 * Should the current user see this page in editing mode.
901 * That is, are they allowed to edit this page, and are they currently in
905 public function user_is_editing() {
907 return !empty($USER->editing
) && $this->user_allowed_editing();
911 * Does the user have permission to edit blocks on this page.
914 public function user_can_edit_blocks() {
915 return has_capability($this->_blockseditingcap
, $this->_context
);
919 * Does the user have permission to see this page in editing mode.
922 public function user_allowed_editing() {
923 return has_any_capability($this->all_editing_caps(), $this->_context
);
927 * Get a description of this page. Normally displayed in the footer in developer debug mode.
930 public function debug_summary() {
932 $summary .= 'General type: ' . $this->pagelayout
. '. ';
933 if (!during_initial_install()) {
934 $summary .= 'Context ' . $this->context
->get_context_name() . ' (context id ' . $this->_context
->id
. '). ';
936 $summary .= 'Page type ' . $this->pagetype
. '. ';
937 if ($this->subpage
) {
938 $summary .= 'Sub-page ' . $this->subpage
. '. ';
943 // Setter methods =============================================================.
948 * The state must be one of that STATE_... constants, and the state is only allowed to advance one step at a time.
950 * @param int $state The new state.
951 * @throws coding_exception
953 public function set_state($state) {
954 if ($state != $this->_state +
1 ||
$state > self
::STATE_DONE
) {
955 throw new coding_exception('Invalid state passed to moodle_page::set_state. We are in state ' .
956 $this->_state
. ' and state ' . $state . ' was requested.');
959 if ($state == self
::STATE_PRINTING_HEADER
) {
960 $this->starting_output();
963 $this->_state
= $state;
967 * Set the current course. This sets both $PAGE->course and $COURSE. It also
968 * sets the right theme and locale.
970 * Normally you don't need to call this function yourself, require_login will
971 * call it for you if you pass a $course to it. You can use this function
972 * on pages that do need to call require_login().
974 * Sets $PAGE->context to the course context, if it is not already set.
976 * @param stdClass $course the course to set as the global course.
977 * @throws coding_exception
979 public function set_course($course) {
980 global $COURSE, $PAGE, $CFG, $SITE;
982 if (empty($course->id
)) {
983 throw new coding_exception('$course passed to moodle_page::set_course does not look like a proper course object.');
986 $this->ensure_theme_not_set();
988 if (!empty($this->_course
->id
) && $this->_course
->id
!= $course->id
) {
989 $this->_categories
= null;
992 $this->_course
= clone($course);
994 if ($this === $PAGE) {
995 $COURSE = $this->_course
;
999 if (!$this->_context
) {
1000 $this->set_context(context_course
::instance($this->_course
->id
));
1003 // Notify course format that this page is set for the course.
1004 if ($this->_course
->id
!= $SITE->id
) {
1005 require_once($CFG->dirroot
.'/course/lib.php');
1006 $courseformat = course_get_format($this->_course
);
1007 $this->add_body_class('format-'. $courseformat->get_format());
1008 $courseformat->page_set_course($this);
1010 $this->add_body_class('format-site');
1015 * Set the main context to which this page belongs.
1017 * @param context $context a context object. You normally get this with context_xxxx::instance().
1019 public function set_context($context) {
1020 if ($context === null) {
1021 // Extremely ugly hack which sets context to some value in order to prevent warnings,
1022 // use only for core error handling!!!!
1023 if (!$this->_context
) {
1024 $this->_context
= context_system
::instance();
1028 // Ideally we should set context only once.
1029 if (isset($this->_context
) && $context->id
!== $this->_context
->id
) {
1030 $current = $this->_context
->contextlevel
;
1031 if ($current == CONTEXT_SYSTEM
or $current == CONTEXT_COURSE
) {
1032 // Hmm - not ideal, but it might produce too many warnings due to the design of require_login.
1033 } else if ($current == CONTEXT_MODULE
and ($parentcontext = $context->get_parent_context()) and
1034 $this->_context
->id
== $parentcontext->id
) {
1035 // Hmm - most probably somebody did require_login() and after that set the block context.
1037 // We do not want devs to do weird switching of context levels on the fly because we might have used
1038 // the context already such as in text filter in page title.
1039 debugging("Coding problem: unsupported modification of PAGE->context from {$current} to {$context->contextlevel}");
1043 $this->_context
= $context;
1047 * The course module that this page belongs to (if it does belong to one).
1049 * @param stdClass|cm_info $cm a record from course_modules table or cm_info from get_fast_modinfo().
1050 * @param stdClass $course
1051 * @param stdClass $module
1053 * @throws coding_exception
1055 public function set_cm($cm, $course = null, $module = null) {
1056 global $DB, $CFG, $SITE;
1058 if (!isset($cm->id
) ||
!isset($cm->course
)) {
1059 throw new coding_exception('Invalid $cm. It has to be instance of cm_info or record from the course_modules table.');
1062 if (!$this->_course ||
$this->_course
->id
!= $cm->course
) {
1064 $course = $DB->get_record('course', array('id' => $cm->course
), '*', MUST_EXIST
);
1066 if ($course->id
!= $cm->course
) {
1067 throw new coding_exception('The course you passed to $PAGE->set_cm does not correspond to the $cm.');
1069 $this->set_course($course);
1072 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
1073 if (!($cm instanceof cm_info
)) {
1074 $modinfo = get_fast_modinfo($this->_course
);
1075 $cm = $modinfo->get_cm($cm->id
);
1079 // Unfortunately the context setting is a mess.
1080 // Let's try to work around some common block problems and show some debug messages.
1081 if (empty($this->_context
) or $this->_context
->contextlevel
!= CONTEXT_BLOCK
) {
1082 $context = context_module
::instance($cm->id
);
1083 $this->set_context($context);
1087 $this->set_activity_record($module);
1090 // Notify course format that this page is set for the course module.
1091 if ($this->_course
->id
!= $SITE->id
) {
1092 require_once($CFG->dirroot
.'/course/lib.php');
1093 course_get_format($this->_course
)->page_set_cm($this);
1098 * Sets the activity record. This could be a row from the main table for a
1099 * module. For instance if the current module (cm) is a forum this should be a row
1100 * from the forum table.
1102 * @param stdClass $module A row from the main database table for the module that this page belongs to.
1103 * @throws coding_exception
1105 public function set_activity_record($module) {
1106 if (is_null($this->_cm
)) {
1107 throw new coding_exception('You cannot call $PAGE->set_activity_record until after $PAGE->cm has been set.');
1109 if ($module->id
!= $this->_cm
->instance ||
$module->course
!= $this->_course
->id
) {
1110 throw new coding_exception('The activity record does not seem to correspond to the cm that has been set.');
1112 $this->_module
= $module;
1116 * Sets the pagetype to use for this page.
1118 * Normally you do not need to set this manually, it is automatically created
1119 * from the script name. However, on some pages this is overridden.
1120 * For example the page type for course/view.php includes the course format,
1121 * for example 'course-view-weeks'. This gets used as the id attribute on
1122 * <body> and also for determining which blocks are displayed.
1124 * @param string $pagetype e.g. 'my-index' or 'mod-quiz-attempt'.
1126 public function set_pagetype($pagetype) {
1127 $this->_pagetype
= $pagetype;
1131 * Sets the layout to use for this page.
1133 * The page layout determines how the page will be displayed, things such as
1134 * block regions, content areas, etc are controlled by the layout.
1135 * The theme in use for the page will determine that the layout contains.
1137 * This properly defaults to 'base', so you only need to call this function if
1138 * you want something different. The exact range of supported layouts is specified
1139 * in the standard theme.
1141 * For an idea of the common page layouts see
1142 * {@link http://docs.moodle.org/dev/Themes_2.0#The_different_layouts_as_of_August_17th.2C_2010}
1143 * But please keep in mind that it may be (and normally is) out of date.
1144 * The only place to find an accurate up-to-date list of the page layouts
1145 * available for your version of Moodle is {@link theme/base/config.php}
1147 * @param string $pagelayout the page layout this is. For example 'popup', 'home'.
1149 public function set_pagelayout($pagelayout) {
1152 if (!empty($SESSION->forcepagelayout
)) {
1153 $this->_pagelayout
= $SESSION->forcepagelayout
;
1155 // Uncomment this to debug theme pagelayout issues like missing blocks.
1156 // if (!empty($this->_wherethemewasinitialised) && $pagelayout != $this->_pagelayout)
1157 // debugging('Page layout has already been set and cannot be changed.', DEBUG_DEVELOPER);
1158 $this->_pagelayout
= $pagelayout;
1163 * If context->id and pagetype are not enough to uniquely identify this page,
1164 * then you can set a subpage id as well. For example, the tags page sets
1166 * @param string $subpage an arbitrary identifier that, along with context->id
1167 * and pagetype, uniquely identifies this page.
1169 public function set_subpage($subpage) {
1170 if (empty($subpage)) {
1171 $this->_subpage
= '';
1173 $this->_subpage
= $subpage;
1178 * Adds a CSS class to the body tag of the page.
1180 * @param string $class add this class name ot the class attribute on the body tag.
1181 * @throws coding_exception
1183 public function add_body_class($class) {
1184 if ($this->_state
> self
::STATE_BEFORE_HEADER
) {
1185 throw new coding_exception('Cannot call moodle_page::add_body_class after output has been started.');
1187 $this->_bodyclasses
[$class] = 1;
1191 * Adds an array of body classes to the body tag of this page.
1193 * @param array $classes this utility method calls add_body_class for each array element.
1195 public function add_body_classes($classes) {
1196 foreach ($classes as $class) {
1197 $this->add_body_class($class);
1202 * Sets the title for the page.
1203 * This is normally used within the title tag in the head of the page.
1205 * @param string $title the title that should go in the <head> section of the HTML of this page.
1207 public function set_title($title) {
1208 $title = format_string($title);
1209 $title = strip_tags($title);
1210 $title = str_replace('"', '"', $title);
1211 $this->_title
= $title;
1215 * Sets the heading to use for the page.
1216 * This is normally used as the main heading at the top of the content.
1218 * @param string $heading the main heading that should be displayed at the top of the <body>.
1220 public function set_heading($heading) {
1221 $this->_heading
= format_string($heading);
1225 * Sets some HTML to use next to the heading {@link moodle_page::set_heading()}
1227 * @param string $menu The menu/content to show in the heading
1229 public function set_headingmenu($menu) {
1230 $this->_headingmenu
= $menu;
1234 * Set the course category this page belongs to manually.
1236 * This automatically sets $PAGE->course to be the site course. You cannot
1237 * use this method if you have already set $PAGE->course - in that case,
1238 * the category must be the one that the course belongs to. This also
1239 * automatically sets the page context to the category context.
1241 * @param int $categoryid The id of the category to set.
1242 * @throws coding_exception
1244 public function set_category_by_id($categoryid) {
1246 if (!is_null($this->_course
)) {
1247 throw new coding_exception('Course has already been set. You cannot change the category now.');
1249 if (is_array($this->_categories
)) {
1250 throw new coding_exception('Course category has already been set. You cannot to change it now.');
1252 $this->ensure_theme_not_set();
1253 $this->set_course($SITE);
1254 $this->load_category($categoryid);
1255 $this->set_context(context_coursecat
::instance($categoryid));
1259 * Set a different path to use for the 'Moodle docs for this page' link.
1261 * By default, it uses the pagetype, which is normally the same as the
1262 * script name. So, for example, for mod/quiz/attempt.php, pagetype is
1263 * mod-quiz-attempt, and so docspath is mod/quiz/attempt.
1265 * @param string $path the path to use at the end of the moodle docs URL.
1267 public function set_docs_path($path) {
1268 $this->_docspath
= $path;
1272 * You should call this method from every page to set the URL that should be used to return to this page.
1274 * Used, for example, by the blocks editing UI to know where to return the
1275 * user after an action.
1276 * For example, course/view.php does:
1277 * $id = optional_param('id', 0, PARAM_INT);
1278 * $PAGE->set_url('/course/view.php', array('id' => $id));
1280 * @param moodle_url|string $url URL relative to $CFG->wwwroot or {@link moodle_url} instance
1281 * @param array $params parameters to add to the URL
1282 * @throws coding_exception
1284 public function set_url($url, array $params = null) {
1287 if (is_string($url) && strpos($url, 'http') !== 0) {
1288 if (strpos($url, '/') === 0) {
1289 // We have to use httpswwwroot here, because of loginhttps pages.
1290 $url = $CFG->httpswwwroot
. $url;
1292 throw new coding_exception('Invalid parameter $url, has to be full url or in shortened form starting with /.');
1296 $this->_url
= new moodle_url($url, $params);
1298 $fullurl = $this->_url
->out_omit_querystring();
1299 if (strpos($fullurl, "$CFG->httpswwwroot/") !== 0) {
1300 debugging('Most probably incorrect set_page() url argument, it does not match the httpswwwroot!');
1302 $shorturl = str_replace("$CFG->httpswwwroot/", '', $fullurl);
1304 if (is_null($this->_pagetype
)) {
1305 $this->initialise_default_pagetype($shorturl);
1310 * Make sure page URL does not contain the given URL parameter.
1312 * This should not be necessary if the script has called set_url properly.
1313 * However, in some situations like the block editing actions; when the URL
1314 * has been guessed, it will contain dangerous block-related actions.
1315 * Therefore, the blocks code calls this function to clean up such parameters
1316 * before doing any redirect.
1318 * @param string $param the name of the parameter to make sure is not in the
1321 public function ensure_param_not_in_url($param) {
1322 $this->_url
->remove_params($param);
1326 * Sets an alternative version of this page.
1328 * There can be alternate versions of some pages (for example an RSS feed version).
1329 * Call this method for each alternative version available.
1330 * For each alternative version a link will be included in the <head> tag.
1332 * @param string $title The title to give the alternate version.
1333 * @param string|moodle_url $url The URL of the alternate version.
1334 * @param string $mimetype The mime-type of the alternate version.
1335 * @throws coding_exception
1337 public function add_alternate_version($title, $url, $mimetype) {
1338 if ($this->_state
> self
::STATE_BEFORE_HEADER
) {
1339 throw new coding_exception('Cannot call moodle_page::add_alternate_version after output has been started.');
1341 $alt = new stdClass
;
1342 $alt->title
= $title;
1344 $this->_alternateversions
[$mimetype] = $alt;
1348 * Specify a form control should be focused when the page has loaded.
1350 * @param string $controlid the id of the HTML element to be focused.
1352 public function set_focuscontrol($controlid) {
1353 $this->_focuscontrol
= $controlid;
1357 * Specify a fragment of HTML that goes where the 'Turn editing on' button normally goes.
1359 * @param string $html the HTML to display there.
1361 public function set_button($html) {
1362 $this->_button
= $html;
1366 * Set the capability that allows users to edit blocks on this page.
1368 * Normally the default of 'moodle/site:manageblocks' is used, but a few
1369 * pages like the My Moodle page need to use a different capability
1370 * like 'moodle/my:manageblocks'.
1372 * @param string $capability a capability.
1374 public function set_blocks_editing_capability($capability) {
1375 $this->_blockseditingcap
= $capability;
1379 * Some pages let you turn editing on for reasons other than editing blocks.
1380 * If that is the case, you can pass other capabilities that let the user
1381 * edit this page here.
1383 * @param string|array $capability either a capability, or an array of capabilities.
1385 public function set_other_editing_capability($capability) {
1386 if (is_array($capability)) {
1387 $this->_othereditingcaps
= array_unique($this->_othereditingcaps +
$capability);
1389 $this->_othereditingcaps
[] = $capability;
1394 * Sets whether the browser should cache this page or not.
1396 * @param bool $cacheable can this page be cached by the user's browser.
1398 public function set_cacheable($cacheable) {
1399 $this->_cacheable
= $cacheable;
1403 * Sets the page to periodically refresh
1405 * This function must be called before $OUTPUT->header has been called or
1406 * a coding exception will be thrown.
1408 * @param int $delay Sets the delay before refreshing the page, if set to null refresh is cancelled.
1409 * @throws coding_exception
1411 public function set_periodic_refresh_delay($delay = null) {
1412 if ($this->_state
> self
::STATE_BEFORE_HEADER
) {
1413 throw new coding_exception('You cannot set a periodic refresh delay after the header has been printed');
1415 if ($delay === null) {
1416 $this->_periodicrefreshdelay
= null;
1417 } else if (is_int($delay)) {
1418 $this->_periodicrefreshdelay
= $delay;
1423 * Force this page to use a particular theme.
1425 * Please use this cautiously.
1426 * It is only intended to be used by the themes selector admin page.
1428 * @param string $themename the name of the theme to use.
1430 public function force_theme($themename) {
1431 $this->ensure_theme_not_set();
1432 $this->_theme
= theme_config
::load($themename);
1436 * Reload theme settings.
1438 * This is used when we need to reset settings
1439 * because they are now double cached in theme.
1441 public function reload_theme() {
1442 if (!is_null($this->_theme
)) {
1443 $this->_theme
= theme_config
::load($this->_theme
->name
);
1448 * This function indicates that current page requires the https when $CFG->loginhttps enabled.
1450 * By using this function properly, we can ensure 100% https-ized pages
1451 * at our entire discretion (login, forgot_password, change_password)
1454 * @throws coding_exception
1456 public function https_required() {
1459 if (!is_null($this->_url
)) {
1460 throw new coding_exception('https_required() must be used before setting page url!');
1463 $this->ensure_theme_not_set();
1465 $this->_https_login_required
= true;
1467 if (!empty($CFG->loginhttps
)) {
1468 $CFG->httpswwwroot
= str_replace('http:', 'https:', $CFG->wwwroot
);
1470 $CFG->httpswwwroot
= $CFG->wwwroot
;
1475 * Makes sure that page previously marked with https_required() is really using https://, if not it redirects to https://
1477 * @return void (may redirect to https://self)
1478 * @throws coding_exception
1480 public function verify_https_required() {
1481 global $CFG, $FULLME;
1483 if (is_null($this->_url
)) {
1484 throw new coding_exception('verify_https_required() must be called after setting page url!');
1487 if (!$this->_https_login_required
) {
1488 throw new coding_exception('verify_https_required() must be called only after https_required()!');
1491 if (empty($CFG->loginhttps
)) {
1492 // Https not required, so stop checking.
1496 if (strpos($this->_url
, 'https://')) {
1497 // Detect if incorrect PAGE->set_url() used, it is recommended to use root-relative paths there.
1498 throw new coding_exception('Invalid page url. It must start with https:// for pages that set https_required()!');
1501 if (!empty($CFG->sslproxy
)) {
1502 // It does not make much sense to use sslproxy and loginhttps at the same time.
1506 // Now the real test and redirect!
1507 // NOTE: do NOT use this test for detection of https on current page because this code is not compatible with SSL proxies,
1508 // instead use is_https().
1509 if (strpos($FULLME, 'https:') !== 0) {
1510 // This may lead to infinite redirect on an incorrectly configured site.
1511 // In that case set $CFG->loginhttps=0; within /config.php.
1512 redirect($this->_url
);
1516 // Initialisation methods =====================================================
1517 // These set various things up in a default way.
1520 * This method is called when the page first moves out of the STATE_BEFORE_HEADER
1521 * state. This is our last change to initialise things.
1523 protected function starting_output() {
1526 if (!during_initial_install()) {
1527 $this->blocks
->load_blocks();
1528 if (empty($this->_block_actions_done
)) {
1529 $this->_block_actions_done
= true;
1530 if ($this->blocks
->process_url_actions($this)) {
1531 redirect($this->url
->out(false));
1534 $this->blocks
->create_all_block_instances();
1537 // If maintenance mode is on, change the page header.
1538 if (!empty($CFG->maintenance_enabled
)) {
1539 $this->set_button('<a href="' . $CFG->wwwroot
. '/' . $CFG->admin
.
1540 '/settings.php?section=maintenancemode">' . get_string('maintenancemode', 'admin') .
1541 '</a> ' . $this->button
);
1543 $title = $this->title
;
1547 $this->set_title($title . get_string('maintenancemode', 'admin'));
1550 $this->initialise_standard_body_classes();
1554 * Method for use by Moodle core to set up the theme. Do not
1555 * use this in your own code.
1557 * Make sure the right theme for this page is loaded. Tell our
1558 * blocks_manager about the theme block regions, and then, if
1559 * we are $PAGE, set up the global $OUTPUT.
1563 public function initialise_theme_and_output() {
1564 global $OUTPUT, $PAGE, $SITE, $CFG;
1566 if (!empty($this->_wherethemewasinitialised
)) {
1570 if (!during_initial_install()) {
1571 // Detect PAGE->context mess.
1572 $this->magic_get_context();
1575 if (!$this->_course
&& !during_initial_install()) {
1576 $this->set_course($SITE);
1579 if (is_null($this->_theme
)) {
1580 $themename = $this->resolve_theme();
1581 $this->_theme
= theme_config
::load($themename);
1584 $this->_theme
->setup_blocks($this->pagelayout
, $this->blocks
);
1585 if ($this->_theme
->enable_dock
&& !empty($CFG->allowblockstodock
)) {
1586 $this->requires
->strings_for_js(array('addtodock', 'undockitem', 'dockblock', 'undockblock', 'undockall', 'hidedockpanel', 'hidepanel'), 'block');
1587 $this->requires
->string_for_js('thisdirectionvertical', 'langconfig');
1588 $this->requires
->yui_module('moodle-core-dock-loader', 'M.core.dock.loader.initLoader');
1591 if ($this === $PAGE) {
1593 if ($this->pagelayout
=== 'maintenance') {
1594 // If the page is using the maintenance layout then we're going to force target to maintenance.
1595 // This leads to a special core renderer that is designed to block access to API's that are likely unavailable for this
1597 $target = RENDERER_TARGET_MAINTENANCE
;
1599 $OUTPUT = $this->get_renderer('core', null, $target);
1602 if (!during_initial_install()) {
1603 $filtermanager = filter_manager
::instance();
1604 $filtermanager->setup_page_for_globally_available_filters($this);
1607 $this->_wherethemewasinitialised
= debug_backtrace();
1611 * Reset the theme and output for a new context. This only makes sense from
1612 * external::validate_context(). Do not cheat.
1614 * @return string the name of the theme that should be used on this page.
1616 public function reset_theme_and_output() {
1617 global $COURSE, $SITE;
1619 $COURSE = clone($SITE);
1620 $this->_theme
= null;
1621 $this->_wherethemewasinitialised
= null;
1622 $this->_course
= null;
1624 $this->_module
= null;
1625 $this->_context
= null;
1629 * Work out the theme this page should use.
1631 * This depends on numerous $CFG settings, and the properties of this page.
1633 * @return string the name of the theme that should be used on this page.
1635 protected function resolve_theme() {
1636 global $CFG, $USER, $SESSION;
1638 if (empty($CFG->themeorder
)) {
1639 $themeorder = array('course', 'category', 'session', 'user', 'site');
1641 $themeorder = $CFG->themeorder
;
1642 // Just in case, make sure we always use the site theme if nothing else matched.
1643 $themeorder[] = 'site';
1646 $mnetpeertheme = '';
1647 if (isloggedin() and isset($CFG->mnet_localhost_id
) and $USER->mnethostid
!= $CFG->mnet_localhost_id
) {
1648 require_once($CFG->dirroot
.'/mnet/peer.php');
1649 $mnetpeer = new mnet_peer();
1650 $mnetpeer->set_id($USER->mnethostid
);
1651 if ($mnetpeer->force_theme
== 1 && $mnetpeer->theme
!= '') {
1652 $mnetpeertheme = $mnetpeer->theme
;
1656 $devicetheme = core_useragent
::get_device_type_theme($this->devicetypeinuse
);
1658 // The user is using another device than default, and we have a theme for that, we should use it.
1659 $hascustomdevicetheme = core_useragent
::DEVICETYPE_DEFAULT
!= $this->devicetypeinuse
&& !empty($devicetheme);
1661 foreach ($themeorder as $themetype) {
1663 switch ($themetype) {
1665 if (!empty($CFG->allowcoursethemes
) && !empty($this->_course
->theme
) && !$hascustomdevicetheme) {
1666 return $this->_course
->theme
;
1671 if (!empty($CFG->allowcategorythemes
) && !$hascustomdevicetheme) {
1672 $categories = $this->categories
;
1673 foreach ($categories as $category) {
1674 if (!empty($category->theme
)) {
1675 return $category->theme
;
1682 if (!empty($SESSION->theme
)) {
1683 return $SESSION->theme
;
1688 if (!empty($CFG->allowuserthemes
) && !empty($USER->theme
) && !$hascustomdevicetheme) {
1689 if ($mnetpeertheme) {
1690 return $mnetpeertheme;
1692 return $USER->theme
;
1698 if ($mnetpeertheme) {
1699 return $mnetpeertheme;
1701 // First try for the device the user is using.
1702 if (!empty($devicetheme)) {
1703 return $devicetheme;
1705 // Next try for the default device (as a fallback).
1706 $devicetheme = core_useragent
::get_device_type_theme(core_useragent
::DEVICETYPE_DEFAULT
);
1707 if (!empty($devicetheme)) {
1708 return $devicetheme;
1710 // The default device theme isn't set up - use the overall default theme.
1711 return theme_config
::DEFAULT_THEME
;
1715 // We should most certainly have resolved a theme by now. Something has gone wrong.
1716 debugging('Error resolving the theme to use for this page.', DEBUG_DEVELOPER
);
1717 return theme_config
::DEFAULT_THEME
;
1722 * Sets ->pagetype from the script name. For example, if the script that was
1723 * run is mod/quiz/view.php, ->pagetype will be set to 'mod-quiz-view'.
1725 * @param string $script the path to the script that should be used to
1726 * initialise ->pagetype. If not passed the $SCRIPT global will be used.
1727 * If legacy code has set $CFG->pagepath that will be used instead, and a
1728 * developer warning issued.
1730 protected function initialise_default_pagetype($script = null) {
1731 global $CFG, $SCRIPT;
1733 if (isset($CFG->pagepath
)) {
1734 debugging('Some code appears to have set $CFG->pagepath. That was a horrible deprecated thing. ' .
1735 'Don\'t do it! Try calling $PAGE->set_pagetype() instead.');
1736 $script = $CFG->pagepath
;
1737 unset($CFG->pagepath
);
1740 if (is_null($script)) {
1741 $script = ltrim($SCRIPT, '/');
1742 $len = strlen($CFG->admin
);
1743 if (substr($script, 0, $len) == $CFG->admin
) {
1744 $script = 'admin' . substr($script, $len);
1748 $path = str_replace('.php', '', $script);
1749 if (substr($path, -1) == '/') {
1753 if (empty($path) ||
$path == 'index') {
1754 $this->_pagetype
= 'site-index';
1756 $this->_pagetype
= str_replace('/', '-', $path);
1761 * Initialises the CSS classes that will be added to body tag of the page.
1763 * The function is responsible for adding all of the critical CSS classes
1764 * that describe the current page, and its state.
1765 * This includes classes that describe the following for example:
1766 * - Current language
1767 * - Language direction
1768 * - YUI CSS initialisation
1770 * These are commonly used in CSS to target specific types of pages.
1772 protected function initialise_standard_body_classes() {
1775 $pagetype = $this->pagetype
;
1776 if ($pagetype == 'site-index') {
1777 $this->_legacyclass
= 'course';
1778 } else if (substr($pagetype, 0, 6) == 'admin-') {
1779 $this->_legacyclass
= 'admin';
1781 $this->add_body_class($this->_legacyclass
);
1783 $pathbits = explode('-', trim($pagetype));
1784 for ($i = 1; $i < count($pathbits); $i++
) {
1785 $this->add_body_class('path-' . join('-', array_slice($pathbits, 0, $i)));
1788 $this->add_body_classes(core_useragent
::get_browser_version_classes());
1789 $this->add_body_class('dir-' . get_string('thisdirection', 'langconfig'));
1790 $this->add_body_class('lang-' . current_language());
1791 $this->add_body_class('yui-skin-sam'); // Make YUI happy, if it is used.
1792 $this->add_body_class('yui3-skin-sam'); // Make YUI3 happy, if it is used.
1793 $this->add_body_class($this->url_to_class_name($CFG->wwwroot
));
1795 // Extra class describing current page layout.
1796 $this->add_body_class('pagelayout-' . $this->_pagelayout
);
1798 if (!during_initial_install()) {
1799 $this->add_body_class('course-' . $this->_course
->id
);
1800 $this->add_body_class('context-' . $this->_context
->id
);
1803 if (!empty($this->_cm
)) {
1804 $this->add_body_class('cmid-' . $this->_cm
->id
);
1807 if (!empty($CFG->allowcategorythemes
)) {
1808 $this->ensure_category_loaded();
1809 foreach ($this->_categories
as $catid => $notused) {
1810 $this->add_body_class('category-' . $catid);
1814 if (is_array($this->_categories
)) {
1815 $catids = array_keys($this->_categories
);
1816 $catid = reset($catids);
1817 } else if (!empty($this->_course
->category
)) {
1818 $catid = $this->_course
->category
;
1821 $this->add_body_class('category-' . $catid);
1825 if (!isloggedin()) {
1826 $this->add_body_class('notloggedin');
1829 if ($this->user_is_editing()) {
1830 $this->add_body_class('editing');
1831 if (optional_param('bui_moveid', false, PARAM_INT
)) {
1832 $this->add_body_class('blocks-moving');
1836 if (!empty($CFG->blocksdrag
)) {
1837 $this->add_body_class('drag');
1840 if ($this->_devicetypeinuse
!= 'default') {
1841 $this->add_body_class($this->_devicetypeinuse
. 'theme');
1844 // Add class for behat site to apply behat related fixes.
1845 if (defined('BEHAT_SITE_RUNNING')) {
1846 $this->add_body_class('behat-site');
1851 * Loads the activity record for the current CM object associated with this
1854 * This will load {@link moodle_page::$_module} with a row from the related
1855 * module table in the database.
1856 * For instance if {@link moodle_page::$_cm} is a forum then a row from the
1857 * forum table will be loaded.
1859 protected function load_activity_record() {
1861 if (is_null($this->_cm
)) {
1864 $this->_module
= $DB->get_record($this->_cm
->modname
, array('id' => $this->_cm
->instance
));
1868 * This function ensures that the category of the current course has been
1869 * loaded, and if not, the function loads it now.
1872 * @throws coding_exception
1874 protected function ensure_category_loaded() {
1875 if (is_array($this->_categories
)) {
1876 return; // Already done.
1878 if (is_null($this->_course
)) {
1879 throw new coding_exception('Attempt to get the course category for this page before the course was set.');
1881 if ($this->_course
->category
== 0) {
1882 $this->_categories
= array();
1884 $this->load_category($this->_course
->category
);
1889 * Loads the requested category into the pages categories array.
1891 * @param int $categoryid
1892 * @throws moodle_exception
1894 protected function load_category($categoryid) {
1896 $category = $DB->get_record('course_categories', array('id' => $categoryid));
1898 throw new moodle_exception('unknowncategory');
1900 $this->_categories
[$category->id
] = $category;
1901 $parentcategoryids = explode('/', trim($category->path
, '/'));
1902 array_pop($parentcategoryids);
1903 foreach (array_reverse($parentcategoryids) as $catid) {
1904 $this->_categories
[$catid] = null;
1909 * Ensures that the category the current course is within, as well as all of
1910 * its parent categories, have been loaded.
1914 protected function ensure_categories_loaded() {
1916 $this->ensure_category_loaded();
1917 if (!is_null(end($this->_categories
))) {
1918 return; // Already done.
1920 $idstoload = array_keys($this->_categories
);
1921 array_shift($idstoload);
1922 $categories = $DB->get_records_list('course_categories', 'id', $idstoload);
1923 foreach ($idstoload as $catid) {
1924 $this->_categories
[$catid] = $categories[$catid];
1929 * Ensure the theme has not been loaded yet. If it has an exception is thrown.
1931 * @throws coding_exception
1933 protected function ensure_theme_not_set() {
1934 // This is explicitly allowed for webservices though which may process many course contexts in a single request.
1939 if (!is_null($this->_theme
)) {
1940 throw new coding_exception('The theme has already been set up for this page ready for output. ' .
1941 'Therefore, you can no longer change the theme, or anything that might affect what ' .
1942 'the current theme is, for example, the course.',
1943 'Stack trace when the theme was set up: ' . format_backtrace($this->_wherethemewasinitialised
));
1948 * Converts the provided URL into a CSS class that be used within the page.
1949 * This is primarily used to add the wwwroot to the body tag as a CSS class.
1951 * @param string $url
1954 protected function url_to_class_name($url) {
1955 $bits = parse_url($url);
1956 $class = str_replace('.', '-', $bits['host']);
1957 if (!empty($bits['port'])) {
1958 $class .= '--' . $bits['port'];
1960 if (!empty($bits['path'])) {
1961 $path = trim($bits['path'], '/');
1963 $class .= '--' . str_replace('/', '-', $path);
1970 * Combines all of the required editing caps for the page and returns them
1975 protected function all_editing_caps() {
1976 $caps = $this->_othereditingcaps
;
1977 $caps[] = $this->_blockseditingcap
;
1982 * Returns true if the page URL has beem set.
1986 public function has_set_url() {
1987 return ($this->_url
!==null);
1991 * Gets set when the block actions for the page have been processed.
1993 * @param bool $setting
1995 public function set_block_actions_done($setting = true) {
1996 $this->_block_actions_done
= $setting;
2000 * Are popup notifications allowed on this page?
2001 * Popup notifications may be disallowed in situations such as while upgrading or completing a quiz
2003 * @return bool true if popup notifications may be displayed
2005 public function get_popup_notification_allowed() {
2006 return $this->_popup_notification_allowed
;
2010 * Allow or disallow popup notifications on this page. Popups are allowed by default.
2012 * @param bool $allowed true if notifications are allowed. False if not allowed. They are allowed by default.
2014 public function set_popup_notification_allowed($allowed) {
2015 $this->_popup_notification_allowed
= $allowed;
2019 * Returns the block region having made any required theme manipulations.
2021 * @since Moodle 2.5.1 2.6
2022 * @param string $region
2025 public function apply_theme_region_manipulations($region) {
2026 if ($this->blockmanipulations
&& isset($this->blockmanipulations
[$region])) {
2027 $regionwas = $region;
2028 $regionnow = $this->blockmanipulations
[$region];
2029 if ($this->blocks
->is_known_region($regionwas) && $this->blocks
->is_known_region($regionnow)) {
2030 // Both the before and after regions are known so we can swap them over.
2033 // We didn't know about both, we won't swap them over.
2040 * Add a report node and a specific report to the navigation.
2042 * @param int $userid The user ID that we are looking to add this report node to.
2043 * @param array $nodeinfo Name and url of the final node that we are creating.
2045 public function add_report_nodes($userid, $nodeinfo) {
2047 // Try to find the specific user node.
2048 $newusernode = $this->navigation
->find('user' . $userid, null);
2050 $navigationnodeerror =
2051 'Could not find the navigation node requested. Please check that the node you are looking for exists.';
2052 if ($userid != $USER->id
) {
2053 // Check that we have a valid node.
2054 if (empty($newusernode)) {
2055 // Throw an error if we ever reach here.
2056 throw new coding_exception($navigationnodeerror);
2058 // Add 'Reports' to the user node.
2059 $reportnode = $newusernode->add(get_string('reports'));
2061 // We are looking at our own profile.
2062 $myprofilenode = $this->settingsnav
->find('myprofile', null);
2063 // Check that we do end up with a valid node.
2064 if (empty($myprofilenode)) {
2065 // Throw an error if we ever reach here.
2066 throw new coding_exception($navigationnodeerror);
2068 // Add 'Reports' to our node.
2069 $reportnode = $myprofilenode->add(get_string('reports'));
2071 // Finally add the report to the navigation tree.
2072 $reportnode->add($nodeinfo['name'], $nodeinfo['url'], navigation_node
::TYPE_COURSE
);