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 blocks_manager $blocks The blocks manager object for this page.
55 * @property-read string $bodyclasses A string to use within the class attribute on the body tag.
56 * @property-read string $bodyid A string to use as the id of the body tag.
57 * @property-read string $button The HTML to go where the Turn editing on button normally goes.
58 * @property-read bool $cacheable Defaults to true. Set to false to stop the page being cached at all.
59 * @property-read array $categories An array of all the categories the page course belongs to,
60 * starting with the immediately containing category, and working out to
61 * the top-level category. This may be the empty array if we are in the
63 * @property-read mixed $category The category that the page course belongs to.
64 * @property-read cm_info $cm The course_module that this page belongs to. Will be null
65 * if this page is not within a module. This is a full cm object, as loaded
66 * by get_coursemodule_from_id or get_coursemodule_from_instance,
67 * so the extra modname and name fields are present.
68 * @property-read context $context The main context to which this page belongs.
69 * @property-read stdClass $course The current course that we are inside - a row from the
70 * course table. (Also available as $COURSE global.) If we are not inside
71 * an actual course, this will be the site course.
72 * @property-read string $devicetypeinuse The name of the device type in use
73 * @property-read string $docspath The path to the Moodle docs for this page.
74 * @property-read string $focuscontrol The id of the HTML element to be focused when the page has loaded.
75 * @property-read bool $headerprinted True if the page header has already been printed.
76 * @property-read string $heading The main heading that should be displayed at the top of the <body>.
77 * @property-read string $headingmenu The menu (or actions) to display in the heading
78 * @property-read array $layout_options An arrays with options for the layout file.
79 * @property-read array $legacythemeinuse True if the legacy browser theme is in use.
80 * @property-read navbar $navbar The navbar object used to display the navbar
81 * @property-read global_navigation $navigation The navigation structure for this page.
82 * @property-read xml_container_stack $opencontainers Tracks XHTML tags on this page that have been opened but not closed.
83 * mainly for internal use by the rendering code.
84 * @property-read string $pagelayout The general type of page this is. For example 'normal', 'popup', 'home'.
85 * Allows the theme to display things differently, if it wishes to.
86 * @property-read string $pagetype The page type string, should be used as the id for the body tag in the theme.
87 * @property-read int $periodicrefreshdelay The periodic refresh delay to use with meta refresh
88 * @property-read page_requirements_manager $requires Tracks the JavaScript, CSS files, etc. required by this page.
89 * @property-read settings_navigation $settingsnav The settings navigation
90 * @property-read int $state One of the STATE_... constants
91 * @property-read string $subpage The subpage identifier, if any.
92 * @property-read theme_config $theme The theme for this page.
93 * @property-read string $title The title that should go in the <head> section of the HTML of this page.
94 * @property-read moodle_url $url The moodle url object for this page.
98 /** The state of the page before it has printed the header **/
99 const STATE_BEFORE_HEADER
= 0;
101 /** The state the page is in temporarily while the header is being printed **/
102 const STATE_PRINTING_HEADER
= 1;
104 /** The state the page is in while content is presumably being printed **/
105 const STATE_IN_BODY
= 2;
108 * The state the page is when the footer has been printed and its function is
111 const STATE_DONE
= 3;
114 * @var int The current state of the page. The state a page is within
115 * determines what actions are possible for it.
117 protected $_state = self
::STATE_BEFORE_HEADER
;
120 * @var stdClass The course currently associated with this page.
121 * If not has been provided the front page course is used.
123 protected $_course = null;
126 * @var cm_info If this page belongs to a module, this is the cm_info module
127 * description object.
129 protected $_cm = null;
132 * @var stdClass If $_cm is not null, then this will hold the corresponding
133 * row from the modname table. For example, if $_cm->modname is 'quiz', this
134 * will be a row from the quiz table.
136 protected $_module = null;
139 * @var context The context that this page belongs to.
141 protected $_context = null;
144 * @var array This holds any categories that $_course belongs to, starting with the
145 * particular category it belongs to, and working out through any parent
146 * categories to the top level. These are loaded progressively, if needed.
147 * There are three states. $_categories = null initially when nothing is
148 * loaded; $_categories = array($id => $cat, $parentid => null) when we have
149 * loaded $_course->category, but not any parents; and a complete array once
150 * everything is loaded.
152 protected $_categories = null;
155 * @var array An array of CSS classes that should be added to the body tag in HTML.
157 protected $_bodyclasses = array();
160 * @var string The title for the page. Used within the title tag in the HTML head.
162 protected $_title = '';
165 * @var string The string to use as the heading of the page. Shown near the top of the
166 * page within most themes.
168 protected $_heading = '';
171 * @var string The pagetype is used to describe the page and defaults to a representation
172 * of the physical path to the page e.g. my-index, mod-quiz-attempt
174 protected $_pagetype = null;
177 * @var string The pagelayout to use when displaying this page. The
178 * pagelayout needs to have been defined by the theme in use, or one of its
179 * parents. By default base is used however standard is the more common layout.
180 * Note that this gets automatically set by core during operations like
183 protected $_pagelayout = 'base';
186 * @var array List of theme layout options, these are ignored by core.
187 * To be used in individual theme layout files only.
189 protected $_layout_options = null;
192 * @var string An optional arbitrary parameter that can be set on pages where the context
193 * and pagetype is not enough to identify the page.
195 protected $_subpage = '';
198 * @var string Set a different path to use for the 'Moodle docs for this page' link.
199 * By default, it uses the path of the file for instance mod/quiz/attempt.
201 protected $_docspath = null;
204 * @var string A legacy class that will be added to the body tag
206 protected $_legacyclass = null;
209 * @var moodle_url The URL for this page. This is mandatory and must be set
210 * before output is started.
212 protected $_url = null;
215 * @var array An array of links to alternative versions of this page.
216 * Primarily used for RSS versions of the current page.
218 protected $_alternateversions = array();
221 * @var block_manager The blocks manager for this page. It is reponsible for
222 * the blocks and there content on this page.
224 protected $_blocks = null;
227 * @var page_requirements_manager Page requirements manager. It is reponsible
228 * for all JavaScript and CSS resources required by this page.
230 protected $_requires = null;
233 * @var string The capability required by the user in order to edit blocks
234 * and block settings on this page.
236 protected $_blockseditingcap = 'moodle/site:manageblocks';
239 * @var bool An internal flag to record when block actions have been processed.
240 * Remember block actions occur on the current URL and it is important that
241 * even they are never executed more than once.
243 protected $_block_actions_done = false;
246 * @var array An array of any other capabilities the current user must have
247 * in order to editing the page and/or its content (not just blocks).
249 protected $_othereditingcaps = array();
252 * @var bool Sets whether this page should be cached by the browser or not.
253 * If it is set to true (default) the page is served with caching headers.
255 protected $_cacheable = true;
258 * @var string Can be set to the ID of an element on the page, if done that
259 * element receives focus when the page loads.
261 protected $_focuscontrol = '';
264 * @var string HTML to go where the turn on editing button is located. This
265 * is nearly a legacy item and not used very often any more.
267 protected $_button = '';
270 * @var theme_config The theme to use with this page. This has to be properly
271 * initialised via {@link moodle_page::initialise_theme_and_output()} which
272 * happens magically before any operation that requires it.
274 protected $_theme = null;
277 * @var global_navigation Contains the global navigation structure.
279 protected $_navigation = null;
282 * @var settings_navigation Contains the settings navigation structure.
284 protected $_settingsnav = null;
287 * @var navbar Contains the navbar structure.
289 protected $_navbar = null;
292 * @var string The menu (or actions) to display in the heading.
294 protected $_headingmenu = null;
297 * @var array stack trace. Then the theme is initialised, we save the stack
298 * trace, for use in error messages.
300 protected $_wherethemewasinitialised = null;
303 * @var xhtml_container_stack Tracks XHTML tags on this page that have been
304 * opened but not closed.
306 protected $_opencontainers;
309 * @var int Sets the page to refresh after a given delay (in seconds) using
310 * meta refresh in {@link standard_head_html()} in outputlib.php
311 * If set to null(default) the page is not refreshed
313 protected $_periodicrefreshdelay = null;
316 * @var stdClass This is simply to improve backwards compatibility. If old
317 * code relies on a page class that implements print_header, or complex logic
318 * in user_allowed_editing then we stash an instance of that other class here,
319 * and delegate to it in certain situations.
321 protected $_legacypageobject = 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;
347 // Magic getter methods =============================================================
348 // Due to the __get magic below, you normally do not call these as $PAGE->magic_get_x
349 // methods, but instead use the $PAGE->x syntax.
352 * Please do not call this method directly, use the ->state syntax. {@link moodle_page::__get()}.
353 * @return integer one of the STATE_XXX constants. You should not normally need
354 * to use this in your code. It is intended for internal use by this class
355 * and its friends like print_header, to check that everything is working as
356 * expected. Also accessible as $PAGE->state.
358 protected function magic_get_state() {
359 return $this->_state
;
363 * Please do not call this method directly, use the ->headerprinted syntax. {@link moodle_page::__get()}.
364 * @return bool has the header already been printed?
366 protected function magic_get_headerprinted() {
367 return $this->_state
>= self
::STATE_IN_BODY
;
371 * Please do not call this method directly, use the ->course syntax. {@link moodle_page::__get()}.
372 * @return stdClass the current course that we are inside - a row from the
373 * course table. (Also available as $COURSE global.) If we are not inside
374 * an actual course, this will be the site course.
376 protected function magic_get_course() {
378 if (is_null($this->_course
)) {
381 return $this->_course
;
385 * Please do not call this method directly, use the ->cm syntax. {@link moodle_page::__get()}.
386 * @return cm_info the course_module that this page belongs to. Will be null
387 * if this page is not within a module. This is a full cm object, as loaded
388 * by get_coursemodule_from_id or get_coursemodule_from_instance,
389 * so the extra modname and name fields are present.
391 protected function magic_get_cm() {
396 * Please do not call this method directly, use the ->activityrecord syntax. {@link moodle_page::__get()}.
397 * @return stdClass the row from the activities own database table (for example
398 * the forum or quiz table) that this page belongs to. Will be null
399 * if this page is not within a module.
401 protected function magic_get_activityrecord() {
402 if (is_null($this->_module
) && !is_null($this->_cm
)) {
403 $this->load_activity_record();
405 return $this->_module
;
409 * Please do not call this method directly, use the ->activityname syntax. {@link moodle_page::__get()}.
410 * @return string the The type of activity we are in, for example 'forum' or 'quiz'.
411 * Will be null if this page is not within a module.
413 protected function magic_get_activityname() {
414 if (is_null($this->_cm
)) {
417 return $this->_cm
->modname
;
421 * Please do not call this method directly, use the ->category syntax. {@link moodle_page::__get()}.
422 * @return stdClass the category that the page course belongs to. If there isn't one
423 * (that is, if this is the front page course) returns null.
425 protected function magic_get_category() {
426 $this->ensure_category_loaded();
427 if (!empty($this->_categories
)) {
428 return reset($this->_categories
);
435 * Please do not call this method directly, use the ->categories syntax. {@link moodle_page::__get()}.
436 * @return array an array of all the categories the page course belongs to,
437 * starting with the immediately containing category, and working out to
438 * the top-level category. This may be the empty array if we are in the
441 protected function magic_get_categories() {
442 $this->ensure_categories_loaded();
443 return $this->_categories
;
447 * Please do not call this method directly, use the ->context syntax. {@link moodle_page::__get()}.
448 * @return context the main context to which this page belongs.
450 protected function magic_get_context() {
451 if (is_null($this->_context
)) {
452 if (CLI_SCRIPT
or NO_MOODLE_COOKIES
) {
453 // cli scripts work in system context, do not annoy devs with debug info
454 // very few scripts do not use cookies, we can safely use system as default context there
456 debugging('Coding problem: $PAGE->context was not set. You may have forgotten '
457 .'to call require_login() or $PAGE->set_context(). The page may not display '
458 .'correctly as a result');
460 $this->_context
= get_context_instance(CONTEXT_SYSTEM
);
462 return $this->_context
;
466 * Please do not call this method directly, use the ->pagetype syntax. {@link moodle_page::__get()}.
467 * @return string e.g. 'my-index' or 'mod-quiz-attempt'.
469 protected function magic_get_pagetype() {
471 if (is_null($this->_pagetype
) ||
isset($CFG->pagepath
)) {
472 $this->initialise_default_pagetype();
474 return $this->_pagetype
;
478 * Please do not call this method directly, use the ->pagetype syntax. {@link moodle_page::__get()}.
479 * @return string The id to use on the body tag, uses {@link magic_get_pagetype()}.
481 protected function magic_get_bodyid() {
482 return 'page-'.$this->pagetype
;
486 * Please do not call this method directly, use the ->pagelayout syntax. {@link moodle_page::__get()}.
487 * @return string the general type of page this is. For example 'standard', 'popup', 'home'.
488 * Allows the theme to display things differently, if it wishes to.
490 protected function magic_get_pagelayout() {
491 return $this->_pagelayout
;
495 * Please do not call this method directly, use the ->layout_options syntax. {@link moodle_page::__get()}.
496 * @return array returns arrays with options for layout file
498 protected function magic_get_layout_options() {
499 if (!is_array($this->_layout_options
)) {
500 $this->_layout_options
= $this->_theme
->pagelayout_options($this->pagelayout
);
502 return $this->_layout_options
;
506 * Please do not call this method directly, use the ->subpage syntax. {@link moodle_page::__get()}.
507 * @return string The subpage identifier, if any.
509 protected function magic_get_subpage() {
510 return $this->_subpage
;
514 * Please do not call this method directly, use the ->bodyclasses syntax. {@link moodle_page::__get()}.
515 * @return string the class names to put on the body element in the HTML.
517 protected function magic_get_bodyclasses() {
518 return implode(' ', array_keys($this->_bodyclasses
));
522 * Please do not call this method directly, use the ->title syntax. {@link moodle_page::__get()}.
523 * @return string the title that should go in the <head> section of the HTML of this page.
525 protected function magic_get_title() {
526 return $this->_title
;
530 * Please do not call this method directly, use the ->heading syntax. {@link moodle_page::__get()}.
531 * @return string the main heading that should be displayed at the top of the <body>.
533 protected function magic_get_heading() {
534 return $this->_heading
;
538 * Please do not call this method directly, use the ->heading syntax. {@link moodle_page::__get()}.
539 * @return string The menu (or actions) to display in the heading
541 protected function magic_get_headingmenu() {
542 return $this->_headingmenu
;
546 * Please do not call this method directly, use the ->docspath syntax. {@link moodle_page::__get()}.
547 * @return string the path to the Moodle docs for this page.
549 protected function magic_get_docspath() {
550 if (is_string($this->_docspath
)) {
551 return $this->_docspath
;
553 return str_replace('-', '/', $this->pagetype
);
558 * Please do not call this method directly, use the ->url syntax. {@link moodle_page::__get()}.
559 * @return moodle_url the clean URL required to load the current page. (You
560 * should normally use this in preference to $ME or $FULLME.)
562 protected function magic_get_url() {
564 if (is_null($this->_url
)) {
565 debugging('This page did not call $PAGE->set_url(...). Using '.s($FULLME), DEBUG_DEVELOPER
);
566 $this->_url
= new moodle_url($FULLME);
567 // Make sure the guessed URL cannot lead to dangerous redirects.
568 $this->_url
->remove_params('sesskey');
570 return new moodle_url($this->_url
); // Return a clone for safety.
574 * The list of alternate versions of this page.
575 * @return array mime type => object with ->url and ->title.
577 protected function magic_get_alternateversions() {
578 return $this->_alternateversions
;
582 * Please do not call this method directly, use the ->blocks syntax. {@link moodle_page::__get()}.
583 * @return blocks_manager the blocks manager object for this page.
585 protected function magic_get_blocks() {
587 if (is_null($this->_blocks
)) {
588 if (!empty($CFG->blockmanagerclass
)) {
589 $classname = $CFG->blockmanagerclass
;
591 $classname = 'block_manager';
593 $this->_blocks
= new $classname($this);
595 return $this->_blocks
;
599 * Please do not call this method directly, use the ->requires syntax. {@link moodle_page::__get()}.
600 * @return page_requirements_manager tracks the JavaScript, CSS files, etc. required by this page.
602 protected function magic_get_requires() {
604 if (is_null($this->_requires
)) {
605 $this->_requires
= new page_requirements_manager();
607 return $this->_requires
;
611 * Please do not call this method directly, use the ->cacheable syntax. {@link moodle_page::__get()}.
612 * @return bool can this page be cached by the user's browser.
614 protected function magic_get_cacheable() {
615 return $this->_cacheable
;
619 * Please do not call this method directly, use the ->focuscontrol syntax. {@link moodle_page::__get()}.
620 * @return string the id of the HTML element to be focused when the page has loaded.
622 protected function magic_get_focuscontrol() {
623 return $this->_focuscontrol
;
627 * Please do not call this method directly, use the ->button syntax. {@link moodle_page::__get()}.
628 * @return string the HTML to go where the Turn editing on button normally goes.
630 protected function magic_get_button() {
631 return $this->_button
;
635 * Please do not call this method directly, use the ->theme syntax. {@link moodle_page::__get()}.
636 * @return theme_config the initialised theme for this page.
638 protected function magic_get_theme() {
639 if (is_null($this->_theme
)) {
640 $this->initialise_theme_and_output();
642 return $this->_theme
;
646 * Please do not call this method directly, use the ->devicetypeinuse syntax. {@link moodle_page::__get()}.
647 * @return string The device type being used.
649 protected function magic_get_devicetypeinuse() {
650 if (empty($this->_devicetypeinuse
)) {
651 $this->_devicetypeinuse
= get_user_device_type();
653 return $this->_devicetypeinuse
;
657 * Please do not call this method directly, use the ->legacythemeinuse syntax. {@link moodle_page::__get()}.
658 * @deprecated since 2.1
661 protected function magic_get_legacythemeinuse() {
662 debugging('$PAGE->legacythemeinuse is a deprecated property - please use $PAGE->devicetypeinuse and check if it is equal to legacy.', DEBUG_DEVELOPER
);
663 return ($this->devicetypeinuse
== 'legacy');
667 * Please do not call this method directly use the ->periodicrefreshdelay syntax
668 * {@link moodle_page::__get()}
669 * @return int The periodic refresh delay to use with meta refresh
671 protected function magic_get_periodicrefreshdelay() {
672 return $this->_periodicrefreshdelay
;
676 * Please do not call this method directly use the ->opencontainers syntax. {@link moodle_page::__get()}
677 * @return xhtml_container_stack tracks XHTML tags on this page that have been opened but not closed.
678 * mainly for internal use by the rendering code.
680 protected function magic_get_opencontainers() {
681 if (is_null($this->_opencontainers
)) {
682 $this->_opencontainers
= new xhtml_container_stack();
684 return $this->_opencontainers
;
688 * Return the navigation object
689 * @return global_navigation
691 protected function magic_get_navigation() {
692 if ($this->_navigation
=== null) {
693 $this->_navigation
= new global_navigation($this);
695 return $this->_navigation
;
699 * Return a navbar object
702 protected function magic_get_navbar() {
703 if ($this->_navbar
=== null) {
704 $this->_navbar
= new navbar($this);
706 return $this->_navbar
;
710 * Returns the settings navigation object
711 * @return settings_navigation
713 protected function magic_get_settingsnav() {
714 if ($this->_settingsnav
=== null) {
715 $this->_settingsnav
= new settings_navigation($this);
716 $this->_settingsnav
->initialise();
718 return $this->_settingsnav
;
722 * PHP overloading magic to make the $PAGE->course syntax work by redirecting
723 * it to the corresponding $PAGE->magic_get_course() method if there is one, and
724 * throwing an exception if not.
726 * @param string $name property name
729 public function __get($name) {
730 $getmethod = 'magic_get_' . $name;
731 if (method_exists($this, $getmethod)) {
732 return $this->$getmethod();
734 throw new coding_exception('Unknown property ' . $name . ' of $PAGE.');
739 * PHP overloading magic to catch obvious coding errors.
741 * This method has been created to catch obvious coding errors where the
742 * developer has tried to set a page property using $PAGE->key = $value.
743 * In the moodle_page class all properties must be set using the appropriate
744 * $PAGE->set_something($value) method.
746 * @param string $name property name
747 * @param mixed $value Value
748 * @return void Throws exception if field not defined in page class
750 public function __set($name, $value) {
751 if (method_exists($this, 'set_' . $name)) {
752 throw new coding_exception('Invalid attempt to modify page object', "Use \$PAGE->set_$name() instead.");
754 throw new coding_exception('Invalid attempt to modify page object', "Unknown property $name");
758 // Other information getting methods ==========================================
761 * Returns instance of page renderer
763 * @param string $component name such as 'core', 'mod_forum' or 'qtype_multichoice'.
764 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
765 * @param string $target one of rendering target constants
766 * @return renderer_base
768 public function get_renderer($component, $subtype = null, $target = null) {
769 return $this->magic_get_theme()->get_renderer($this, $component, $subtype, $target);
773 * Checks to see if there are any items on the navbar object
775 * @return bool true if there are, false if not
777 public function has_navbar() {
778 if ($this->_navbar
=== null) {
779 $this->_navbar
= new navbar($this);
781 return $this->_navbar
->has_items();
785 * Should the current user see this page in editing mode.
786 * That is, are they allowed to edit this page, and are they currently in
790 public function user_is_editing() {
792 return !empty($USER->editing
) && $this->user_allowed_editing();
796 * Does the user have permission to edit blocks on this page.
799 public function user_can_edit_blocks() {
800 return has_capability($this->_blockseditingcap
, $this->_context
);
804 * Does the user have permission to see this page in editing mode.
807 public function user_allowed_editing() {
808 if ($this->_legacypageobject
) {
809 return $this->_legacypageobject
->user_allowed_editing();
811 return has_any_capability($this->all_editing_caps(), $this->_context
);
815 * Get a description of this page. Normally displayed in the footer in
816 * developer debug mode.
819 public function debug_summary() {
821 $summary .= 'General type: ' . $this->pagelayout
. '. ';
822 if (!during_initial_install()) {
823 $summary .= 'Context ' . print_context_name($this->_context
) . ' (context id ' . $this->_context
->id
. '). ';
825 $summary .= 'Page type ' . $this->pagetype
. '. ';
826 if ($this->subpage
) {
827 'Sub-page ' . $this->subpage
. '. ';
832 // Setter methods =============================================================
835 * Set the state. The state must be one of that STATE_... constants, and
836 * the state is only allowed to advance one step at a time.
838 * @param integer $state The new state.
840 public function set_state($state) {
841 if ($state != $this->_state +
1 ||
$state > self
::STATE_DONE
) {
842 throw new coding_exception('Invalid state passed to moodle_page::set_state. We are in state ' .
843 $this->_state
. ' and state ' . $state . ' was requested.');
846 if ($state == self
::STATE_PRINTING_HEADER
) {
847 $this->starting_output();
850 $this->_state
= $state;
854 * Set the current course. This sets both $PAGE->course and $COURSE. It also
855 * sets the right theme and locale.
857 * Normally you don't need to call this function yourself, require_login will
858 * call it for you if you pass a $course to it. You can use this function
859 * on pages that do need to call require_login().
861 * Sets $PAGE->context to the course context, if it is not already set.
863 * @param stdClass $course the course to set as the global course.
865 public function set_course($course) {
866 global $COURSE, $PAGE;
868 if (empty($course->id
)) {
869 throw new coding_exception('$course passed to moodle_page::set_course does not look like a proper course object.');
872 $this->ensure_theme_not_set();
874 if (!empty($this->_course
->id
) && $this->_course
->id
!= $course->id
) {
875 $this->_categories
= null;
878 $this->_course
= clone($course);
880 if ($this === $PAGE) {
881 $COURSE = $this->_course
;
885 if (!$this->_context
) {
886 $this->set_context(get_context_instance(CONTEXT_COURSE
, $this->_course
->id
));
891 * Set the main context to which this page belongs.
893 * @param context $context a context object, normally obtained with get_context_instance.
895 public function set_context($context) {
896 if ($context === null) {
897 // extremely ugly hack which sets context to some value in order to prevent warnings,
898 // use only for core error handling!!!!
899 if (!$this->_context
) {
900 $this->_context
= get_context_instance(CONTEXT_SYSTEM
);
905 // ideally we should set context only once
906 if (isset($this->_context
)) {
907 if ($context->id
== $this->_context
->id
) {
908 // fine - no change needed
909 } else if ($this->_context
->contextlevel
== CONTEXT_SYSTEM
or $this->_context
->contextlevel
== CONTEXT_COURSE
) {
910 // hmm - not ideal, but it might produce too many warnings due to the design of require_login
911 } else if ($this->_context
->contextlevel
== CONTEXT_MODULE
and $this->_context
->id
== get_parent_contextid($context)) {
912 // hmm - most probably somebody did require_login() and after that set the block context
914 // we do not want devs to do weird switching of context levels on the fly,
915 // because we might have used the context already such as in text filter in page title
916 debugging('Coding problem: unsupported modification of PAGE->context from '.$this->_context
->contextlevel
.' to '.$context->contextlevel
);
920 $this->_context
= $context;
924 * The course module that this page belongs to (if it does belong to one).
926 * @param stdClass|cm_info $cm a record from course_modules table or cm_info from get_fast_modinfo().
927 * @param stdClass $course
928 * @param stdClass $module
931 public function set_cm($cm, $course = null, $module = null) {
934 if (!isset($cm->id
) ||
!isset($cm->course
)) {
935 throw new coding_exception('Invalid $cm parameter for $PAGE object, it has to be instance of cm_info or record from the course_modules table.');
938 if (!$this->_course ||
$this->_course
->id
!= $cm->course
) {
940 $course = $DB->get_record('course', array('id' => $cm->course
), '*', MUST_EXIST
);
942 if ($course->id
!= $cm->course
) {
943 throw new coding_exception('The course you passed to $PAGE->set_cm does not correspond to the $cm.');
945 $this->set_course($course);
948 // make sure we have a $cm from get_fast_modinfo as this contains activity access details
949 if (!($cm instanceof cm_info
)) {
950 $modinfo = get_fast_modinfo($this->_course
);
951 $cm = $modinfo->get_cm($cm->id
);
955 // unfortunately the context setting is a mess, let's try to work around some common block problems and show some debug messages
956 if (empty($this->_context
) or $this->_context
->contextlevel
!= CONTEXT_BLOCK
) {
957 $context = get_context_instance(CONTEXT_MODULE
, $cm->id
);
958 $this->set_context($context);
962 $this->set_activity_record($module);
967 * Sets the activity record. This could be a row from the main table for a
968 * module. For instance if the current module (cm) is a forum this should be a row
969 * from the forum table.
971 * @param stdClass $module A row from the main database table for the module that this
975 public function set_activity_record($module) {
976 if (is_null($this->_cm
)) {
977 throw new coding_exception('You cannot call $PAGE->set_activity_record until after $PAGE->cm has been set.');
979 if ($module->id
!= $this->_cm
->instance ||
$module->course
!= $this->_course
->id
) {
980 throw new coding_exception('The activity record your are trying to set does not seem to correspond to the cm that has been set.');
982 $this->_module
= $module;
986 * Sets the pagetype to use for this page.
988 * Normally you do not need to set this manually, it is automatically created
989 * from the script name. However, on some pages this is overridden.
990 * For example the page type for course/view.php includes the course format,
991 * for example 'course-view-weeks'. This gets used as the id attribute on
992 * <body> and also for determining which blocks are displayed.
994 * @param string $pagetype e.g. 'my-index' or 'mod-quiz-attempt'.
996 public function set_pagetype($pagetype) {
997 $this->_pagetype
= $pagetype;
1001 * Sets the layout to use for this page.
1003 * The page layout determines how the page will be displayed, things such as
1004 * block regions, content areas, etc are controlled by the layout.
1005 * The theme in use for the page will determine that the layout contains.
1007 * This properly defaults to 'base', so you only need to call this function if
1008 * you want something different. The exact range of supported layouts is specified
1009 * in the standard theme.
1011 * For an idea of the common page layouts see
1012 * {@link http://docs.moodle.org/dev/Themes_2.0#The_different_layouts_as_of_August_17th.2C_2010}
1013 * But please keep in mind that it may be (and normally is) out of date.
1014 * The only place to find an accurate up-to-date list of the page layouts
1015 * available for your version of Moodle is {@link theme/base/config.php}
1017 * @param string $pagelayout the page layout this is. For example 'popup', 'home'.
1019 public function set_pagelayout($pagelayout) {
1021 * Uncomment this to debug theme pagelayout issues like missing blocks.
1023 * if (!empty($this->_wherethemewasinitialised) && $pagelayout != $this->_pagelayout) {
1024 * debugging('Page layout has already been set and cannot be changed.', DEBUG_DEVELOPER);
1027 $this->_pagelayout
= $pagelayout;
1031 * If context->id and pagetype are not enough to uniquely identify this page,
1032 * then you can set a subpage id as well. For example, the tags page sets
1034 * @param string $subpage an arbitrary identifier that, along with context->id
1035 * and pagetype, uniquely identifies this page.
1037 public function set_subpage($subpage) {
1038 if (empty($subpage)) {
1039 $this->_subpage
= '';
1041 $this->_subpage
= $subpage;
1046 * Adds a CSS class to the body tag of the page.
1048 * @param string $class add this class name ot the class attribute on the body tag.
1050 public function add_body_class($class) {
1051 if ($this->_state
> self
::STATE_BEFORE_HEADER
) {
1052 throw new coding_exception('Cannot call moodle_page::add_body_class after output has been started.');
1054 $this->_bodyclasses
[$class] = 1;
1058 * Adds an array of body classes to the body tag of this page.
1060 * @param array $classes this utility method calls add_body_class for each array element.
1062 public function add_body_classes($classes) {
1063 foreach ($classes as $class) {
1064 $this->add_body_class($class);
1069 * Sets the title for the page.
1070 * This is normally used within the title tag in the head of the page.
1072 * @param string $title the title that should go in the <head> section of the HTML of this page.
1074 public function set_title($title) {
1075 $title = format_string($title);
1076 $title = strip_tags($title);
1077 $title = str_replace('"', '"', $title);
1078 $this->_title
= $title;
1082 * Sets the heading to use for the page.
1083 * This is normally used as the main heading at the top of the content.
1085 * @param string $heading the main heading that should be displayed at the top of the <body>.
1087 public function set_heading($heading) {
1088 $this->_heading
= format_string($heading);
1092 * Sets some HTML to use next to the heading {@link moodle_page::set_heading()}
1094 * @param string $menu The menu/content to show in the heading
1096 public function set_headingmenu($menu) {
1097 $this->_headingmenu
= $menu;
1101 * Set the course category this page belongs to manually.
1103 * This automatically sets $PAGE->course to be the site course. You cannot
1104 * use this method if you have already set $PAGE->course - in that case,
1105 * the category must be the one that the course belongs to. This also
1106 * automatically sets the page context to the category context.
1108 * @param integer $categoryid The id of the category to set.
1110 public function set_category_by_id($categoryid) {
1112 if (!is_null($this->_course
)) {
1113 throw new coding_exception('Attempt to manually set the course category when the course has been set. This is not allowed.');
1115 if (is_array($this->_categories
)) {
1116 throw new coding_exception('Course category has already been set. You are not allowed to change it.');
1118 $this->ensure_theme_not_set();
1119 $this->set_course($SITE);
1120 $this->load_category($categoryid);
1121 $this->set_context(get_context_instance(CONTEXT_COURSECAT
, $categoryid));
1125 * Set a different path to use for the 'Moodle docs for this page' link.
1127 * By default, it uses the pagetype, which is normally the same as the
1128 * script name. So, for example, for mod/quiz/attempt.php, pagetype is
1129 * mod-quiz-attempt, and so docspath is mod/quiz/attempt.
1131 * @param string $path the path to use at the end of the moodle docs URL.
1133 public function set_docs_path($path) {
1134 $this->_docspath
= $path;
1138 * You should call this method from every page to set the cleaned-up URL
1139 * that should be used to return to this page.
1141 * Used, for example, by the blocks editing UI to know where to return the
1142 * user after an action.
1143 * For example, course/view.php does:
1144 * $id = optional_param('id', 0, PARAM_INT);
1145 * $PAGE->set_url('/course/view.php', array('id' => $id));
1147 * @param moodle_url|string $url URL relative to $CFG->wwwroot or {@link moodle_url} instance
1148 * @param array $params parameters to add to the URL
1150 public function set_url($url, array $params = null) {
1153 if (is_string($url)) {
1154 if (strpos($url, 'http') === 0) {
1156 } else if (strpos($url, '/') === 0) {
1157 // we have to use httpswwwroot here, because of loginhttps pages
1158 $url = $CFG->httpswwwroot
. $url;
1160 throw new coding_exception('Invalid parameter $url, has to be full url or in shortened form starting with /.');
1164 $this->_url
= new moodle_url($url, $params);
1166 $fullurl = $this->_url
->out_omit_querystring();
1167 if (strpos($fullurl, "$CFG->httpswwwroot/") !== 0) {
1168 debugging('Most probably incorrect set_page() url argument, it does not match the httpswwwroot!');
1170 $shorturl = str_replace("$CFG->httpswwwroot/", '', $fullurl);
1172 if (is_null($this->_pagetype
)) {
1173 $this->initialise_default_pagetype($shorturl);
1175 if (!is_null($this->_legacypageobject
)) {
1176 $this->_legacypageobject
->set_url($url, $params);
1181 * Make sure page URL does not contain the given URL parameter.
1183 * This should not be necessary if the script has called set_url properly.
1184 * However, in some situations like the block editing actions; when the URL
1185 * has been guessed, it will contain dangerous block-related actions.
1186 * Therefore, the blocks code calls this function to clean up such parameters
1187 * before doing any redirect.
1189 * @param string $param the name of the parameter to make sure is not in the
1192 public function ensure_param_not_in_url($param) {
1193 $discard = $this->url
; // Make sure $this->url is lazy-loaded;
1194 $this->_url
->remove_params($param);
1198 * There can be alternate versions of some pages (for example an RSS feed version).
1199 * If such other version exist, call this method, and a link to the alternate
1200 * version will be included in the <head> of the page.
1202 * @param string $title The title to give the alternate version.
1203 * @param string|moodle_url $url The URL of the alternate version.
1204 * @param string $mimetype The mime-type of the alternate version.
1206 public function add_alternate_version($title, $url, $mimetype) {
1207 if ($this->_state
> self
::STATE_BEFORE_HEADER
) {
1208 throw new coding_exception('Cannot call moodle_page::add_alternate_version after output has been started.');
1210 $alt = new stdClass
;
1211 $alt->title
= $title;
1213 $this->_alternateversions
[$mimetype] = $alt;
1217 * Specify a form control should be focused when the page has loaded.
1219 * @param string $controlid the id of the HTML element to be focused.
1221 public function set_focuscontrol($controlid) {
1222 $this->_focuscontrol
= $controlid;
1226 * Specify a fragment of HTML that goes where the 'Turn editing on' button normally goes.
1228 * @param string $html the HTML to display there.
1230 public function set_button($html) {
1231 $this->_button
= $html;
1235 * Set the capability that allows users to edit blocks on this page.
1237 * Normally the default of 'moodle/site:manageblocks' is used, but a few
1238 * pages like the My Moodle page need to use a different capability
1239 * like 'moodle/my:manageblocks'.
1241 * @param string $capability a capability.
1243 public function set_blocks_editing_capability($capability) {
1244 $this->_blockseditingcap
= $capability;
1248 * Some pages let you turn editing on for reasons other than editing blocks.
1249 * If that is the case, you can pass other capabilities that let the user
1250 * edit this page here.
1252 * @param string|array $capability either a capability, or an array of capabilities.
1254 public function set_other_editing_capability($capability) {
1255 if (is_array($capability)) {
1256 $this->_othereditingcaps
= array_unique($this->_othereditingcaps +
$capability);
1258 $this->_othereditingcaps
[] = $capability;
1263 * Sets whether the browser should cache this page or not.
1265 * @return bool $cacheable can this page be cached by the user's browser.
1267 public function set_cacheable($cacheable) {
1268 $this->_cacheable
= $cacheable;
1272 * Sets the page to periodically refresh
1274 * This function must be called before $OUTPUT->header has been called or
1275 * a coding exception will be thrown.
1277 * @param int $delay Sets the delay before refreshing the page, if set to null
1278 * refresh is cancelled
1280 public function set_periodic_refresh_delay($delay=null) {
1281 if ($this->_state
> self
::STATE_BEFORE_HEADER
) {
1282 throw new coding_exception('You cannot set a periodic refresh delay after the header has been printed');
1284 if ($delay===null) {
1285 $this->_periodicrefreshdelay
= null;
1286 } else if (is_int($delay)) {
1287 $this->_periodicrefreshdelay
= $delay;
1292 * Force this page to use a particular theme.
1294 * Please use this cautiously.
1295 * It is only intended to be used by the themes selector admin page.
1297 * @param string $themename the name of the theme to use.
1299 public function force_theme($themename) {
1300 $this->ensure_theme_not_set();
1301 $this->_theme
= theme_config
::load($themename);
1305 * This function indicates that current page requires the https
1306 * when $CFG->loginhttps enabled.
1308 * By using this function properly, we can ensure 100% https-ized pages
1309 * at our entire discretion (login, forgot_password, change_password)
1312 public function https_required() {
1315 if (!is_null($this->_url
)) {
1316 throw new coding_exception('https_required() must be used before setting page url!');
1319 $this->ensure_theme_not_set();
1321 $this->_https_login_required
= true;
1323 if (!empty($CFG->loginhttps
)) {
1324 $CFG->httpswwwroot
= str_replace('http:', 'https:', $CFG->wwwroot
);
1326 $CFG->httpswwwroot
= $CFG->wwwroot
;
1331 * Makes sure that page previously marked with https_required()
1332 * is really using https://, if not it redirects to https://
1334 * @return void (may redirect to https://self)
1336 public function verify_https_required() {
1337 global $CFG, $FULLME;
1339 if (is_null($this->_url
)) {
1340 throw new coding_exception('verify_https_required() must be called after setting page url!');
1343 if (!$this->_https_login_required
) {
1344 throw new coding_exception('verify_https_required() must be called only after https_required()!');
1347 if (empty($CFG->loginhttps
)) {
1348 // https not required, so stop checking
1352 if (strpos($this->_url
, 'https://')) {
1353 // detect if incorrect PAGE->set_url() used, it is recommended to use root-relative paths there
1354 throw new coding_exception('Invalid page url specified, it must start with https:// for pages that set https_required()!');
1357 if (!empty($CFG->sslproxy
)) {
1358 // it does not make much sense to use sslproxy and loginhttps at the same time
1362 // now the real test and redirect!
1363 // NOTE: do NOT use this test for detection of https on current page because this code is not compatible with SSL proxies,
1364 // instead use strpos($CFG->httpswwwroot, 'https:') === 0
1365 if (strpos($FULLME, 'https:') !== 0) {
1366 // this may lead to infinite redirect on misconfigured sites, in that case use $CFG->loginhttps=0; in /config.php
1367 redirect($this->_url
);
1371 // Initialisation methods =====================================================
1372 // These set various things up in a default way.
1375 * This method is called when the page first moves out of the STATE_BEFORE_HEADER
1376 * state. This is our last change to initialise things.
1378 protected function starting_output() {
1381 if (!during_initial_install()) {
1382 $this->blocks
->load_blocks();
1383 if (empty($this->_block_actions_done
)) {
1384 $this->_block_actions_done
= true;
1385 if ($this->blocks
->process_url_actions($this)) {
1386 redirect($this->url
->out(false));
1389 $this->blocks
->create_all_block_instances();
1392 // If maintenance mode is on, change the page header.
1393 if (!empty($CFG->maintenance_enabled
)) {
1394 $this->set_button('<a href="' . $CFG->wwwroot
. '/' . $CFG->admin
.
1395 '/settings.php?section=maintenancemode">' . get_string('maintenancemode', 'admin') .
1396 '</a> ' . $this->button
);
1398 $title = $this->title
;
1402 $this->set_title($title . get_string('maintenancemode', 'admin'));
1404 // Show the messaging popup if there are messages
1405 message_popup_window();
1408 $this->initialise_standard_body_classes();
1412 * Method for use by Moodle core to set up the theme. Do not
1413 * use this in your own code.
1415 * Make sure the right theme for this page is loaded. Tell our
1416 * blocks_manager about the theme block regions, and then, if
1417 * we are $PAGE, set up the global $OUTPUT.
1421 public function initialise_theme_and_output() {
1422 global $OUTPUT, $PAGE, $SITE;
1424 if (!empty($this->_wherethemewasinitialised
)) {
1428 if (!during_initial_install()) {
1429 // detect PAGE->context mess
1430 $this->magic_get_context();
1433 if (!$this->_course
&& !during_initial_install()) {
1434 $this->set_course($SITE);
1437 if (is_null($this->_theme
)) {
1438 $themename = $this->resolve_theme();
1439 $this->_theme
= theme_config
::load($themename);
1442 $this->_theme
->setup_blocks($this->pagelayout
, $this->blocks
);
1444 if ($this === $PAGE) {
1445 $OUTPUT = $this->get_renderer('core');
1448 $this->_wherethemewasinitialised
= debug_backtrace();
1452 * Work out the theme this page should use.
1454 * This depends on numerous $CFG settings, and the properties of this page.
1456 * @return string the name of the theme that should be used on this page.
1458 protected function resolve_theme() {
1459 global $CFG, $USER, $SESSION;
1461 if (empty($CFG->themeorder
)) {
1462 $themeorder = array('course', 'category', 'session', 'user', 'site');
1464 $themeorder = $CFG->themeorder
;
1465 // Just in case, make sure we always use the site theme if nothing else matched.
1466 $themeorder[] = 'site';
1469 $mnetpeertheme = '';
1470 if (isloggedin() and isset($CFG->mnet_localhost_id
) and $USER->mnethostid
!= $CFG->mnet_localhost_id
) {
1471 require_once($CFG->dirroot
.'/mnet/peer.php');
1472 $mnetpeer = new mnet_peer();
1473 $mnetpeer->set_id($USER->mnethostid
);
1474 if ($mnetpeer->force_theme
== 1 && $mnetpeer->theme
!= '') {
1475 $mnetpeertheme = $mnetpeer->theme
;
1479 foreach ($themeorder as $themetype) {
1480 switch ($themetype) {
1482 if (!empty($CFG->allowcoursethemes
) && !empty($this->_course
->theme
) && $this->devicetypeinuse
== 'default') {
1483 return $this->_course
->theme
;
1488 if (!empty($CFG->allowcategorythemes
) && $this->devicetypeinuse
== 'default') {
1489 $categories = $this->categories
;
1490 foreach ($categories as $category) {
1491 if (!empty($category->theme
)) {
1492 return $category->theme
;
1499 if (!empty($SESSION->theme
)) {
1500 return $SESSION->theme
;
1505 if (!empty($CFG->allowuserthemes
) && !empty($USER->theme
) && $this->devicetypeinuse
== 'default') {
1506 if ($mnetpeertheme) {
1507 return $mnetpeertheme;
1509 return $USER->theme
;
1515 if ($mnetpeertheme) {
1516 return $mnetpeertheme;
1518 // First try for the device the user is using.
1519 $devicetheme = get_selected_theme_for_device_type($this->devicetypeinuse
);
1520 if (!empty($devicetheme)) {
1521 return $devicetheme;
1523 // Next try for the default device (as a fallback)
1524 $devicetheme = get_selected_theme_for_device_type('default');
1525 if (!empty($devicetheme)) {
1526 return $devicetheme;
1528 // The default device theme isn't set up - use the overall default theme.
1529 return theme_config
::DEFAULT_THEME
;
1536 * Sets ->pagetype from the script name. For example, if the script that was
1537 * run is mod/quiz/view.php, ->pagetype will be set to 'mod-quiz-view'.
1539 * @param string $script the path to the script that should be used to
1540 * initialise ->pagetype. If not passed the $SCRIPT global will be used.
1541 * If legacy code has set $CFG->pagepath that will be used instead, and a
1542 * developer warning issued.
1544 protected function initialise_default_pagetype($script = null) {
1545 global $CFG, $SCRIPT;
1547 if (isset($CFG->pagepath
)) {
1548 debugging('Some code appears to have set $CFG->pagepath. That was a horrible deprecated thing. ' .
1549 'Don\'t do it! Try calling $PAGE->set_pagetype() instead.');
1550 $script = $CFG->pagepath
;
1551 unset($CFG->pagepath
);
1554 if (is_null($script)) {
1555 $script = ltrim($SCRIPT, '/');
1556 $len = strlen($CFG->admin
);
1557 if (substr($script, 0, $len) == $CFG->admin
) {
1558 $script = 'admin' . substr($script, $len);
1562 $path = str_replace('.php', '', $script);
1563 if (substr($path, -1) == '/') {
1567 if (empty($path) ||
$path == 'index') {
1568 $this->_pagetype
= 'site-index';
1570 $this->_pagetype
= str_replace('/', '-', $path);
1575 * Initialises the CSS classes that will be added to body tag of the page.
1577 * The function is responsible for adding all of the critical CSS classes
1578 * that describe the current page, and its state.
1579 * This includes classes that describe the following for example:
1580 * - Current language
1581 * - Language direction
1582 * - YUI CSS initialisation
1584 * These are commonly used in CSS to target specific types of pages.
1586 protected function initialise_standard_body_classes() {
1589 $pagetype = $this->pagetype
;
1590 if ($pagetype == 'site-index') {
1591 $this->_legacyclass
= 'course';
1592 } else if (substr($pagetype, 0, 6) == 'admin-') {
1593 $this->_legacyclass
= 'admin';
1595 $this->add_body_class($this->_legacyclass
);
1597 $pathbits = explode('-', trim($pagetype));
1598 for ($i=1;$i<count($pathbits);$i++
) {
1599 $this->add_body_class('path-'.join('-',array_slice($pathbits, 0, $i)));
1602 $this->add_body_classes(get_browser_version_classes());
1603 $this->add_body_class('dir-' . get_string('thisdirection', 'langconfig'));
1604 $this->add_body_class('lang-' . current_language());
1605 $this->add_body_class('yui-skin-sam'); // Make YUI happy, if it is used.
1606 $this->add_body_class('yui3-skin-sam'); // Make YUI3 happy, if it is used.
1607 $this->add_body_class($this->url_to_class_name($CFG->wwwroot
));
1609 $this->add_body_class('pagelayout-' . $this->_pagelayout
); // extra class describing current page layout
1611 if (!during_initial_install()) {
1612 $this->add_body_class('course-' . $this->_course
->id
);
1613 $this->add_body_class('context-' . $this->_context
->id
);
1616 if (!empty($this->_cm
)) {
1617 $this->add_body_class('cmid-' . $this->_cm
->id
);
1620 if (!empty($CFG->allowcategorythemes
)) {
1621 $this->ensure_category_loaded();
1622 foreach ($this->_categories
as $catid => $notused) {
1623 $this->add_body_class('category-' . $catid);
1627 if (is_array($this->_categories
)) {
1628 $catids = array_keys($this->_categories
);
1629 $catid = reset($catids);
1630 } else if (!empty($this->_course
->category
)) {
1631 $catid = $this->_course
->category
;
1634 $this->add_body_class('category-' . $catid);
1638 if (!isloggedin()) {
1639 $this->add_body_class('notloggedin');
1642 if (!empty($USER->editing
)) {
1643 $this->add_body_class('editing');
1644 if (optional_param('bui_moveid', false, PARAM_INT
)) {
1645 $this->add_body_class('blocks-moving');
1649 if (!empty($CFG->blocksdrag
)) {
1650 $this->add_body_class('drag');
1653 if ($this->_devicetypeinuse
!= 'default') {
1654 $this->add_body_class($this->_devicetypeinuse
. 'theme');
1659 * Loads the activity record for the current CM object associated with this
1662 * This will load {@link moodle_page::$_module} with a row from the related
1663 * module table in the database.
1664 * For instance if {@link moodle_page::$_cm} is a forum then a row from the
1665 * forum table will be loaded.
1667 protected function load_activity_record() {
1669 if (is_null($this->_cm
)) {
1672 $this->_module
= $DB->get_record($this->_cm
->modname
, array('id' => $this->_cm
->instance
));
1676 * This function ensures that the category of the current course has been
1677 * loaded, and if not, the function loads it now.
1680 * @throws coding_exception
1682 protected function ensure_category_loaded() {
1683 if (is_array($this->_categories
)) {
1684 return; // Already done.
1686 if (is_null($this->_course
)) {
1687 throw new coding_exception('Attempt to get the course category for this page before the course was set.');
1689 if ($this->_course
->category
== 0) {
1690 $this->_categories
= array();
1692 $this->load_category($this->_course
->category
);
1697 * Loads the requested category into the pages categories array.
1699 * @param ing $categoryid
1700 * @throws moodle_exception
1702 protected function load_category($categoryid) {
1704 $category = $DB->get_record('course_categories', array('id' => $categoryid));
1706 throw new moodle_exception('unknowncategory');
1708 $this->_categories
[$category->id
] = $category;
1709 $parentcategoryids = explode('/', trim($category->path
, '/'));
1710 array_pop($parentcategoryids);
1711 foreach (array_reverse($parentcategoryids) as $catid) {
1712 $this->_categories
[$catid] = null;
1717 * Ensures that the category the current course is within, as well as all of
1718 * its parent categories, have been loaded.
1722 protected function ensure_categories_loaded() {
1724 $this->ensure_category_loaded();
1725 if (!is_null(end($this->_categories
))) {
1726 return; // Already done.
1728 $idstoload = array_keys($this->_categories
);
1729 array_shift($idstoload);
1730 $categories = $DB->get_records_list('course_categories', 'id', $idstoload);
1731 foreach ($idstoload as $catid) {
1732 $this->_categories
[$catid] = $categories[$catid];
1737 * Ensure the theme has not been loaded yet. If it has an exception is thrown.
1740 * @throws coding_exception
1742 protected function ensure_theme_not_set() {
1743 if (!is_null($this->_theme
)) {
1744 throw new coding_exception('The theme has already been set up for this page ready for output. ' .
1745 'Therefore, you can no longer change the theme, or anything that might affect what ' .
1746 'the current theme is, for example, the course.',
1747 'Stack trace when the theme was set up: ' . format_backtrace($this->_wherethemewasinitialised
));
1752 * Converts the provided URL into a CSS class that be used within the page.
1753 * This is primarily used to add the wwwroot to the body tag as a CSS class.
1755 * @param string $url
1758 protected function url_to_class_name($url) {
1759 $bits = parse_url($url);
1760 $class = str_replace('.', '-', $bits['host']);
1761 if (!empty($bits['port'])) {
1762 $class .= '--' . $bits['port'];
1764 if (!empty($bits['path'])) {
1765 $path = trim($bits['path'], '/');
1767 $class .= '--' . str_replace('/', '-', $path);
1774 * Combines all of the required editing caps for the page and returns them
1779 protected function all_editing_caps() {
1780 $caps = $this->_othereditingcaps
;
1781 $caps[] = $this->_blockseditingcap
;
1785 // Deprecated fields and methods for backwards compatibility ==================
1788 * Returns the page type.
1790 * @deprecated since Moodle 2.0 - use $PAGE->pagetype instead.
1791 * @return string page type.
1793 public function get_type() {
1794 debugging('Call to deprecated method moodle_page::get_type. Please use $PAGE->pagetype instead.');
1795 return $this->get_pagetype();
1799 * Returns the page type.
1801 * @deprecated since Moodle 2.0 - use $PAGE->pagetype instead.
1802 * @return string this is what page_id_and_class used to return via the $getclass parameter.
1804 public function get_format_name() {
1805 return $this->get_pagetype();
1809 * Returns the course associated with this page.
1811 * @deprecated since Moodle 2.0 - use $PAGE->course instead.
1812 * @return stdClass course.
1814 public function get_courserecord() {
1815 debugging('Call to deprecated method moodle_page::get_courserecord. Please use $PAGE->course instead.');
1816 return $this->get_course();
1820 * Returns the legacy page class.
1822 * @deprecated since Moodle 2.0
1823 * @return string this is what page_id_and_class used to return via the $getclass parameter.
1825 public function get_legacyclass() {
1826 if (is_null($this->_legacyclass
)) {
1827 $this->initialise_standard_body_classes();
1829 debugging('Call to deprecated method moodle_page::get_legacyclass.');
1830 return $this->_legacyclass
;
1834 * Returns an array of block regions on this page.
1836 * @deprecated since Moodle 2.0 - use $PAGE->blocks->get_regions() instead
1837 * @return array the places on this page where blocks can go.
1839 function blocks_get_positions() {
1840 debugging('Call to deprecated method moodle_page::blocks_get_positions. Use $PAGE->blocks->get_regions() instead.');
1841 return $this->blocks
->get_regions();
1845 * Returns the default block region.
1847 * @deprecated since Moodle 2.0 - use $PAGE->blocks->get_default_region() instead
1848 * @return string the default place for blocks on this page.
1850 function blocks_default_position() {
1851 debugging('Call to deprecated method moodle_page::blocks_default_position. Use $PAGE->blocks->get_default_region() instead.');
1852 return $this->blocks
->get_default_region();
1856 * Returns the default block to use of the page.
1857 * This function no longer does anything. DO NOT USE.
1859 * @deprecated since Moodle 2.0 - no longer used.
1861 function blocks_get_default() {
1862 debugging('Call to deprecated method moodle_page::blocks_get_default. This method has no function any more.');
1867 * This function no longer does anything. DO NOT USE.
1869 * @deprecated since Moodle 2.0 - no longer used.
1871 function blocks_move_position(&$instance, $move) {
1872 debugging('Call to deprecated method moodle_page::blocks_move_position. This method has no function any more.');
1876 * Returns the URL parameters for the current page.
1878 * @deprecated since Moodle 2.0 - use $this->url->params() instead.
1879 * @return array URL parameters for this page.
1881 function url_get_parameters() {
1882 debugging('Call to deprecated method moodle_page::url_get_parameters. Use $this->url->params() instead.');
1883 return $this->url
->params();
1887 * Returns the URL path of the current page.
1889 * @deprecated since Moodle 2.0 - use $this->url->params() instead.
1890 * @return string URL for this page without parameters.
1892 function url_get_path() {
1893 debugging('Call to deprecated method moodle_page::url_get_path. Use $this->url->out() instead.');
1894 return $this->url
->out();
1898 * Returns the full URL for this page.
1900 * @deprecated since Moodle 2.0 - use $this->url->out() instead.
1901 * @return string full URL for this page.
1903 function url_get_full($extraparams = array()) {
1904 debugging('Call to deprecated method moodle_page::url_get_full. Use $this->url->out() instead.');
1905 return $this->url
->out(true, $extraparams);
1909 * Returns the legacy page object.
1911 * @deprecated since Moodle 2.0 - just a backwards compatibility hook.
1912 * @return moodle_page
1914 function set_legacy_page_object($pageobject) {
1915 return $this->_legacypageobject
= $pageobject;
1919 * Prints a header... DO NOT USE!
1921 * @deprecated since Moodle 2.0 - page objects should no longer be doing print_header.
1922 * @param mixed $_ ...
1924 function print_header($_) {
1925 if (is_null($this->_legacypageobject
)) {
1926 throw new coding_exception('You have called print_header on $PAGE when there is not a legacy page class present.');
1928 debugging('You should not longer be doing print_header via a page class.', DEBUG_DEVELOPER
);
1929 $args = func_get_args();
1930 call_user_func_array(array($this->_legacypageobject
, 'print_header'), $args);
1934 * Returns the ID for this page. DO NOT USE!
1936 * @deprecated since Moodle 2.0
1937 * @return the 'page id'. This concept no longer exists.
1940 debugging('Call to deprecated method moodle_page::get_id(). It should not be necessary any more.', DEBUG_DEVELOPER
);
1941 if (!is_null($this->_legacypageobject
)) {
1942 return $this->_legacypageobject
->get_id();
1948 * Returns the ID for this page. DO NOT USE!
1950 * @deprecated since Moodle 2.0
1951 * @return the 'page id'. This concept no longer exists.
1953 function get_pageid() {
1954 debugging('Call to deprecated method moodle_page::get_pageid(). It should not be necessary any more.', DEBUG_DEVELOPER
);
1955 if (!is_null($this->_legacypageobject
)) {
1956 return $this->_legacypageobject
->get_id();
1962 * Returns the module record for this page.
1964 * @deprecated since Moodle 2.0 - user $PAGE->cm instead.
1965 * @return $this->cm;
1967 function get_modulerecord() {
1972 * Returns true if the page URL has beem set.
1976 public function has_set_url() {
1977 return ($this->_url
!==null);
1981 * Gets set when the block actions for the page have been processed.
1983 * @param bool $setting
1985 public function set_block_actions_done($setting = true) {
1986 $this->_block_actions_done
= $setting;
1990 * Are popup notifications allowed on this page?
1991 * Popup notifications may be disallowed in situations such as while upgrading or completing a quiz
1993 * @return bool true if popup notifications may be displayed
1995 public function get_popup_notification_allowed() {
1996 return $this->_popup_notification_allowed
;
2000 * Allow or disallow popup notifications on this page. Popups are allowed by default.
2002 * @param bool $allowed true if notifications are allowed. False if not allowed. They are allowed by default.
2004 public function set_popup_notification_allowed($allowed) {
2005 $this->_popup_notification_allowed
= $allowed;
2010 * Not needed any more. DO NOT USE!
2012 * @deprecated since Moodle 2.0
2013 * @param string $path the folder path
2014 * @return array an array of page types.
2016 function page_import_types($path) {
2018 debugging('Call to deprecated function page_import_types.', DEBUG_DEVELOPER
);
2022 * Do not use this any more. The global $PAGE is automatically created for you.
2023 * If you need custom behaviour, you should just set properties of that object.
2025 * @deprecated since Moodle 2.0
2026 * @param integer $instance legacy page instance id.
2027 * @return moodle_page The global $PAGE object.
2029 function page_create_instance($instance) {
2031 return page_create_object($PAGE->pagetype
, $instance);
2035 * Do not use this any more. The global $PAGE is automatically created for you.
2036 * If you need custom behaviour, you should just set properties of that object.
2038 * @deprecated since Moodle 2.0
2039 * @return moodle_page The global $PAGE object.
2041 function page_create_object($type, $id = NULL) {
2042 global $CFG, $PAGE, $SITE, $ME;
2043 debugging('Call to deprecated function page_create_object.', DEBUG_DEVELOPER
);
2045 $data = new stdClass
;
2046 $data->pagetype
= $type;
2047 $data->pageid
= $id;
2049 $classname = page_map_class($type);
2053 $legacypage = new $classname;
2054 $legacypage->init_quick($data);
2056 $course = $PAGE->course
;
2057 if ($course->id
!= $SITE->id
) {
2058 $legacypage->set_course($course);
2061 $category = $PAGE->category
;
2062 } catch (coding_exception
$e) {
2063 // Was not set before, so no need to try to set it again.
2067 $legacypage->set_category_by_id($category->id
);
2069 $legacypage->set_course($SITE);
2073 $legacypage->set_pagetype($type);
2075 $legacypage->set_url($ME);
2076 $PAGE->set_url(str_replace($CFG->wwwroot
. '/', '', $legacypage->url_get_full()));
2078 $PAGE->set_pagetype($type);
2079 $PAGE->set_legacy_page_object($legacypage);
2084 * You should not be writing page subclasses any more. Just set properties on the
2085 * global $PAGE object to control its behaviour.
2087 * @deprecated since Moodle 2.0
2088 * @return mixed Null if there is not a valid page mapping, or the mapping if
2091 function page_map_class($type, $classname = NULL) {
2094 static $mappings = array(
2095 PAGE_COURSE_VIEW
=> 'page_course',
2098 if (!empty($type) && !empty($classname)) {
2099 $mappings[$type] = $classname;
2102 if (!isset($mappings[$type])) {
2103 debugging('Page class mapping requested for unknown type: '.$type);
2105 } else if (empty($classname) && !class_exists($mappings[$type])) {
2106 debugging('Page class mapping for id "'.$type.'" exists but class "'.$mappings[$type].'" is not defined');
2110 return $mappings[$type];
2114 * Parent class from which all Moodle page classes derive
2116 * @deprecated since Moodle 2.0
2119 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2122 class page_base
extends moodle_page
{
2124 * @var int The numeric identifier of the page being described.
2129 * Returns the page id
2130 * @deprecated since Moodle 2.0
2131 * @return int Returns the id of the page.
2133 public function get_id() {
2138 * Initialize the data members of the parent class
2139 * @param scalar $data
2141 public function init_quick($data) {
2142 $this->id
= $data->pageid
;
2146 * DOES NOTHING... DO NOT USE.
2147 * @deprecated since Moodle 2.0
2149 public function init_full() {}
2153 * Class that models the behavior of a moodle course.
2154 * Although this does nothing, this class declaration should be left for now
2155 * since there may be legacy class doing class page_... extends page_course
2157 * @deprecated since Moodle 2.0
2160 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2161 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2163 class page_course
extends page_base
{}
2166 * Class that models the common parts of all activity modules
2168 * @deprecated since Moodle 2.0
2171 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2172 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
2174 class page_generic_activity
extends page_base
{
2177 * Although this function is deprecated, it should be left here because
2178 * people upgrading legacy code need to copy it. See
2179 * http://docs.moodle.org/dev/Migrating_your_code_to_the_2.0_rendering_API
2181 * @param string $title
2182 * @param array $morenavlinks
2183 * @param string $bodytags
2184 * @param string $meta
2186 function print_header($title, $morenavlinks = NULL, $bodytags = '', $meta = '') {
2187 global $USER, $CFG, $PAGE, $OUTPUT;
2190 $replacements = array(
2191 '%fullname%' => format_string($this->activityrecord
->name
)
2193 foreach ($replacements as $search => $replace) {
2194 $title = str_replace($search, $replace, $title);
2197 $buttons = '<table><tr><td>'.$OUTPUT->update_module_button($this->modulerecord
->id
, $this->activityname
).'</td>';
2198 if ($this->user_allowed_editing()) {
2199 $buttons .= '<td><form method="get" action="view.php"><div>'.
2200 '<input type="hidden" name="id" value="'.$this->modulerecord
->id
.'" />'.
2201 '<input type="hidden" name="edit" value="'.($this->user_is_editing()?
'off':'on').'" />'.
2202 '<input type="submit" value="'.get_string($this->user_is_editing()?
'blockseditoff':'blocksediton').'" /></div></form></td>';
2204 $buttons .= '</tr></table>';
2206 if (!empty($morenavlinks) && is_array($morenavlinks)) {
2207 foreach ($morenavlinks as $navitem) {
2208 if (is_array($navitem) && array_key_exists('name', $navitem)) {
2210 if (array_key_exists('link', $navitem)) {
2211 $link = $navitem['link'];
2213 $PAGE->navbar
->add($navitem['name'], $link);
2218 $PAGE->set_title($title);
2219 $PAGE->set_heading($this->course
->fullname
);
2220 $PAGE->set_button($buttons);
2221 echo $OUTPUT->header();