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;
235 /** @var page_requirements_manager Saves the requirement manager object used before switching to to fragments one. */
236 protected $savedrequires = null;
239 * @var string The capability required by the user in order to edit blocks
240 * and block settings on this page.
242 protected $_blockseditingcap = 'moodle/site:manageblocks';
245 * @var bool An internal flag to record when block actions have been processed.
246 * Remember block actions occur on the current URL and it is important that
247 * even they are never executed more than once.
249 protected $_block_actions_done = false;
252 * @var array An array of any other capabilities the current user must have
253 * in order to editing the page and/or its content (not just blocks).
255 protected $_othereditingcaps = array();
258 * @var bool Sets whether this page should be cached by the browser or not.
259 * If it is set to true (default) the page is served with caching headers.
261 protected $_cacheable = true;
264 * @var string Can be set to the ID of an element on the page, if done that
265 * element receives focus when the page loads.
267 protected $_focuscontrol = '';
270 * @var string HTML to go where the turn on editing button is located. This
271 * is nearly a legacy item and not used very often any more.
273 protected $_button = '';
276 * @var theme_config The theme to use with this page. This has to be properly
277 * initialised via {@link moodle_page::initialise_theme_and_output()} which
278 * happens magically before any operation that requires it.
280 protected $_theme = null;
283 * @var global_navigation Contains the global navigation structure.
285 protected $_navigation = null;
288 * @var settings_navigation Contains the settings navigation structure.
290 protected $_settingsnav = null;
293 * @var flat_navigation Contains a list of nav nodes, most closely related to the current page.
295 protected $_flatnav = null;
298 * @var navbar Contains the navbar structure.
300 protected $_navbar = null;
303 * @var string The menu (or actions) to display in the heading.
305 protected $_headingmenu = null;
308 * @var array stack trace. Then the theme is initialised, we save the stack
309 * trace, for use in error messages.
311 protected $_wherethemewasinitialised = null;
314 * @var xhtml_container_stack Tracks XHTML tags on this page that have been
315 * opened but not closed.
317 protected $_opencontainers;
320 * @var int Sets the page to refresh after a given delay (in seconds) using
321 * meta refresh in {@link standard_head_html()} in outputlib.php
322 * If set to null(default) the page is not refreshed
324 protected $_periodicrefreshdelay = null;
327 * @var array Associative array of browser shortnames (as used by check_browser_version)
328 * and their minimum required versions
330 protected $_legacybrowsers = array('MSIE' => 6.0);
333 * @var string Is set to the name of the device type in use.
334 * This will we worked out when it is first used.
336 protected $_devicetypeinuse = null;
339 * @var bool Used to determine if HTTPS should be required for login.
341 protected $_https_login_required = false;
344 * @var bool Determines if popup notifications allowed on this page.
345 * Code such as the quiz module disables popup notifications in situations
346 * such as upgrading or completing a quiz.
348 protected $_popup_notification_allowed = true;
351 * @var bool Is the settings menu being forced to display on this page (activities / resources only).
352 * This is only used by themes that use the settings menu.
354 protected $_forcesettingsmenu = false;
357 * Force the settings menu to be displayed on this page. This will only force the
358 * settings menu on an activity / resource page that is being displayed on a theme that
359 * uses a settings menu.
361 * @param bool $forced default of true, can be sent false to turn off the force.
363 public function force_settings_menu($forced = true) {
364 $this->_forcesettingsmenu
= $forced;
368 * Check to see if the settings menu is forced to display on this activity / resource page.
369 * This only applies to themes that use the settings menu.
371 * @return bool True if the settings menu is forced to display.
373 public function is_settings_menu_forced() {
374 return $this->_forcesettingsmenu
;
377 // Magic getter methods =============================================================
378 // Due to the __get magic below, you normally do not call these as $PAGE->magic_get_x
379 // methods, but instead use the $PAGE->x syntax.
382 * Please do not call this method directly, use the ->state syntax. {@link moodle_page::__get()}.
383 * @return integer one of the STATE_XXX constants. You should not normally need
384 * to use this in your code. It is intended for internal use by this class
385 * and its friends like print_header, to check that everything is working as
386 * expected. Also accessible as $PAGE->state.
388 protected function magic_get_state() {
389 return $this->_state
;
393 * Please do not call this method directly, use the ->headerprinted syntax. {@link moodle_page::__get()}.
394 * @return bool has the header already been printed?
396 protected function magic_get_headerprinted() {
397 return $this->_state
>= self
::STATE_IN_BODY
;
401 * Please do not call this method directly, use the ->course syntax. {@link moodle_page::__get()}.
402 * @return stdClass the current course that we are inside - a row from the
403 * course table. (Also available as $COURSE global.) If we are not inside
404 * an actual course, this will be the site course.
406 protected function magic_get_course() {
408 if (is_null($this->_course
)) {
411 return $this->_course
;
415 * Please do not call this method directly, use the ->cm syntax. {@link moodle_page::__get()}.
416 * @return cm_info the course_module that this page belongs to. Will be null
417 * if this page is not within a module. This is a full cm object, as loaded
418 * by get_coursemodule_from_id or get_coursemodule_from_instance,
419 * so the extra modname and name fields are present.
421 protected function magic_get_cm() {
426 * Please do not call this method directly, use the ->activityrecord syntax. {@link moodle_page::__get()}.
427 * @return stdClass the row from the activities own database table (for example
428 * the forum or quiz table) that this page belongs to. Will be null
429 * if this page is not within a module.
431 protected function magic_get_activityrecord() {
432 if (is_null($this->_module
) && !is_null($this->_cm
)) {
433 $this->load_activity_record();
435 return $this->_module
;
439 * Please do not call this method directly, use the ->activityname syntax. {@link moodle_page::__get()}.
440 * @return string the The type of activity we are in, for example 'forum' or 'quiz'.
441 * Will be null if this page is not within a module.
443 protected function magic_get_activityname() {
444 if (is_null($this->_cm
)) {
447 return $this->_cm
->modname
;
451 * Please do not call this method directly, use the ->category syntax. {@link moodle_page::__get()}.
452 * @return stdClass the category that the page course belongs to. If there isn't one
453 * (that is, if this is the front page course) returns null.
455 protected function magic_get_category() {
456 $this->ensure_category_loaded();
457 if (!empty($this->_categories
)) {
458 return reset($this->_categories
);
465 * Please do not call this method directly, use the ->categories syntax. {@link moodle_page::__get()}.
466 * @return array an array of all the categories the page course belongs to,
467 * starting with the immediately containing category, and working out to
468 * the top-level category. This may be the empty array if we are in the
471 protected function magic_get_categories() {
472 $this->ensure_categories_loaded();
473 return $this->_categories
;
477 * Please do not call this method directly, use the ->context syntax. {@link moodle_page::__get()}.
478 * @return context the main context to which this page belongs.
480 protected function magic_get_context() {
482 if (is_null($this->_context
)) {
483 if (CLI_SCRIPT
or NO_MOODLE_COOKIES
) {
484 // Cli scripts work in system context, do not annoy devs with debug info.
485 // Very few scripts do not use cookies, we can safely use system as default context there.
486 } else if (AJAX_SCRIPT
&& $CFG->debugdeveloper
) {
487 // Throw exception inside AJAX script in developer mode, otherwise the debugging message may be missed.
488 throw new coding_exception('$PAGE->context was not set. You may have forgotten '
489 .'to call require_login() or $PAGE->set_context()');
491 debugging('Coding problem: $PAGE->context was not set. You may have forgotten '
492 .'to call require_login() or $PAGE->set_context(). The page may not display '
493 .'correctly as a result');
495 $this->_context
= context_system
::instance();
497 return $this->_context
;
501 * Please do not call this method directly, use the ->pagetype syntax. {@link moodle_page::__get()}.
502 * @return string e.g. 'my-index' or 'mod-quiz-attempt'.
504 protected function magic_get_pagetype() {
506 if (is_null($this->_pagetype
) ||
isset($CFG->pagepath
)) {
507 $this->initialise_default_pagetype();
509 return $this->_pagetype
;
513 * Please do not call this method directly, use the ->pagetype syntax. {@link moodle_page::__get()}.
514 * @return string The id to use on the body tag, uses {@link magic_get_pagetype()}.
516 protected function magic_get_bodyid() {
517 return 'page-'.$this->pagetype
;
521 * Please do not call this method directly, use the ->pagelayout syntax. {@link moodle_page::__get()}.
522 * @return string the general type of page this is. For example 'standard', 'popup', 'home'.
523 * Allows the theme to display things differently, if it wishes to.
525 protected function magic_get_pagelayout() {
526 return $this->_pagelayout
;
530 * Please do not call this method directly, use the ->layout_options syntax. {@link moodle_page::__get()}.
531 * @return array returns arrays with options for layout file
533 protected function magic_get_layout_options() {
534 if (!is_array($this->_layout_options
)) {
535 $this->_layout_options
= $this->_theme
->pagelayout_options($this->pagelayout
);
537 return $this->_layout_options
;
541 * Please do not call this method directly, use the ->subpage syntax. {@link moodle_page::__get()}.
542 * @return string The subpage identifier, if any.
544 protected function magic_get_subpage() {
545 return $this->_subpage
;
549 * Please do not call this method directly, use the ->bodyclasses syntax. {@link moodle_page::__get()}.
550 * @return string the class names to put on the body element in the HTML.
552 protected function magic_get_bodyclasses() {
553 return implode(' ', array_keys($this->_bodyclasses
));
557 * Please do not call this method directly, use the ->title syntax. {@link moodle_page::__get()}.
558 * @return string the title that should go in the <head> section of the HTML of this page.
560 protected function magic_get_title() {
561 return $this->_title
;
565 * Please do not call this method directly, use the ->heading syntax. {@link moodle_page::__get()}.
566 * @return string the main heading that should be displayed at the top of the <body>.
568 protected function magic_get_heading() {
569 return $this->_heading
;
573 * Please do not call this method directly, use the ->heading syntax. {@link moodle_page::__get()}.
574 * @return string The menu (or actions) to display in the heading
576 protected function magic_get_headingmenu() {
577 return $this->_headingmenu
;
581 * Please do not call this method directly, use the ->docspath syntax. {@link moodle_page::__get()}.
582 * @return string the path to the Moodle docs for this page.
584 protected function magic_get_docspath() {
585 if (is_string($this->_docspath
)) {
586 return $this->_docspath
;
588 return str_replace('-', '/', $this->pagetype
);
593 * Please do not call this method directly, use the ->url syntax. {@link moodle_page::__get()}.
594 * @return moodle_url the clean URL required to load the current page. (You
595 * should normally use this in preference to $ME or $FULLME.)
597 protected function magic_get_url() {
599 if (is_null($this->_url
)) {
600 debugging('This page did not call $PAGE->set_url(...). Using '.s($FULLME), DEBUG_DEVELOPER
);
601 $this->_url
= new moodle_url($FULLME);
602 // Make sure the guessed URL cannot lead to dangerous redirects.
603 $this->_url
->remove_params('sesskey');
605 return new moodle_url($this->_url
); // Return a clone for safety.
609 * The list of alternate versions of this page.
610 * @return array mime type => object with ->url and ->title.
612 protected function magic_get_alternateversions() {
613 return $this->_alternateversions
;
617 * Please do not call this method directly, use the ->blocks syntax. {@link moodle_page::__get()}.
618 * @return block_manager the blocks manager object for this page.
620 protected function magic_get_blocks() {
622 if (is_null($this->_blocks
)) {
623 if (!empty($CFG->blockmanagerclass
)) {
624 if (!empty($CFG->blockmanagerclassfile
)) {
625 require_once($CFG->blockmanagerclassfile
);
627 $classname = $CFG->blockmanagerclass
;
629 $classname = 'block_manager';
631 $this->_blocks
= new $classname($this);
633 return $this->_blocks
;
637 * Please do not call this method directly, use the ->requires syntax. {@link moodle_page::__get()}.
638 * @return page_requirements_manager tracks the JavaScript, CSS files, etc. required by this page.
640 protected function magic_get_requires() {
641 if (is_null($this->_requires
)) {
642 $this->_requires
= new page_requirements_manager();
644 return $this->_requires
;
648 * Please do not call this method directly, use the ->cacheable syntax. {@link moodle_page::__get()}.
649 * @return bool can this page be cached by the user's browser.
651 protected function magic_get_cacheable() {
652 return $this->_cacheable
;
656 * Please do not call this method directly, use the ->focuscontrol syntax. {@link moodle_page::__get()}.
657 * @return string the id of the HTML element to be focused when the page has loaded.
659 protected function magic_get_focuscontrol() {
660 return $this->_focuscontrol
;
664 * Please do not call this method directly, use the ->button syntax. {@link moodle_page::__get()}.
665 * @return string the HTML to go where the Turn editing on button normally goes.
667 protected function magic_get_button() {
668 return $this->_button
;
672 * Please do not call this method directly, use the ->theme syntax. {@link moodle_page::__get()}.
673 * @return theme_config the initialised theme for this page.
675 protected function magic_get_theme() {
676 if (is_null($this->_theme
)) {
677 $this->initialise_theme_and_output();
679 return $this->_theme
;
683 * Returns an array of minipulations or false if there are none to make.
685 * @since Moodle 2.5.1 2.6
688 protected function magic_get_blockmanipulations() {
689 if (!right_to_left()) {
692 if (is_null($this->_theme
)) {
693 $this->initialise_theme_and_output();
695 return $this->_theme
->blockrtlmanipulations
;
699 * Please do not call this method directly, use the ->devicetypeinuse syntax. {@link moodle_page::__get()}.
700 * @return string The device type being used.
702 protected function magic_get_devicetypeinuse() {
703 if (empty($this->_devicetypeinuse
)) {
704 $this->_devicetypeinuse
= core_useragent
::get_user_device_type();
706 return $this->_devicetypeinuse
;
710 * Please do not call this method directly use the ->periodicrefreshdelay syntax
711 * {@link moodle_page::__get()}
712 * @return int The periodic refresh delay to use with meta refresh
714 protected function magic_get_periodicrefreshdelay() {
715 return $this->_periodicrefreshdelay
;
719 * Please do not call this method directly use the ->opencontainers syntax. {@link moodle_page::__get()}
720 * @return xhtml_container_stack tracks XHTML tags on this page that have been opened but not closed.
721 * mainly for internal use by the rendering code.
723 protected function magic_get_opencontainers() {
724 if (is_null($this->_opencontainers
)) {
725 $this->_opencontainers
= new xhtml_container_stack();
727 return $this->_opencontainers
;
731 * Return the navigation object
732 * @return global_navigation
734 protected function magic_get_navigation() {
735 if ($this->_navigation
=== null) {
736 $this->_navigation
= new global_navigation($this);
738 return $this->_navigation
;
742 * Return a navbar object
745 protected function magic_get_navbar() {
746 if ($this->_navbar
=== null) {
747 $this->_navbar
= new navbar($this);
749 return $this->_navbar
;
753 * Returns the settings navigation object
754 * @return settings_navigation
756 protected function magic_get_settingsnav() {
757 if ($this->_settingsnav
=== null) {
758 $this->_settingsnav
= new settings_navigation($this);
759 $this->_settingsnav
->initialise();
761 return $this->_settingsnav
;
765 * Returns the flat navigation object
766 * @return flat_navigation
768 protected function magic_get_flatnav() {
769 if ($this->_flatnav
=== null) {
770 $this->_flatnav
= new flat_navigation($this);
771 $this->_flatnav
->initialise();
773 return $this->_flatnav
;
777 * Returns request IP address.
779 * @return string IP address or null if unknown
781 protected function magic_get_requestip() {
782 return getremoteaddr(null);
786 * Returns the origin of current request.
788 * Note: constants are not required because we need to use these values in logging and reports.
790 * @return string 'web', 'ws', 'cli', 'restore', etc.
792 protected function magic_get_requestorigin() {
793 if (class_exists('restore_controller', false) && restore_controller
::is_executing()) {
809 * PHP overloading magic to make the $PAGE->course syntax work by redirecting
810 * it to the corresponding $PAGE->magic_get_course() method if there is one, and
811 * throwing an exception if not.
813 * @param string $name property name
815 * @throws coding_exception
817 public function __get($name) {
818 $getmethod = 'magic_get_' . $name;
819 if (method_exists($this, $getmethod)) {
820 return $this->$getmethod();
822 throw new coding_exception('Unknown property ' . $name . ' of $PAGE.');
827 * PHP overloading magic to catch obvious coding errors.
829 * This method has been created to catch obvious coding errors where the
830 * developer has tried to set a page property using $PAGE->key = $value.
831 * In the moodle_page class all properties must be set using the appropriate
832 * $PAGE->set_something($value) method.
834 * @param string $name property name
835 * @param mixed $value Value
836 * @return void Throws exception if field not defined in page class
837 * @throws coding_exception
839 public function __set($name, $value) {
840 if (method_exists($this, 'set_' . $name)) {
841 throw new coding_exception('Invalid attempt to modify page object', "Use \$PAGE->set_$name() instead.");
843 throw new coding_exception('Invalid attempt to modify page object', "Unknown property $name");
847 // Other information getting methods ==========================================.
850 * Returns instance of page renderer
852 * @param string $component name such as 'core', 'mod_forum' or 'qtype_multichoice'.
853 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
854 * @param string $target one of rendering target constants
855 * @return renderer_base
857 public function get_renderer($component, $subtype = null, $target = null) {
858 if ($this->pagelayout
=== 'maintenance') {
859 // If the page is using the maintenance layout then we're going to force target to maintenance.
860 // This leads to a special core renderer that is designed to block access to API's that are likely unavailable for this
862 $target = RENDERER_TARGET_MAINTENANCE
;
864 return $this->magic_get_theme()->get_renderer($this, $component, $subtype, $target);
868 * Checks to see if there are any items on the navbar object
870 * @return bool true if there are, false if not
872 public function has_navbar() {
873 if ($this->_navbar
=== null) {
874 $this->_navbar
= new navbar($this);
876 return $this->_navbar
->has_items();
880 * Switches from the regular requirements manager to the fragment requirements manager to
881 * capture all necessary JavaScript to display a chunk of HTML such as an mform. This is for use
882 * by the get_fragment() web service and not for use elsewhere.
884 public function start_collecting_javascript_requirements() {
886 require_once($CFG->libdir
.'/outputfragmentrequirementslib.php');
888 // Check that the requirements manager has not already been switched.
889 if (get_class($this->_requires
) == 'fragment_requirements_manager') {
890 throw new coding_exception('JavaScript collection has already been started.');
892 // The header needs to have been called to flush out the generic JavaScript for the page. This allows only
893 // JavaScript for the fragment to be collected. _wherethemewasinitialised is set when header() is called.
894 if (!empty($this->_wherethemewasinitialised
)) {
895 // Change the current requirements manager over to the fragment manager to capture JS.
896 $this->savedrequires
= $this->_requires
;
897 $this->_requires
= new fragment_requirements_manager();
899 throw new coding_exception('$OUTPUT->header() needs to be called before collecting JavaScript requirements.');
904 * Switches back from collecting fragment JS requirement to the original requirement manager
906 public function end_collecting_javascript_requirements() {
907 if ($this->savedrequires
=== null) {
908 throw new coding_exception('JavaScript collection has not been started.');
910 $this->_requires
= $this->savedrequires
;
911 $this->savedrequires
= null;
915 * Should the current user see this page in editing mode.
916 * That is, are they allowed to edit this page, and are they currently in
920 public function user_is_editing() {
922 return !empty($USER->editing
) && $this->user_allowed_editing();
926 * Does the user have permission to edit blocks on this page.
929 public function user_can_edit_blocks() {
930 return has_capability($this->_blockseditingcap
, $this->_context
);
934 * Does the user have permission to see this page in editing mode.
937 public function user_allowed_editing() {
938 return has_any_capability($this->all_editing_caps(), $this->_context
);
942 * Get a description of this page. Normally displayed in the footer in developer debug mode.
945 public function debug_summary() {
947 $summary .= 'General type: ' . $this->pagelayout
. '. ';
948 if (!during_initial_install()) {
949 $summary .= 'Context ' . $this->context
->get_context_name() . ' (context id ' . $this->_context
->id
. '). ';
951 $summary .= 'Page type ' . $this->pagetype
. '. ';
952 if ($this->subpage
) {
953 $summary .= 'Sub-page ' . $this->subpage
. '. ';
958 // Setter methods =============================================================.
963 * The state must be one of that STATE_... constants, and the state is only allowed to advance one step at a time.
965 * @param int $state The new state.
966 * @throws coding_exception
968 public function set_state($state) {
969 if ($state != $this->_state +
1 ||
$state > self
::STATE_DONE
) {
970 throw new coding_exception('Invalid state passed to moodle_page::set_state. We are in state ' .
971 $this->_state
. ' and state ' . $state . ' was requested.');
974 if ($state == self
::STATE_PRINTING_HEADER
) {
975 $this->starting_output();
978 $this->_state
= $state;
982 * Set the current course. This sets both $PAGE->course and $COURSE. It also
983 * sets the right theme and locale.
985 * Normally you don't need to call this function yourself, require_login will
986 * call it for you if you pass a $course to it. You can use this function
987 * on pages that do need to call require_login().
989 * Sets $PAGE->context to the course context, if it is not already set.
991 * @param stdClass $course the course to set as the global course.
992 * @throws coding_exception
994 public function set_course($course) {
995 global $COURSE, $PAGE, $CFG, $SITE;
997 if (empty($course->id
)) {
998 throw new coding_exception('$course passed to moodle_page::set_course does not look like a proper course object.');
1001 $this->ensure_theme_not_set();
1003 if (!empty($this->_course
->id
) && $this->_course
->id
!= $course->id
) {
1004 $this->_categories
= null;
1007 $this->_course
= clone($course);
1009 if ($this === $PAGE) {
1010 $COURSE = $this->_course
;
1014 if (!$this->_context
) {
1015 $this->set_context(context_course
::instance($this->_course
->id
));
1018 // Notify course format that this page is set for the course.
1019 if ($this->_course
->id
!= $SITE->id
) {
1020 require_once($CFG->dirroot
.'/course/lib.php');
1021 $courseformat = course_get_format($this->_course
);
1022 $this->add_body_class('format-'. $courseformat->get_format());
1023 $courseformat->page_set_course($this);
1025 $this->add_body_class('format-site');
1030 * Set the main context to which this page belongs.
1032 * @param context $context a context object. You normally get this with context_xxxx::instance().
1034 public function set_context($context) {
1035 if ($context === null) {
1036 // Extremely ugly hack which sets context to some value in order to prevent warnings,
1037 // use only for core error handling!!!!
1038 if (!$this->_context
) {
1039 $this->_context
= context_system
::instance();
1043 // Ideally we should set context only once.
1044 if (isset($this->_context
) && $context->id
!== $this->_context
->id
) {
1045 $current = $this->_context
->contextlevel
;
1046 if ($current == CONTEXT_SYSTEM
or $current == CONTEXT_COURSE
) {
1047 // Hmm - not ideal, but it might produce too many warnings due to the design of require_login.
1048 } else if ($current == CONTEXT_MODULE
and ($parentcontext = $context->get_parent_context()) and
1049 $this->_context
->id
== $parentcontext->id
) {
1050 // Hmm - most probably somebody did require_login() and after that set the block context.
1052 // We do not want devs to do weird switching of context levels on the fly because we might have used
1053 // the context already such as in text filter in page title.
1054 debugging("Coding problem: unsupported modification of PAGE->context from {$current} to {$context->contextlevel}");
1058 $this->_context
= $context;
1062 * The course module that this page belongs to (if it does belong to one).
1064 * @param stdClass|cm_info $cm a record from course_modules table or cm_info from get_fast_modinfo().
1065 * @param stdClass $course
1066 * @param stdClass $module
1068 * @throws coding_exception
1070 public function set_cm($cm, $course = null, $module = null) {
1071 global $DB, $CFG, $SITE;
1073 if (!isset($cm->id
) ||
!isset($cm->course
)) {
1074 throw new coding_exception('Invalid $cm. It has to be instance of cm_info or record from the course_modules table.');
1077 if (!$this->_course ||
$this->_course
->id
!= $cm->course
) {
1079 $course = $DB->get_record('course', array('id' => $cm->course
), '*', MUST_EXIST
);
1081 if ($course->id
!= $cm->course
) {
1082 throw new coding_exception('The course you passed to $PAGE->set_cm does not correspond to the $cm.');
1084 $this->set_course($course);
1087 // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
1088 if (!($cm instanceof cm_info
)) {
1089 $modinfo = get_fast_modinfo($this->_course
);
1090 $cm = $modinfo->get_cm($cm->id
);
1094 // Unfortunately the context setting is a mess.
1095 // Let's try to work around some common block problems and show some debug messages.
1096 if (empty($this->_context
) or $this->_context
->contextlevel
!= CONTEXT_BLOCK
) {
1097 $context = context_module
::instance($cm->id
);
1098 $this->set_context($context);
1102 $this->set_activity_record($module);
1105 // Notify course format that this page is set for the course module.
1106 if ($this->_course
->id
!= $SITE->id
) {
1107 require_once($CFG->dirroot
.'/course/lib.php');
1108 course_get_format($this->_course
)->page_set_cm($this);
1113 * Sets the activity record. This could be a row from the main table for a
1114 * module. For instance if the current module (cm) is a forum this should be a row
1115 * from the forum table.
1117 * @param stdClass $module A row from the main database table for the module that this page belongs to.
1118 * @throws coding_exception
1120 public function set_activity_record($module) {
1121 if (is_null($this->_cm
)) {
1122 throw new coding_exception('You cannot call $PAGE->set_activity_record until after $PAGE->cm has been set.');
1124 if ($module->id
!= $this->_cm
->instance ||
$module->course
!= $this->_course
->id
) {
1125 throw new coding_exception('The activity record does not seem to correspond to the cm that has been set.');
1127 $this->_module
= $module;
1131 * Sets the pagetype to use for this page.
1133 * Normally you do not need to set this manually, it is automatically created
1134 * from the script name. However, on some pages this is overridden.
1135 * For example the page type for course/view.php includes the course format,
1136 * for example 'course-view-weeks'. This gets used as the id attribute on
1137 * <body> and also for determining which blocks are displayed.
1139 * @param string $pagetype e.g. 'my-index' or 'mod-quiz-attempt'.
1141 public function set_pagetype($pagetype) {
1142 $this->_pagetype
= $pagetype;
1146 * Sets the layout to use for this page.
1148 * The page layout determines how the page will be displayed, things such as
1149 * block regions, content areas, etc are controlled by the layout.
1150 * The theme in use for the page will determine that the layout contains.
1152 * This properly defaults to 'base', so you only need to call this function if
1153 * you want something different. The exact range of supported layouts is specified
1154 * in the standard theme.
1156 * For an idea of the common page layouts see
1157 * {@link http://docs.moodle.org/dev/Themes_2.0#The_different_layouts_as_of_August_17th.2C_2010}
1158 * But please keep in mind that it may be (and normally is) out of date.
1159 * The only place to find an accurate up-to-date list of the page layouts
1160 * available for your version of Moodle is {@link theme/base/config.php}
1162 * @param string $pagelayout the page layout this is. For example 'popup', 'home'.
1164 public function set_pagelayout($pagelayout) {
1167 if (!empty($SESSION->forcepagelayout
)) {
1168 $this->_pagelayout
= $SESSION->forcepagelayout
;
1170 // Uncomment this to debug theme pagelayout issues like missing blocks.
1171 // if (!empty($this->_wherethemewasinitialised) && $pagelayout != $this->_pagelayout)
1172 // debugging('Page layout has already been set and cannot be changed.', DEBUG_DEVELOPER);
1173 $this->_pagelayout
= $pagelayout;
1178 * If context->id and pagetype are not enough to uniquely identify this page,
1179 * then you can set a subpage id as well. For example, the tags page sets
1181 * @param string $subpage an arbitrary identifier that, along with context->id
1182 * and pagetype, uniquely identifies this page.
1184 public function set_subpage($subpage) {
1185 if (empty($subpage)) {
1186 $this->_subpage
= '';
1188 $this->_subpage
= $subpage;
1193 * Adds a CSS class to the body tag of the page.
1195 * @param string $class add this class name ot the class attribute on the body tag.
1196 * @throws coding_exception
1198 public function add_body_class($class) {
1199 if ($this->_state
> self
::STATE_BEFORE_HEADER
) {
1200 throw new coding_exception('Cannot call moodle_page::add_body_class after output has been started.');
1202 $this->_bodyclasses
[$class] = 1;
1206 * Adds an array of body classes to the body tag of this page.
1208 * @param array $classes this utility method calls add_body_class for each array element.
1210 public function add_body_classes($classes) {
1211 foreach ($classes as $class) {
1212 $this->add_body_class($class);
1217 * Sets the title for the page.
1218 * This is normally used within the title tag in the head of the page.
1220 * @param string $title the title that should go in the <head> section of the HTML of this page.
1222 public function set_title($title) {
1223 $title = format_string($title);
1224 $title = strip_tags($title);
1225 $title = str_replace('"', '"', $title);
1226 $this->_title
= $title;
1230 * Sets the heading to use for the page.
1231 * This is normally used as the main heading at the top of the content.
1233 * @param string $heading the main heading that should be displayed at the top of the <body>.
1235 public function set_heading($heading) {
1236 $this->_heading
= format_string($heading);
1240 * Sets some HTML to use next to the heading {@link moodle_page::set_heading()}
1242 * @param string $menu The menu/content to show in the heading
1244 public function set_headingmenu($menu) {
1245 $this->_headingmenu
= $menu;
1249 * Set the course category this page belongs to manually.
1251 * This automatically sets $PAGE->course to be the site course. You cannot
1252 * use this method if you have already set $PAGE->course - in that case,
1253 * the category must be the one that the course belongs to. This also
1254 * automatically sets the page context to the category context.
1256 * @param int $categoryid The id of the category to set.
1257 * @throws coding_exception
1259 public function set_category_by_id($categoryid) {
1261 if (!is_null($this->_course
)) {
1262 throw new coding_exception('Course has already been set. You cannot change the category now.');
1264 if (is_array($this->_categories
)) {
1265 throw new coding_exception('Course category has already been set. You cannot to change it now.');
1267 $this->ensure_theme_not_set();
1268 $this->set_course($SITE);
1269 $this->load_category($categoryid);
1270 $this->set_context(context_coursecat
::instance($categoryid));
1274 * Set a different path to use for the 'Moodle docs for this page' link.
1276 * By default, it uses the pagetype, which is normally the same as the
1277 * script name. So, for example, for mod/quiz/attempt.php, pagetype is
1278 * mod-quiz-attempt, and so docspath is mod/quiz/attempt.
1280 * @param string $path the path to use at the end of the moodle docs URL.
1282 public function set_docs_path($path) {
1283 $this->_docspath
= $path;
1287 * You should call this method from every page to set the URL that should be used to return to this page.
1289 * Used, for example, by the blocks editing UI to know where to return the
1290 * user after an action.
1291 * For example, course/view.php does:
1292 * $id = optional_param('id', 0, PARAM_INT);
1293 * $PAGE->set_url('/course/view.php', array('id' => $id));
1295 * @param moodle_url|string $url URL relative to $CFG->wwwroot or {@link moodle_url} instance
1296 * @param array $params parameters to add to the URL
1297 * @throws coding_exception
1299 public function set_url($url, array $params = null) {
1302 if (is_string($url) && strpos($url, 'http') !== 0) {
1303 if (strpos($url, '/') === 0) {
1304 // Add the wwwroot to the relative url.
1305 $url = $CFG->wwwroot
. $url;
1307 throw new coding_exception('Invalid parameter $url, has to be full url or in shortened form starting with /.');
1311 $this->_url
= new moodle_url($url, $params);
1313 $fullurl = $this->_url
->out_omit_querystring();
1314 if (strpos($fullurl, "$CFG->wwwroot/") !== 0) {
1315 debugging('Most probably incorrect set_page() url argument, it does not match the wwwroot!');
1317 $shorturl = str_replace("$CFG->wwwroot/", '', $fullurl);
1319 if (is_null($this->_pagetype
)) {
1320 $this->initialise_default_pagetype($shorturl);
1325 * Make sure page URL does not contain the given URL parameter.
1327 * This should not be necessary if the script has called set_url properly.
1328 * However, in some situations like the block editing actions; when the URL
1329 * has been guessed, it will contain dangerous block-related actions.
1330 * Therefore, the blocks code calls this function to clean up such parameters
1331 * before doing any redirect.
1333 * @param string $param the name of the parameter to make sure is not in the
1336 public function ensure_param_not_in_url($param) {
1337 $this->_url
->remove_params($param);
1341 * Sets an alternative version of this page.
1343 * There can be alternate versions of some pages (for example an RSS feed version).
1344 * Call this method for each alternative version available.
1345 * For each alternative version a link will be included in the <head> tag.
1347 * @param string $title The title to give the alternate version.
1348 * @param string|moodle_url $url The URL of the alternate version.
1349 * @param string $mimetype The mime-type of the alternate version.
1350 * @throws coding_exception
1352 public function add_alternate_version($title, $url, $mimetype) {
1353 if ($this->_state
> self
::STATE_BEFORE_HEADER
) {
1354 throw new coding_exception('Cannot call moodle_page::add_alternate_version after output has been started.');
1356 $alt = new stdClass
;
1357 $alt->title
= $title;
1359 $this->_alternateversions
[$mimetype] = $alt;
1363 * Specify a form control should be focused when the page has loaded.
1365 * @param string $controlid the id of the HTML element to be focused.
1367 public function set_focuscontrol($controlid) {
1368 $this->_focuscontrol
= $controlid;
1372 * Specify a fragment of HTML that goes where the 'Turn editing on' button normally goes.
1374 * @param string $html the HTML to display there.
1376 public function set_button($html) {
1377 $this->_button
= $html;
1381 * Set the capability that allows users to edit blocks on this page.
1383 * Normally the default of 'moodle/site:manageblocks' is used, but a few
1384 * pages like the My Moodle page need to use a different capability
1385 * like 'moodle/my:manageblocks'.
1387 * @param string $capability a capability.
1389 public function set_blocks_editing_capability($capability) {
1390 $this->_blockseditingcap
= $capability;
1394 * Some pages let you turn editing on for reasons other than editing blocks.
1395 * If that is the case, you can pass other capabilities that let the user
1396 * edit this page here.
1398 * @param string|array $capability either a capability, or an array of capabilities.
1400 public function set_other_editing_capability($capability) {
1401 if (is_array($capability)) {
1402 $this->_othereditingcaps
= array_unique($this->_othereditingcaps +
$capability);
1404 $this->_othereditingcaps
[] = $capability;
1409 * Sets whether the browser should cache this page or not.
1411 * @param bool $cacheable can this page be cached by the user's browser.
1413 public function set_cacheable($cacheable) {
1414 $this->_cacheable
= $cacheable;
1418 * Sets the page to periodically refresh
1420 * This function must be called before $OUTPUT->header has been called or
1421 * a coding exception will be thrown.
1423 * @param int $delay Sets the delay before refreshing the page, if set to null refresh is cancelled.
1424 * @throws coding_exception
1426 public function set_periodic_refresh_delay($delay = null) {
1427 if ($this->_state
> self
::STATE_BEFORE_HEADER
) {
1428 throw new coding_exception('You cannot set a periodic refresh delay after the header has been printed');
1430 if ($delay === null) {
1431 $this->_periodicrefreshdelay
= null;
1432 } else if (is_int($delay)) {
1433 $this->_periodicrefreshdelay
= $delay;
1438 * Force this page to use a particular theme.
1440 * Please use this cautiously.
1441 * It is only intended to be used by the themes selector admin page.
1443 * @param string $themename the name of the theme to use.
1445 public function force_theme($themename) {
1446 $this->ensure_theme_not_set();
1447 $this->_theme
= theme_config
::load($themename);
1451 * Reload theme settings.
1453 * This is used when we need to reset settings
1454 * because they are now double cached in theme.
1456 public function reload_theme() {
1457 if (!is_null($this->_theme
)) {
1458 $this->_theme
= theme_config
::load($this->_theme
->name
);
1463 * This function indicates that current page requires the https when $CFG->loginhttps enabled.
1464 * Since loginhttps was removed this is no longer required or functional.
1466 * @deprecated since Moodle 3.4 MDL-42834 - please do not use this function any more.
1467 * @todo MDL-46267 This will be deleted in Moodle 3.8
1469 * @throws coding_exception
1471 public function https_required() {
1472 debugging('https_required() has been deprecated. It no longer needs to be called.', DEBUG_DEVELOPER
);
1476 * Makes sure that page previously marked with https_required() is really using https://, if not it redirects to https://
1477 * Since loginhttps was removed this is no longer required or functional.
1479 * @deprecated since Moodle 3.4 MDL-42834 - please do not use this function any more.
1480 * @todo MDL-46267 This will be deleted in Moodle 3.8
1482 * @throws coding_exception
1484 public function verify_https_required() {
1485 debugging('verify_https_required() has been deprecated. It no longer needs to be called.', DEBUG_DEVELOPER
);
1488 // Initialisation methods =====================================================
1489 // These set various things up in a default way.
1492 * This method is called when the page first moves out of the STATE_BEFORE_HEADER
1493 * state. This is our last change to initialise things.
1495 protected function starting_output() {
1498 if (!during_initial_install()) {
1499 $this->blocks
->load_blocks();
1500 if (empty($this->_block_actions_done
)) {
1501 $this->_block_actions_done
= true;
1502 if ($this->blocks
->process_url_actions($this)) {
1503 redirect($this->url
->out(false));
1506 $this->blocks
->create_all_block_instances();
1509 // If maintenance mode is on, change the page header.
1510 if (!empty($CFG->maintenance_enabled
)) {
1511 $this->set_button('<a href="' . $CFG->wwwroot
. '/' . $CFG->admin
.
1512 '/settings.php?section=maintenancemode">' . get_string('maintenancemode', 'admin') .
1513 '</a> ' . $this->button
);
1515 $title = $this->title
;
1519 $this->set_title($title . get_string('maintenancemode', 'admin'));
1522 $this->initialise_standard_body_classes();
1526 * Method for use by Moodle core to set up the theme. Do not
1527 * use this in your own code.
1529 * Make sure the right theme for this page is loaded. Tell our
1530 * blocks_manager about the theme block regions, and then, if
1531 * we are $PAGE, set up the global $OUTPUT.
1535 public function initialise_theme_and_output() {
1536 global $OUTPUT, $PAGE, $SITE, $CFG;
1538 if (!empty($this->_wherethemewasinitialised
)) {
1542 if (!during_initial_install()) {
1543 // Detect PAGE->context mess.
1544 $this->magic_get_context();
1547 if (!$this->_course
&& !during_initial_install()) {
1548 $this->set_course($SITE);
1551 if (is_null($this->_theme
)) {
1552 $themename = $this->resolve_theme();
1553 $this->_theme
= theme_config
::load($themename);
1556 $this->_theme
->setup_blocks($this->pagelayout
, $this->blocks
);
1557 if ($this->_theme
->enable_dock
&& !empty($CFG->allowblockstodock
)) {
1558 $this->requires
->strings_for_js(array('addtodock', 'undockitem', 'dockblock', 'undockblock', 'undockall', 'hidedockpanel', 'hidepanel'), 'block');
1559 $this->requires
->string_for_js('thisdirectionvertical', 'langconfig');
1560 $this->requires
->yui_module('moodle-core-dock-loader', 'M.core.dock.loader.initLoader');
1563 if ($this === $PAGE) {
1565 if ($this->pagelayout
=== 'maintenance') {
1566 // If the page is using the maintenance layout then we're going to force target to maintenance.
1567 // This leads to a special core renderer that is designed to block access to API's that are likely unavailable for this
1569 $target = RENDERER_TARGET_MAINTENANCE
;
1571 $OUTPUT = $this->get_renderer('core', null, $target);
1574 if (!during_initial_install()) {
1575 $filtermanager = filter_manager
::instance();
1576 $filtermanager->setup_page_for_globally_available_filters($this);
1579 $this->_wherethemewasinitialised
= debug_backtrace();
1583 * Reset the theme and output for a new context. This only makes sense from
1584 * external::validate_context(). Do not cheat.
1586 * @return string the name of the theme that should be used on this page.
1588 public function reset_theme_and_output() {
1589 global $COURSE, $SITE;
1591 $COURSE = clone($SITE);
1592 $this->_theme
= null;
1593 $this->_wherethemewasinitialised
= null;
1594 $this->_course
= null;
1596 $this->_module
= null;
1597 $this->_context
= null;
1601 * Work out the theme this page should use.
1603 * This depends on numerous $CFG settings, and the properties of this page.
1605 * @return string the name of the theme that should be used on this page.
1607 protected function resolve_theme() {
1608 global $CFG, $USER, $SESSION;
1610 if (empty($CFG->themeorder
)) {
1611 $themeorder = array('course', 'category', 'session', 'user', 'cohort', 'site');
1613 $themeorder = $CFG->themeorder
;
1614 // Just in case, make sure we always use the site theme if nothing else matched.
1615 $themeorder[] = 'site';
1618 $mnetpeertheme = '';
1619 if (isloggedin() and isset($CFG->mnet_localhost_id
) and $USER->mnethostid
!= $CFG->mnet_localhost_id
) {
1620 require_once($CFG->dirroot
.'/mnet/peer.php');
1621 $mnetpeer = new mnet_peer();
1622 $mnetpeer->set_id($USER->mnethostid
);
1623 if ($mnetpeer->force_theme
== 1 && $mnetpeer->theme
!= '') {
1624 $mnetpeertheme = $mnetpeer->theme
;
1628 $devicetheme = core_useragent
::get_device_type_theme($this->devicetypeinuse
);
1630 // The user is using another device than default, and we have a theme for that, we should use it.
1631 $hascustomdevicetheme = core_useragent
::DEVICETYPE_DEFAULT
!= $this->devicetypeinuse
&& !empty($devicetheme);
1633 foreach ($themeorder as $themetype) {
1635 switch ($themetype) {
1637 if (!empty($CFG->allowcoursethemes
) && !empty($this->_course
->theme
) && !$hascustomdevicetheme) {
1638 return $this->_course
->theme
;
1643 if (!empty($CFG->allowcategorythemes
) && !$hascustomdevicetheme) {
1644 $categories = $this->categories
;
1645 foreach ($categories as $category) {
1646 if (!empty($category->theme
)) {
1647 return $category->theme
;
1654 if (!empty($SESSION->theme
)) {
1655 return $SESSION->theme
;
1660 if (!empty($CFG->allowuserthemes
) && !empty($USER->theme
) && !$hascustomdevicetheme) {
1661 if ($mnetpeertheme) {
1662 return $mnetpeertheme;
1664 return $USER->theme
;
1670 if (!empty($CFG->allowcohortthemes
) && !empty($USER->cohorttheme
) && !$hascustomdevicetheme) {
1671 return $USER->cohorttheme
;
1676 if ($mnetpeertheme) {
1677 return $mnetpeertheme;
1679 // First try for the device the user is using.
1680 if (!empty($devicetheme)) {
1681 return $devicetheme;
1683 // Next try for the default device (as a fallback).
1684 $devicetheme = core_useragent
::get_device_type_theme(core_useragent
::DEVICETYPE_DEFAULT
);
1685 if (!empty($devicetheme)) {
1686 return $devicetheme;
1688 // The default device theme isn't set up - use the overall default theme.
1689 return theme_config
::DEFAULT_THEME
;
1693 // We should most certainly have resolved a theme by now. Something has gone wrong.
1694 debugging('Error resolving the theme to use for this page.', DEBUG_DEVELOPER
);
1695 return theme_config
::DEFAULT_THEME
;
1700 * Sets ->pagetype from the script name. For example, if the script that was
1701 * run is mod/quiz/view.php, ->pagetype will be set to 'mod-quiz-view'.
1703 * @param string $script the path to the script that should be used to
1704 * initialise ->pagetype. If not passed the $SCRIPT global will be used.
1705 * If legacy code has set $CFG->pagepath that will be used instead, and a
1706 * developer warning issued.
1708 protected function initialise_default_pagetype($script = null) {
1709 global $CFG, $SCRIPT;
1711 if (isset($CFG->pagepath
)) {
1712 debugging('Some code appears to have set $CFG->pagepath. That was a horrible deprecated thing. ' .
1713 'Don\'t do it! Try calling $PAGE->set_pagetype() instead.');
1714 $script = $CFG->pagepath
;
1715 unset($CFG->pagepath
);
1718 if (is_null($script)) {
1719 $script = ltrim($SCRIPT, '/');
1720 $len = strlen($CFG->admin
);
1721 if (substr($script, 0, $len) == $CFG->admin
) {
1722 $script = 'admin' . substr($script, $len);
1726 $path = str_replace('.php', '', $script);
1727 if (substr($path, -1) == '/') {
1731 if (empty($path) ||
$path == 'index') {
1732 $this->_pagetype
= 'site-index';
1734 $this->_pagetype
= str_replace('/', '-', $path);
1739 * Initialises the CSS classes that will be added to body tag of the page.
1741 * The function is responsible for adding all of the critical CSS classes
1742 * that describe the current page, and its state.
1743 * This includes classes that describe the following for example:
1744 * - Current language
1745 * - Language direction
1746 * - YUI CSS initialisation
1748 * These are commonly used in CSS to target specific types of pages.
1750 protected function initialise_standard_body_classes() {
1753 $pagetype = $this->pagetype
;
1754 if ($pagetype == 'site-index') {
1755 $this->_legacyclass
= 'course';
1756 } else if (substr($pagetype, 0, 6) == 'admin-') {
1757 $this->_legacyclass
= 'admin';
1759 $this->add_body_class($this->_legacyclass
);
1761 $pathbits = explode('-', trim($pagetype));
1762 for ($i = 1; $i < count($pathbits); $i++
) {
1763 $this->add_body_class('path-' . join('-', array_slice($pathbits, 0, $i)));
1766 $this->add_body_classes(core_useragent
::get_browser_version_classes());
1767 $this->add_body_class('dir-' . get_string('thisdirection', 'langconfig'));
1768 $this->add_body_class('lang-' . current_language());
1769 $this->add_body_class('yui-skin-sam'); // Make YUI happy, if it is used.
1770 $this->add_body_class('yui3-skin-sam'); // Make YUI3 happy, if it is used.
1771 $this->add_body_class($this->url_to_class_name($CFG->wwwroot
));
1773 // Extra class describing current page layout.
1774 $this->add_body_class('pagelayout-' . $this->_pagelayout
);
1776 if (!during_initial_install()) {
1777 $this->add_body_class('course-' . $this->_course
->id
);
1778 $this->add_body_class('context-' . $this->_context
->id
);
1781 if (!empty($this->_cm
)) {
1782 $this->add_body_class('cmid-' . $this->_cm
->id
);
1785 if (!empty($CFG->allowcategorythemes
)) {
1786 $this->ensure_category_loaded();
1787 foreach ($this->_categories
as $catid => $notused) {
1788 $this->add_body_class('category-' . $catid);
1792 if (is_array($this->_categories
)) {
1793 $catids = array_keys($this->_categories
);
1794 $catid = reset($catids);
1795 } else if (!empty($this->_course
->category
)) {
1796 $catid = $this->_course
->category
;
1799 $this->add_body_class('category-' . $catid);
1803 if (!isloggedin()) {
1804 $this->add_body_class('notloggedin');
1807 if ($this->user_is_editing()) {
1808 $this->add_body_class('editing');
1809 if (optional_param('bui_moveid', false, PARAM_INT
)) {
1810 $this->add_body_class('blocks-moving');
1814 if (!empty($CFG->blocksdrag
)) {
1815 $this->add_body_class('drag');
1818 if ($this->_devicetypeinuse
!= 'default') {
1819 $this->add_body_class($this->_devicetypeinuse
. 'theme');
1822 // Add class for behat site to apply behat related fixes.
1823 if (defined('BEHAT_SITE_RUNNING')) {
1824 $this->add_body_class('behat-site');
1829 * Loads the activity record for the current CM object associated with this
1832 * This will load {@link moodle_page::$_module} with a row from the related
1833 * module table in the database.
1834 * For instance if {@link moodle_page::$_cm} is a forum then a row from the
1835 * forum table will be loaded.
1837 protected function load_activity_record() {
1839 if (is_null($this->_cm
)) {
1842 $this->_module
= $DB->get_record($this->_cm
->modname
, array('id' => $this->_cm
->instance
));
1846 * This function ensures that the category of the current course has been
1847 * loaded, and if not, the function loads it now.
1850 * @throws coding_exception
1852 protected function ensure_category_loaded() {
1853 if (is_array($this->_categories
)) {
1854 return; // Already done.
1856 if (is_null($this->_course
)) {
1857 throw new coding_exception('Attempt to get the course category for this page before the course was set.');
1859 if ($this->_course
->category
== 0) {
1860 $this->_categories
= array();
1862 $this->load_category($this->_course
->category
);
1867 * Loads the requested category into the pages categories array.
1869 * @param int $categoryid
1870 * @throws moodle_exception
1872 protected function load_category($categoryid) {
1874 $category = $DB->get_record('course_categories', array('id' => $categoryid));
1876 throw new moodle_exception('unknowncategory');
1878 $this->_categories
[$category->id
] = $category;
1879 $parentcategoryids = explode('/', trim($category->path
, '/'));
1880 array_pop($parentcategoryids);
1881 foreach (array_reverse($parentcategoryids) as $catid) {
1882 $this->_categories
[$catid] = null;
1887 * Ensures that the category the current course is within, as well as all of
1888 * its parent categories, have been loaded.
1892 protected function ensure_categories_loaded() {
1894 $this->ensure_category_loaded();
1895 if (!is_null(end($this->_categories
))) {
1896 return; // Already done.
1898 $idstoload = array_keys($this->_categories
);
1899 array_shift($idstoload);
1900 $categories = $DB->get_records_list('course_categories', 'id', $idstoload);
1901 foreach ($idstoload as $catid) {
1902 $this->_categories
[$catid] = $categories[$catid];
1907 * Ensure the theme has not been loaded yet. If it has an exception is thrown.
1909 * @throws coding_exception
1911 protected function ensure_theme_not_set() {
1912 // This is explicitly allowed for webservices though which may process many course contexts in a single request.
1917 if (!is_null($this->_theme
)) {
1918 throw new coding_exception('The theme has already been set up for this page ready for output. ' .
1919 'Therefore, you can no longer change the theme, or anything that might affect what ' .
1920 'the current theme is, for example, the course.',
1921 'Stack trace when the theme was set up: ' . format_backtrace($this->_wherethemewasinitialised
));
1926 * Converts the provided URL into a CSS class that be used within the page.
1927 * This is primarily used to add the wwwroot to the body tag as a CSS class.
1929 * @param string $url
1932 protected function url_to_class_name($url) {
1933 $bits = parse_url($url);
1934 $class = str_replace('.', '-', $bits['host']);
1935 if (!empty($bits['port'])) {
1936 $class .= '--' . $bits['port'];
1938 if (!empty($bits['path'])) {
1939 $path = trim($bits['path'], '/');
1941 $class .= '--' . str_replace('/', '-', $path);
1948 * Combines all of the required editing caps for the page and returns them
1953 protected function all_editing_caps() {
1954 $caps = $this->_othereditingcaps
;
1955 $caps[] = $this->_blockseditingcap
;
1960 * Returns true if the page URL has beem set.
1964 public function has_set_url() {
1965 return ($this->_url
!==null);
1969 * Gets set when the block actions for the page have been processed.
1971 * @param bool $setting
1973 public function set_block_actions_done($setting = true) {
1974 $this->_block_actions_done
= $setting;
1978 * Are popup notifications allowed on this page?
1979 * Popup notifications may be disallowed in situations such as while upgrading or completing a quiz
1981 * @return bool true if popup notifications may be displayed
1983 public function get_popup_notification_allowed() {
1984 return $this->_popup_notification_allowed
;
1988 * Allow or disallow popup notifications on this page. Popups are allowed by default.
1990 * @param bool $allowed true if notifications are allowed. False if not allowed. They are allowed by default.
1992 public function set_popup_notification_allowed($allowed) {
1993 $this->_popup_notification_allowed
= $allowed;
1997 * Returns the block region having made any required theme manipulations.
1999 * @since Moodle 2.5.1 2.6
2000 * @param string $region
2003 public function apply_theme_region_manipulations($region) {
2004 if ($this->blockmanipulations
&& isset($this->blockmanipulations
[$region])) {
2005 $regionwas = $region;
2006 $regionnow = $this->blockmanipulations
[$region];
2007 if ($this->blocks
->is_known_region($regionwas) && $this->blocks
->is_known_region($regionnow)) {
2008 // Both the before and after regions are known so we can swap them over.
2011 // We didn't know about both, we won't swap them over.
2018 * Add a report node and a specific report to the navigation.
2020 * @param int $userid The user ID that we are looking to add this report node to.
2021 * @param array $nodeinfo Name and url of the final node that we are creating.
2023 public function add_report_nodes($userid, $nodeinfo) {
2025 // Try to find the specific user node.
2026 $newusernode = $this->navigation
->find('user' . $userid, null);
2028 $navigationnodeerror =
2029 'Could not find the navigation node requested. Please check that the node you are looking for exists.';
2030 if ($userid != $USER->id
) {
2031 // Check that we have a valid node.
2032 if (empty($newusernode)) {
2033 // Throw an error if we ever reach here.
2034 throw new coding_exception($navigationnodeerror);
2036 // Add 'Reports' to the user node.
2037 $reportnode = $newusernode->add(get_string('reports'));
2039 // We are looking at our own profile.
2040 $myprofilenode = $this->settingsnav
->find('myprofile', null);
2041 // Check that we do end up with a valid node.
2042 if (empty($myprofilenode)) {
2043 // Throw an error if we ever reach here.
2044 throw new coding_exception($navigationnodeerror);
2046 // Add 'Reports' to our node.
2047 $reportnode = $myprofilenode->add(get_string('reports'));
2049 // Finally add the report to the navigation tree.
2050 $reportnode->add($nodeinfo['name'], $nodeinfo['url'], navigation_node
::TYPE_COURSE
);