Merge branch 'wip-MDL-40540-m26' of git://github.com/samhemelryk/moodle
[moodle.git] / lib / pagelib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * This file contains the moodle_page class. There is normally a single instance
19  * of this class in the $PAGE global variable. This class is a central repository
20  * of information about the page we are building up to send back to the user.
21  *
22  * @package core
23  * @category page
24  * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
25  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26  */
28 defined('MOODLE_INTERNAL') || die();
30 /**
31  * $PAGE is a central store of information about the current page we are
32  * generating in response to the user's request.
33  *
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,
37  * $PAGE->blocks, etc.
38  *
39  * @copyright 2009 Tim Hunt
40  * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41  * @since Moodle 2.0
42  * @package core
43  * @category page
44  *
45  * The following properties are alphabetical. Please keep it that way so that its
46  * easy to maintain.
47  *
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
63  *      front page course.
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 settings_navigation $settingsnav The settings navigation
91  * @property-read int $state One of the STATE_... constants
92  * @property-read string $subpage The subpage identifier, if any.
93  * @property-read theme_config $theme The theme for this page.
94  * @property-read string $title The title that should go in the <head> section of the HTML of this page.
95  * @property-read moodle_url $url The moodle url object for this page.
96  */
97 class moodle_page {
99     /** The state of the page before it has printed the header **/
100     const STATE_BEFORE_HEADER = 0;
102     /** The state the page is in temporarily while the header is being printed **/
103     const STATE_PRINTING_HEADER = 1;
105     /** The state the page is in while content is presumably being printed **/
106     const STATE_IN_BODY = 2;
108     /**
109      * The state the page is when the footer has been printed and its function is
110      * complete.
111      */
112     const STATE_DONE = 3;
114     /**
115      * @var int The current state of the page. The state a page is within
116      * determines what actions are possible for it.
117      */
118     protected $_state = self::STATE_BEFORE_HEADER;
120     /**
121      * @var stdClass The course currently associated with this page.
122      * If not has been provided the front page course is used.
123      */
124     protected $_course = null;
126     /**
127      * @var cm_info If this page belongs to a module, this is the cm_info module
128      * description object.
129      */
130     protected $_cm = null;
132     /**
133      * @var stdClass If $_cm is not null, then this will hold the corresponding
134      * row from the modname table. For example, if $_cm->modname is 'quiz', this
135      * will be a row from the quiz table.
136      */
137     protected $_module = null;
139     /**
140      * @var context The context that this page belongs to.
141      */
142     protected $_context = null;
144     /**
145      * @var array This holds any categories that $_course belongs to, starting with the
146      * particular category it belongs to, and working out through any parent
147      * categories to the top level. These are loaded progressively, if needed.
148      * There are three states. $_categories = null initially when nothing is
149      * loaded; $_categories = array($id => $cat, $parentid => null) when we have
150      * loaded $_course->category, but not any parents; and a complete array once
151      * everything is loaded.
152      */
153     protected $_categories = null;
155     /**
156      * @var array An array of CSS classes that should be added to the body tag in HTML.
157      */
158     protected $_bodyclasses = array();
160     /**
161      * @var string The title for the page. Used within the title tag in the HTML head.
162      */
163     protected $_title = '';
165     /**
166      * @var string The string to use as the heading of the page. Shown near the top of the
167      * page within most themes.
168      */
169     protected $_heading = '';
171     /**
172      * @var string The pagetype is used to describe the page and defaults to a representation
173      * of the physical path to the page e.g. my-index, mod-quiz-attempt
174      */
175     protected $_pagetype = null;
177     /**
178      * @var string The pagelayout to use when displaying this page. The
179      * pagelayout needs to have been defined by the theme in use, or one of its
180      * parents. By default base is used however standard is the more common layout.
181      * Note that this gets automatically set by core during operations like
182      * require_login.
183      */
184     protected $_pagelayout = 'base';
186     /**
187      * @var array List of theme layout options, these are ignored by core.
188      * To be used in individual theme layout files only.
189      */
190     protected $_layout_options = null;
192     /**
193      * @var string An optional arbitrary parameter that can be set on pages where the context
194      * and pagetype is not enough to identify the page.
195      */
196     protected $_subpage = '';
198     /**
199      * @var string Set a different path to use for the 'Moodle docs for this page' link.
200      * By default, it uses the path of the file for instance mod/quiz/attempt.
201      */
202     protected $_docspath = null;
204     /**
205      * @var string A legacy class that will be added to the body tag
206      */
207     protected $_legacyclass = null;
209     /**
210      * @var moodle_url The URL for this page. This is mandatory and must be set
211      * before output is started.
212      */
213     protected $_url = null;
215     /**
216      * @var array An array of links to alternative versions of this page.
217      * Primarily used for RSS versions of the current page.
218      */
219     protected $_alternateversions = array();
221     /**
222      * @var block_manager The blocks manager for this page. It is responsible for
223      * the blocks and there content on this page.
224      */
225     protected $_blocks = null;
227     /**
228      * @var page_requirements_manager Page requirements manager. It is responsible
229      * for all JavaScript and CSS resources required by this page.
230      */
231     protected $_requires = null;
233     /**
234      * @var string The capability required by the user in order to edit blocks
235      * and block settings on this page.
236      */
237     protected $_blockseditingcap = 'moodle/site:manageblocks';
239     /**
240      * @var bool An internal flag to record when block actions have been processed.
241      * Remember block actions occur on the current URL and it is important that
242      * even they are never executed more than once.
243      */
244     protected $_block_actions_done = false;
246     /**
247      * @var array An array of any other capabilities the current user must have
248      * in order to editing the page and/or its content (not just blocks).
249      */
250     protected $_othereditingcaps = array();
252     /**
253      * @var bool Sets whether this page should be cached by the browser or not.
254      * If it is set to true (default) the page is served with caching headers.
255      */
256     protected $_cacheable = true;
258     /**
259      * @var string Can be set to the ID of an element on the page, if done that
260      * element receives focus when the page loads.
261      */
262     protected $_focuscontrol = '';
264     /**
265      * @var string HTML to go where the turn on editing button is located. This
266      * is nearly a legacy item and not used very often any more.
267      */
268     protected $_button = '';
270     /**
271      * @var theme_config The theme to use with this page. This has to be properly
272      * initialised via {@link moodle_page::initialise_theme_and_output()} which
273      * happens magically before any operation that requires it.
274      */
275     protected $_theme = null;
277     /**
278      * @var global_navigation Contains the global navigation structure.
279      */
280     protected $_navigation = null;
282     /**
283      * @var settings_navigation Contains the settings navigation structure.
284      */
285     protected $_settingsnav = null;
287     /**
288      * @var navbar Contains the navbar structure.
289      */
290     protected $_navbar = null;
292     /**
293      * @var string The menu (or actions) to display in the heading.
294      */
295     protected $_headingmenu = null;
297     /**
298      * @var array stack trace. Then the theme is initialised, we save the stack
299      * trace, for use in error messages.
300      */
301     protected $_wherethemewasinitialised = null;
303     /**
304      * @var xhtml_container_stack Tracks XHTML tags on this page that have been
305      * opened but not closed.
306      */
307     protected $_opencontainers;
309     /**
310      * @var int Sets the page to refresh after a given delay (in seconds) using
311      * meta refresh in {@link standard_head_html()} in outputlib.php
312      * If set to null(default) the page is not refreshed
313      */
314     protected $_periodicrefreshdelay = null;
316     /**
317      * @var array Associative array of browser shortnames (as used by check_browser_version)
318      * and their minimum required versions
319      */
320     protected $_legacybrowsers = array('MSIE' => 6.0);
322     /**
323      * @var string Is set to the name of the device type in use.
324      * This will we worked out when it is first used.
325      */
326     protected $_devicetypeinuse = null;
328     /**
329      * @var bool Used to determine if HTTPS should be required for login.
330      */
331     protected $_https_login_required = false;
333     /**
334      * @var bool Determines if popup notifications allowed on this page.
335      * Code such as the quiz module disables popup notifications in situations
336      * such as upgrading or completing a quiz.
337      */
338     protected $_popup_notification_allowed = true;
340     // Magic getter methods =============================================================
341     // Due to the __get magic below, you normally do not call these as $PAGE->magic_get_x
342     // methods, but instead use the $PAGE->x syntax.
344     /**
345      * Please do not call this method directly, use the ->state syntax. {@link moodle_page::__get()}.
346      * @return integer one of the STATE_XXX constants. You should not normally need
347      * to use this in your code. It is intended for internal use by this class
348      * and its friends like print_header, to check that everything is working as
349      * expected. Also accessible as $PAGE->state.
350      */
351     protected function magic_get_state() {
352         return $this->_state;
353     }
355     /**
356      * Please do not call this method directly, use the ->headerprinted syntax. {@link moodle_page::__get()}.
357      * @return bool has the header already been printed?
358      */
359     protected function magic_get_headerprinted() {
360         return $this->_state >= self::STATE_IN_BODY;
361     }
363     /**
364      * Please do not call this method directly, use the ->course syntax. {@link moodle_page::__get()}.
365      * @return stdClass the current course that we are inside - a row from the
366      * course table. (Also available as $COURSE global.) If we are not inside
367      * an actual course, this will be the site course.
368      */
369     protected function magic_get_course() {
370         global $SITE;
371         if (is_null($this->_course)) {
372             return $SITE;
373         }
374         return $this->_course;
375     }
377     /**
378      * Please do not call this method directly, use the ->cm syntax. {@link moodle_page::__get()}.
379      * @return cm_info the course_module that this page belongs to. Will be null
380      * if this page is not within a module. This is a full cm object, as loaded
381      * by get_coursemodule_from_id or get_coursemodule_from_instance,
382      * so the extra modname and name fields are present.
383      */
384     protected function magic_get_cm() {
385         return $this->_cm;
386     }
388     /**
389      * Please do not call this method directly, use the ->activityrecord syntax. {@link moodle_page::__get()}.
390      * @return stdClass the row from the activities own database table (for example
391      * the forum or quiz table) that this page belongs to. Will be null
392      * if this page is not within a module.
393      */
394     protected function magic_get_activityrecord() {
395         if (is_null($this->_module) && !is_null($this->_cm)) {
396             $this->load_activity_record();
397         }
398         return $this->_module;
399     }
401     /**
402      * Please do not call this method directly, use the ->activityname syntax. {@link moodle_page::__get()}.
403      * @return string the The type of activity we are in, for example 'forum' or 'quiz'.
404      * Will be null if this page is not within a module.
405      */
406     protected function magic_get_activityname() {
407         if (is_null($this->_cm)) {
408             return null;
409         }
410         return $this->_cm->modname;
411     }
413     /**
414      * Please do not call this method directly, use the ->category syntax. {@link moodle_page::__get()}.
415      * @return stdClass the category that the page course belongs to. If there isn't one
416      * (that is, if this is the front page course) returns null.
417      */
418     protected function magic_get_category() {
419         $this->ensure_category_loaded();
420         if (!empty($this->_categories)) {
421             return reset($this->_categories);
422         } else {
423             return null;
424         }
425     }
427     /**
428      * Please do not call this method directly, use the ->categories syntax. {@link moodle_page::__get()}.
429      * @return array an array of all the categories the page course belongs to,
430      * starting with the immediately containing category, and working out to
431      * the top-level category. This may be the empty array if we are in the
432      * front page course.
433      */
434     protected function magic_get_categories() {
435         $this->ensure_categories_loaded();
436         return $this->_categories;
437     }
439     /**
440      * Please do not call this method directly, use the ->context syntax. {@link moodle_page::__get()}.
441      * @return context the main context to which this page belongs.
442      */
443     protected function magic_get_context() {
444         if (is_null($this->_context)) {
445             if (CLI_SCRIPT or NO_MOODLE_COOKIES) {
446                 // Cli scripts work in system context, do not annoy devs with debug info.
447                 // Very few scripts do not use cookies, we can safely use system as default context there.
448             } else {
449                 debugging('Coding problem: $PAGE->context was not set. You may have forgotten '
450                     .'to call require_login() or $PAGE->set_context(). The page may not display '
451                     .'correctly as a result');
452             }
453             $this->_context = context_system::instance();
454         }
455         return $this->_context;
456     }
458     /**
459      * Please do not call this method directly, use the ->pagetype syntax. {@link moodle_page::__get()}.
460      * @return string e.g. 'my-index' or 'mod-quiz-attempt'.
461      */
462     protected function magic_get_pagetype() {
463         global $CFG;
464         if (is_null($this->_pagetype) || isset($CFG->pagepath)) {
465             $this->initialise_default_pagetype();
466         }
467         return $this->_pagetype;
468     }
470     /**
471      * Please do not call this method directly, use the ->pagetype syntax. {@link moodle_page::__get()}.
472      * @return string The id to use on the body tag, uses {@link magic_get_pagetype()}.
473      */
474     protected function magic_get_bodyid() {
475         return 'page-'.$this->pagetype;
476     }
478     /**
479      * Please do not call this method directly, use the ->pagelayout syntax. {@link moodle_page::__get()}.
480      * @return string the general type of page this is. For example 'standard', 'popup', 'home'.
481      *      Allows the theme to display things differently, if it wishes to.
482      */
483     protected function magic_get_pagelayout() {
484         return $this->_pagelayout;
485     }
487     /**
488      * Please do not call this method directly, use the ->layout_options syntax. {@link moodle_page::__get()}.
489      * @return array returns arrays with options for layout file
490      */
491     protected function magic_get_layout_options() {
492         if (!is_array($this->_layout_options)) {
493             $this->_layout_options = $this->_theme->pagelayout_options($this->pagelayout);
494         }
495         return $this->_layout_options;
496     }
498     /**
499      * Please do not call this method directly, use the ->subpage syntax. {@link moodle_page::__get()}.
500      * @return string The subpage identifier, if any.
501      */
502     protected function magic_get_subpage() {
503         return $this->_subpage;
504     }
506     /**
507      * Please do not call this method directly, use the ->bodyclasses syntax. {@link moodle_page::__get()}.
508      * @return string the class names to put on the body element in the HTML.
509      */
510     protected function magic_get_bodyclasses() {
511         return implode(' ', array_keys($this->_bodyclasses));
512     }
514     /**
515      * Please do not call this method directly, use the ->title syntax. {@link moodle_page::__get()}.
516      * @return string the title that should go in the <head> section of the HTML of this page.
517      */
518     protected function magic_get_title() {
519         return $this->_title;
520     }
522     /**
523      * Please do not call this method directly, use the ->heading syntax. {@link moodle_page::__get()}.
524      * @return string the main heading that should be displayed at the top of the <body>.
525      */
526     protected function magic_get_heading() {
527         return $this->_heading;
528     }
530     /**
531      * Please do not call this method directly, use the ->heading syntax. {@link moodle_page::__get()}.
532      * @return string The menu (or actions) to display in the heading
533      */
534     protected function magic_get_headingmenu() {
535         return $this->_headingmenu;
536     }
538     /**
539      * Please do not call this method directly, use the ->docspath syntax. {@link moodle_page::__get()}.
540      * @return string the path to the Moodle docs for this page.
541      */
542     protected function magic_get_docspath() {
543         if (is_string($this->_docspath)) {
544             return $this->_docspath;
545         } else {
546             return str_replace('-', '/', $this->pagetype);
547         }
548     }
550     /**
551      * Please do not call this method directly, use the ->url syntax. {@link moodle_page::__get()}.
552      * @return moodle_url the clean URL required to load the current page. (You
553      * should normally use this in preference to $ME or $FULLME.)
554      */
555     protected function magic_get_url() {
556         global $FULLME;
557         if (is_null($this->_url)) {
558             debugging('This page did not call $PAGE->set_url(...). Using '.s($FULLME), DEBUG_DEVELOPER);
559             $this->_url = new moodle_url($FULLME);
560             // Make sure the guessed URL cannot lead to dangerous redirects.
561             $this->_url->remove_params('sesskey');
562         }
563         return new moodle_url($this->_url); // Return a clone for safety.
564     }
566     /**
567      * The list of alternate versions of this page.
568      * @return array mime type => object with ->url and ->title.
569      */
570     protected function magic_get_alternateversions() {
571         return $this->_alternateversions;
572     }
574     /**
575      * Please do not call this method directly, use the ->blocks syntax. {@link moodle_page::__get()}.
576      * @return block_manager the blocks manager object for this page.
577      */
578     protected function magic_get_blocks() {
579         global $CFG;
580         if (is_null($this->_blocks)) {
581             if (!empty($CFG->blockmanagerclass)) {
582                 if (!empty($CFG->blockmanagerclassfile)) {
583                     require_once($CFG->blockmanagerclassfile);
584                 }
585                 $classname = $CFG->blockmanagerclass;
586             } else {
587                 $classname = 'block_manager';
588             }
589             $this->_blocks = new $classname($this);
590         }
591         return $this->_blocks;
592     }
594     /**
595      * Please do not call this method directly, use the ->requires syntax. {@link moodle_page::__get()}.
596      * @return page_requirements_manager tracks the JavaScript, CSS files, etc. required by this page.
597      */
598     protected function magic_get_requires() {
599         if (is_null($this->_requires)) {
600             $this->_requires = new page_requirements_manager();
601         }
602         return $this->_requires;
603     }
605     /**
606      * Please do not call this method directly, use the ->cacheable syntax. {@link moodle_page::__get()}.
607      * @return bool can this page be cached by the user's browser.
608      */
609     protected function magic_get_cacheable() {
610         return $this->_cacheable;
611     }
613     /**
614      * Please do not call this method directly, use the ->focuscontrol syntax. {@link moodle_page::__get()}.
615      * @return string the id of the HTML element to be focused when the page has loaded.
616      */
617     protected function magic_get_focuscontrol() {
618         return $this->_focuscontrol;
619     }
621     /**
622      * Please do not call this method directly, use the ->button syntax. {@link moodle_page::__get()}.
623      * @return string the HTML to go where the Turn editing on button normally goes.
624      */
625     protected function magic_get_button() {
626         return $this->_button;
627     }
629     /**
630      * Please do not call this method directly, use the ->theme syntax. {@link moodle_page::__get()}.
631      * @return theme_config the initialised theme for this page.
632      */
633     protected function magic_get_theme() {
634         if (is_null($this->_theme)) {
635             $this->initialise_theme_and_output();
636         }
637         return $this->_theme;
638     }
640     /**
641      * Returns an array of minipulations or false if there are none to make.
642      *
643      * @since 2.5.1 2.6
644      * @return bool|array
645      */
646     protected function magic_get_blockmanipulations() {
647         if (!right_to_left()) {
648             return false;
649         }
650         if (is_null($this->_theme)) {
651             $this->initialise_theme_and_output();
652         }
653         return $this->_theme->blockrtlmanipulations;
654     }
656     /**
657      * Please do not call this method directly, use the ->devicetypeinuse syntax. {@link moodle_page::__get()}.
658      * @return string The device type being used.
659      */
660     protected function magic_get_devicetypeinuse() {
661         if (empty($this->_devicetypeinuse)) {
662             $this->_devicetypeinuse = get_user_device_type();
663         }
664         return $this->_devicetypeinuse;
665     }
667     /**
668      * Please do not call this method directly use the ->periodicrefreshdelay syntax
669      * {@link moodle_page::__get()}
670      * @return int The periodic refresh delay to use with meta refresh
671      */
672     protected function magic_get_periodicrefreshdelay() {
673         return $this->_periodicrefreshdelay;
674     }
676     /**
677      * Please do not call this method directly use the ->opencontainers syntax. {@link moodle_page::__get()}
678      * @return xhtml_container_stack tracks XHTML tags on this page that have been opened but not closed.
679      *      mainly for internal use by the rendering code.
680      */
681     protected function magic_get_opencontainers() {
682         if (is_null($this->_opencontainers)) {
683             $this->_opencontainers = new xhtml_container_stack();
684         }
685         return $this->_opencontainers;
686     }
688     /**
689      * Return the navigation object
690      * @return global_navigation
691      */
692     protected function magic_get_navigation() {
693         if ($this->_navigation === null) {
694             $this->_navigation = new global_navigation($this);
695         }
696         return $this->_navigation;
697     }
699     /**
700      * Return a navbar object
701      * @return navbar
702      */
703     protected function magic_get_navbar() {
704         if ($this->_navbar === null) {
705             $this->_navbar = new navbar($this);
706         }
707         return $this->_navbar;
708     }
710     /**
711      * Returns the settings navigation object
712      * @return settings_navigation
713      */
714     protected function magic_get_settingsnav() {
715         if ($this->_settingsnav === null) {
716             $this->_settingsnav = new settings_navigation($this);
717             $this->_settingsnav->initialise();
718         }
719         return $this->_settingsnav;
720     }
722     /**
723      * PHP overloading magic to make the $PAGE->course syntax work by redirecting
724      * it to the corresponding $PAGE->magic_get_course() method if there is one, and
725      * throwing an exception if not.
726      *
727      * @param string $name property name
728      * @return mixed
729      * @throws coding_exception
730      */
731     public function __get($name) {
732         $getmethod = 'magic_get_' . $name;
733         if (method_exists($this, $getmethod)) {
734             return $this->$getmethod();
735         } else {
736             throw new coding_exception('Unknown property ' . $name . ' of $PAGE.');
737         }
738     }
740     /**
741      * PHP overloading magic to catch obvious coding errors.
742      *
743      * This method has been created to catch obvious coding errors where the
744      * developer has tried to set a page property using $PAGE->key = $value.
745      * In the moodle_page class all properties must be set using the appropriate
746      * $PAGE->set_something($value) method.
747      *
748      * @param string $name property name
749      * @param mixed $value Value
750      * @return void Throws exception if field not defined in page class
751      * @throws coding_exception
752      */
753     public function __set($name, $value) {
754         if (method_exists($this, 'set_' . $name)) {
755             throw new coding_exception('Invalid attempt to modify page object', "Use \$PAGE->set_$name() instead.");
756         } else {
757             throw new coding_exception('Invalid attempt to modify page object', "Unknown property $name");
758         }
759     }
761     // Other information getting methods ==========================================.
763     /**
764      * Returns instance of page renderer
765      *
766      * @param string $component name such as 'core', 'mod_forum' or 'qtype_multichoice'.
767      * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
768      * @param string $target one of rendering target constants
769      * @return renderer_base
770      */
771     public function get_renderer($component, $subtype = null, $target = null) {
772         return $this->magic_get_theme()->get_renderer($this, $component, $subtype, $target);
773     }
775     /**
776      * Checks to see if there are any items on the navbar object
777      *
778      * @return bool true if there are, false if not
779      */
780     public function has_navbar() {
781         if ($this->_navbar === null) {
782             $this->_navbar = new navbar($this);
783         }
784         return $this->_navbar->has_items();
785     }
787     /**
788      * Should the current user see this page in editing mode.
789      * That is, are they allowed to edit this page, and are they currently in
790      * editing mode.
791      * @return bool
792      */
793     public function user_is_editing() {
794         global $USER;
795         return !empty($USER->editing) && $this->user_allowed_editing();
796     }
798     /**
799      * Does the user have permission to edit blocks on this page.
800      * @return bool
801      */
802     public function user_can_edit_blocks() {
803         return has_capability($this->_blockseditingcap, $this->_context);
804     }
806     /**
807      * Does the user have permission to see this page in editing mode.
808      * @return bool
809      */
810     public function user_allowed_editing() {
811         return has_any_capability($this->all_editing_caps(), $this->_context);
812     }
814     /**
815      * Get a description of this page. Normally displayed in the footer in developer debug mode.
816      * @return string
817      */
818     public function debug_summary() {
819         $summary = '';
820         $summary .= 'General type: ' . $this->pagelayout . '. ';
821         if (!during_initial_install()) {
822             $summary .= 'Context ' . $this->context->get_context_name() . ' (context id ' . $this->_context->id . '). ';
823         }
824         $summary .= 'Page type ' . $this->pagetype .  '. ';
825         if ($this->subpage) {
826             $summary .= 'Sub-page ' . $this->subpage .  '. ';
827         }
828         return $summary;
829     }
831     // Setter methods =============================================================.
833     /**
834      * Set the state.
835      *
836      * The state must be one of that STATE_... constants, and the state is only allowed to advance one step at a time.
837      *
838      * @param int $state The new state.
839      * @throws coding_exception
840      */
841     public function set_state($state) {
842         if ($state != $this->_state + 1 || $state > self::STATE_DONE) {
843             throw new coding_exception('Invalid state passed to moodle_page::set_state. We are in state ' .
844                     $this->_state . ' and state ' . $state . ' was requested.');
845         }
847         if ($state == self::STATE_PRINTING_HEADER) {
848             $this->starting_output();
849         }
851         $this->_state = $state;
852     }
854     /**
855      * Set the current course. This sets both $PAGE->course and $COURSE. It also
856      * sets the right theme and locale.
857      *
858      * Normally you don't need to call this function yourself, require_login will
859      * call it for you if you pass a $course to it. You can use this function
860      * on pages that do need to call require_login().
861      *
862      * Sets $PAGE->context to the course context, if it is not already set.
863      *
864      * @param stdClass $course the course to set as the global course.
865      * @throws coding_exception
866      */
867     public function set_course($course) {
868         global $COURSE, $PAGE, $CFG, $SITE;
870         if (empty($course->id)) {
871             throw new coding_exception('$course passed to moodle_page::set_course does not look like a proper course object.');
872         }
874         $this->ensure_theme_not_set();
876         if (!empty($this->_course->id) && $this->_course->id != $course->id) {
877             $this->_categories = null;
878         }
880         $this->_course = clone($course);
882         if ($this === $PAGE) {
883             $COURSE = $this->_course;
884             moodle_setlocale();
885         }
887         if (!$this->_context) {
888             $this->set_context(context_course::instance($this->_course->id));
889         }
891         // Notify course format that this page is set for the course.
892         if ($this->_course->id != $SITE->id) {
893             require_once($CFG->dirroot.'/course/lib.php');
894             $courseformat = course_get_format($this->_course);
895             $this->add_body_class('format-'. $courseformat->get_format());
896             $courseformat->page_set_course($this);
897         } else {
898             $this->add_body_class('format-site');
899         }
900     }
902     /**
903      * Set the main context to which this page belongs.
904      *
905      * @param context $context a context object. You normally get this with context_xxxx::instance().
906      */
907     public function set_context($context) {
908         if ($context === null) {
909             // Extremely ugly hack which sets context to some value in order to prevent warnings,
910             // use only for core error handling!!!!
911             if (!$this->_context) {
912                 $this->_context = context_system::instance();
913             }
914             return;
915         }
917         // Ideally we should set context only once.
918         if (isset($this->_context) && $context->id !== $this->_context->id) {
919             $current = $this->_context->contextlevel;
920             if ($current == CONTEXT_SYSTEM or $current == CONTEXT_COURSE) {
921                 // Hmm - not ideal, but it might produce too many warnings due to the design of require_login.
922             } else if ($current == CONTEXT_MODULE and ($parentcontext = $context->get_parent_context()) and
923                 $this->_context->id == $parentcontext->id) {
924                 // Hmm - most probably somebody did require_login() and after that set the block context.
925             } else {
926                 // We do not want devs to do weird switching of context levels on the fly because we might have used
927                 // the context already such as in text filter in page title.
928                 debugging("Coding problem: unsupported modification of PAGE->context from {$current} to {$context->contextlevel}");
929             }
930         }
932         $this->_context = $context;
933     }
935     /**
936      * The course module that this page belongs to (if it does belong to one).
937      *
938      * @param stdClass|cm_info $cm a record from course_modules table or cm_info from get_fast_modinfo().
939      * @param stdClass $course
940      * @param stdClass $module
941      * @return void
942      * @throws coding_exception
943      */
944     public function set_cm($cm, $course = null, $module = null) {
945         global $DB, $CFG, $SITE;
947         if (!isset($cm->id) || !isset($cm->course)) {
948             throw new coding_exception('Invalid $cm. It has to be instance of cm_info or record from the course_modules table.');
949         }
951         if (!$this->_course || $this->_course->id != $cm->course) {
952             if (!$course) {
953                 $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
954             }
955             if ($course->id != $cm->course) {
956                 throw new coding_exception('The course you passed to $PAGE->set_cm does not correspond to the $cm.');
957             }
958             $this->set_course($course);
959         }
961         // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
962         if (!($cm instanceof cm_info)) {
963             $modinfo = get_fast_modinfo($this->_course);
964             $cm = $modinfo->get_cm($cm->id);
965         }
966         $this->_cm = $cm;
968         // Unfortunately the context setting is a mess.
969         // Let's try to work around some common block problems and show some debug messages.
970         if (empty($this->_context) or $this->_context->contextlevel != CONTEXT_BLOCK) {
971             $context = context_module::instance($cm->id);
972             $this->set_context($context);
973         }
975         if ($module) {
976             $this->set_activity_record($module);
977         }
979         // Notify course format that this page is set for the course module.
980         if ($this->_course->id != $SITE->id) {
981             require_once($CFG->dirroot.'/course/lib.php');
982             course_get_format($this->_course)->page_set_cm($this);
983         }
984     }
986     /**
987      * Sets the activity record. This could be a row from the main table for a
988      * module. For instance if the current module (cm) is a forum this should be a row
989      * from the forum table.
990      *
991      * @param stdClass $module A row from the main database table for the module that this page belongs to.
992      * @throws coding_exception
993      */
994     public function set_activity_record($module) {
995         if (is_null($this->_cm)) {
996             throw new coding_exception('You cannot call $PAGE->set_activity_record until after $PAGE->cm has been set.');
997         }
998         if ($module->id != $this->_cm->instance || $module->course != $this->_course->id) {
999             throw new coding_exception('The activity record does not seem to correspond to the cm that has been set.');
1000         }
1001         $this->_module = $module;
1002     }
1004     /**
1005      * Sets the pagetype to use for this page.
1006      *
1007      * Normally you do not need to set this manually, it is automatically created
1008      * from the script name. However, on some pages this is overridden.
1009      * For example the page type for course/view.php includes the course format,
1010      * for example 'course-view-weeks'. This gets used as the id attribute on
1011      * <body> and also for determining which blocks are displayed.
1012      *
1013      * @param string $pagetype e.g. 'my-index' or 'mod-quiz-attempt'.
1014      */
1015     public function set_pagetype($pagetype) {
1016         $this->_pagetype = $pagetype;
1017     }
1019     /**
1020      * Sets the layout to use for this page.
1021      *
1022      * The page layout determines how the page will be displayed, things such as
1023      * block regions, content areas, etc are controlled by the layout.
1024      * The theme in use for the page will determine that the layout contains.
1025      *
1026      * This properly defaults to 'base', so you only need to call this function if
1027      * you want something different. The exact range of supported layouts is specified
1028      * in the standard theme.
1029      *
1030      * For an idea of the common page layouts see
1031      * {@link http://docs.moodle.org/dev/Themes_2.0#The_different_layouts_as_of_August_17th.2C_2010}
1032      * But please keep in mind that it may be (and normally is) out of date.
1033      * The only place to find an accurate up-to-date list of the page layouts
1034      * available for your version of Moodle is {@link theme/base/config.php}
1035      *
1036      * @param string $pagelayout the page layout this is. For example 'popup', 'home'.
1037      */
1038     public function set_pagelayout($pagelayout) {
1039         // Uncomment this to debug theme pagelayout issues like missing blocks.
1040         // if (!empty($this->_wherethemewasinitialised) && $pagelayout != $this->_pagelayout)
1041         //     debugging('Page layout has already been set and cannot be changed.', DEBUG_DEVELOPER);
1042         $this->_pagelayout = $pagelayout;
1043     }
1045     /**
1046      * If context->id and pagetype are not enough to uniquely identify this page,
1047      * then you can set a subpage id as well. For example, the tags page sets
1048      *
1049      * @param string $subpage an arbitrary identifier that, along with context->id
1050      *      and pagetype, uniquely identifies this page.
1051      */
1052     public function set_subpage($subpage) {
1053         if (empty($subpage)) {
1054             $this->_subpage = '';
1055         } else {
1056             $this->_subpage = $subpage;
1057         }
1058     }
1060     /**
1061      * Adds a CSS class to the body tag of the page.
1062      *
1063      * @param string $class add this class name ot the class attribute on the body tag.
1064      * @throws coding_exception
1065      */
1066     public function add_body_class($class) {
1067         if ($this->_state > self::STATE_BEFORE_HEADER) {
1068             throw new coding_exception('Cannot call moodle_page::add_body_class after output has been started.');
1069         }
1070         $this->_bodyclasses[$class] = 1;
1071     }
1073     /**
1074      * Adds an array of body classes to the body tag of this page.
1075      *
1076      * @param array $classes this utility method calls add_body_class for each array element.
1077      */
1078     public function add_body_classes($classes) {
1079         foreach ($classes as $class) {
1080             $this->add_body_class($class);
1081         }
1082     }
1084     /**
1085      * Sets the title for the page.
1086      * This is normally used within the title tag in the head of the page.
1087      *
1088      * @param string $title the title that should go in the <head> section of the HTML of this page.
1089      */
1090     public function set_title($title) {
1091         $title = format_string($title);
1092         $title = strip_tags($title);
1093         $title = str_replace('"', '&quot;', $title);
1094         $this->_title = $title;
1095     }
1097     /**
1098      * Sets the heading to use for the page.
1099      * This is normally used as the main heading at the top of the content.
1100      *
1101      * @param string $heading the main heading that should be displayed at the top of the <body>.
1102      */
1103     public function set_heading($heading) {
1104         $this->_heading = format_string($heading);
1105     }
1107     /**
1108      * Sets some HTML to use next to the heading {@link moodle_page::set_heading()}
1109      *
1110      * @param string $menu The menu/content to show in the heading
1111      */
1112     public function set_headingmenu($menu) {
1113         $this->_headingmenu = $menu;
1114     }
1116     /**
1117      * Set the course category this page belongs to manually.
1118      *
1119      * This automatically sets $PAGE->course to be the site course. You cannot
1120      * use this method if you have already set $PAGE->course - in that case,
1121      * the category must be the one that the course belongs to. This also
1122      * automatically sets the page context to the category context.
1123      *
1124      * @param int $categoryid The id of the category to set.
1125      * @throws coding_exception
1126      */
1127     public function set_category_by_id($categoryid) {
1128         global $SITE;
1129         if (!is_null($this->_course)) {
1130             throw new coding_exception('Course has already been set. You cannot change the category now.');
1131         }
1132         if (is_array($this->_categories)) {
1133             throw new coding_exception('Course category has already been set. You cannot to change it now.');
1134         }
1135         $this->ensure_theme_not_set();
1136         $this->set_course($SITE);
1137         $this->load_category($categoryid);
1138         $this->set_context(context_coursecat::instance($categoryid));
1139     }
1141     /**
1142      * Set a different path to use for the 'Moodle docs for this page' link.
1143      *
1144      * By default, it uses the pagetype, which is normally the same as the
1145      * script name. So, for example, for mod/quiz/attempt.php, pagetype is
1146      * mod-quiz-attempt, and so docspath is mod/quiz/attempt.
1147      *
1148      * @param string $path the path to use at the end of the moodle docs URL.
1149      */
1150     public function set_docs_path($path) {
1151         $this->_docspath = $path;
1152     }
1154     /**
1155      * You should call this method from every page to set the URL that should be used to return to this page.
1156      *
1157      * Used, for example, by the blocks editing UI to know where to return the
1158      * user after an action.
1159      * For example, course/view.php does:
1160      *      $id = optional_param('id', 0, PARAM_INT);
1161      *      $PAGE->set_url('/course/view.php', array('id' => $id));
1162      *
1163      * @param moodle_url|string $url URL relative to $CFG->wwwroot or {@link moodle_url} instance
1164      * @param array $params parameters to add to the URL
1165      * @throws coding_exception
1166      */
1167     public function set_url($url, array $params = null) {
1168         global $CFG;
1170         if (is_string($url) && strpos($url, 'http') !== 0) {
1171             if (strpos($url, '/') === 0) {
1172                 // We have to use httpswwwroot here, because of loginhttps pages.
1173                 $url = $CFG->httpswwwroot . $url;
1174             } else {
1175                 throw new coding_exception('Invalid parameter $url, has to be full url or in shortened form starting with /.');
1176             }
1177         }
1179         $this->_url = new moodle_url($url, $params);
1181         $fullurl = $this->_url->out_omit_querystring();
1182         if (strpos($fullurl, "$CFG->httpswwwroot/") !== 0) {
1183             debugging('Most probably incorrect set_page() url argument, it does not match the httpswwwroot!');
1184         }
1185         $shorturl = str_replace("$CFG->httpswwwroot/", '', $fullurl);
1187         if (is_null($this->_pagetype)) {
1188             $this->initialise_default_pagetype($shorturl);
1189         }
1190     }
1192     /**
1193      * Make sure page URL does not contain the given URL parameter.
1194      *
1195      * This should not be necessary if the script has called set_url properly.
1196      * However, in some situations like the block editing actions; when the URL
1197      * has been guessed, it will contain dangerous block-related actions.
1198      * Therefore, the blocks code calls this function to clean up such parameters
1199      * before doing any redirect.
1200      *
1201      * @param string $param the name of the parameter to make sure is not in the
1202      * page URL.
1203      */
1204     public function ensure_param_not_in_url($param) {
1205         $this->_url->remove_params($param);
1206     }
1208     /**
1209      * Sets an alternative version of this page.
1210      *
1211      * There can be alternate versions of some pages (for example an RSS feed version).
1212      * Call this method for each alternative version available.
1213      * For each alternative version a link will be included in the <head> tag.
1214      *
1215      * @param string $title The title to give the alternate version.
1216      * @param string|moodle_url $url The URL of the alternate version.
1217      * @param string $mimetype The mime-type of the alternate version.
1218      * @throws coding_exception
1219      */
1220     public function add_alternate_version($title, $url, $mimetype) {
1221         if ($this->_state > self::STATE_BEFORE_HEADER) {
1222             throw new coding_exception('Cannot call moodle_page::add_alternate_version after output has been started.');
1223         }
1224         $alt = new stdClass;
1225         $alt->title = $title;
1226         $alt->url = $url;
1227         $this->_alternateversions[$mimetype] = $alt;
1228     }
1230     /**
1231      * Specify a form control should be focused when the page has loaded.
1232      *
1233      * @param string $controlid the id of the HTML element to be focused.
1234      */
1235     public function set_focuscontrol($controlid) {
1236         $this->_focuscontrol = $controlid;
1237     }
1239     /**
1240      * Specify a fragment of HTML that goes where the 'Turn editing on' button normally goes.
1241      *
1242      * @param string $html the HTML to display there.
1243      */
1244     public function set_button($html) {
1245         $this->_button = $html;
1246     }
1248     /**
1249      * Set the capability that allows users to edit blocks on this page.
1250      *
1251      * Normally the default of 'moodle/site:manageblocks' is used, but a few
1252      * pages like the My Moodle page need to use a different capability
1253      * like 'moodle/my:manageblocks'.
1254      *
1255      * @param string $capability a capability.
1256      */
1257     public function set_blocks_editing_capability($capability) {
1258         $this->_blockseditingcap = $capability;
1259     }
1261     /**
1262      * Some pages let you turn editing on for reasons other than editing blocks.
1263      * If that is the case, you can pass other capabilities that let the user
1264      * edit this page here.
1265      *
1266      * @param string|array $capability either a capability, or an array of capabilities.
1267      */
1268     public function set_other_editing_capability($capability) {
1269         if (is_array($capability)) {
1270             $this->_othereditingcaps = array_unique($this->_othereditingcaps + $capability);
1271         } else {
1272             $this->_othereditingcaps[] = $capability;
1273         }
1274     }
1276     /**
1277      * Sets whether the browser should cache this page or not.
1278      *
1279      * @param bool $cacheable can this page be cached by the user's browser.
1280      */
1281     public function set_cacheable($cacheable) {
1282         $this->_cacheable = $cacheable;
1283     }
1285     /**
1286      * Sets the page to periodically refresh
1287      *
1288      * This function must be called before $OUTPUT->header has been called or
1289      * a coding exception will be thrown.
1290      *
1291      * @param int $delay Sets the delay before refreshing the page, if set to null refresh is cancelled.
1292      * @throws coding_exception
1293      */
1294     public function set_periodic_refresh_delay($delay = null) {
1295         if ($this->_state > self::STATE_BEFORE_HEADER) {
1296             throw new coding_exception('You cannot set a periodic refresh delay after the header has been printed');
1297         }
1298         if ($delay === null) {
1299             $this->_periodicrefreshdelay = null;
1300         } else if (is_int($delay)) {
1301             $this->_periodicrefreshdelay = $delay;
1302         }
1303     }
1305     /**
1306      * Force this page to use a particular theme.
1307      *
1308      * Please use this cautiously.
1309      * It is only intended to be used by the themes selector admin page.
1310      *
1311      * @param string $themename the name of the theme to use.
1312      */
1313     public function force_theme($themename) {
1314         $this->ensure_theme_not_set();
1315         $this->_theme = theme_config::load($themename);
1316     }
1318     /**
1319      * Reload theme settings.
1320      *
1321      * This is used when we need to reset settings
1322      * because they are now double cached in theme.
1323      */
1324     public function reload_theme() {
1325         if (!is_null($this->_theme)) {
1326             $this->_theme = theme_config::load($this->_theme->name);
1327         }
1328     }
1330     /**
1331      * This function indicates that current page requires the https when $CFG->loginhttps enabled.
1332      *
1333      * By using this function properly, we can ensure 100% https-ized pages
1334      * at our entire discretion (login, forgot_password, change_password)
1335      *
1336      * @return void
1337      * @throws coding_exception
1338      */
1339     public function https_required() {
1340         global $CFG;
1342         if (!is_null($this->_url)) {
1343             throw new coding_exception('https_required() must be used before setting page url!');
1344         }
1346         $this->ensure_theme_not_set();
1348         $this->_https_login_required = true;
1350         if (!empty($CFG->loginhttps)) {
1351             $CFG->httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
1352         } else {
1353             $CFG->httpswwwroot = $CFG->wwwroot;
1354         }
1355     }
1357     /**
1358      * Makes sure that page previously marked with https_required() is really using https://, if not it redirects to https://
1359      *
1360      * @return void (may redirect to https://self)
1361      * @throws coding_exception
1362      */
1363     public function verify_https_required() {
1364         global $CFG, $FULLME;
1366         if (is_null($this->_url)) {
1367             throw new coding_exception('verify_https_required() must be called after setting page url!');
1368         }
1370         if (!$this->_https_login_required) {
1371             throw new coding_exception('verify_https_required() must be called only after https_required()!');
1372         }
1374         if (empty($CFG->loginhttps)) {
1375             // Https not required, so stop checking.
1376             return;
1377         }
1379         if (strpos($this->_url, 'https://')) {
1380             // Detect if incorrect PAGE->set_url() used, it is recommended to use root-relative paths there.
1381             throw new coding_exception('Invalid page url. It must start with https:// for pages that set https_required()!');
1382         }
1384         if (!empty($CFG->sslproxy)) {
1385             // It does not make much sense to use sslproxy and loginhttps at the same time.
1386             return;
1387         }
1389         // Now the real test and redirect!
1390         // NOTE: do NOT use this test for detection of https on current page because this code is not compatible with SSL proxies,
1391         //       instead use (strpos($CFG->httpswwwroot, 'https:') === 0).
1392         if (strpos($FULLME, 'https:') !== 0) {
1393             // This may lead to infinite redirect on an incorrectly configured site.
1394             // In that case set $CFG->loginhttps=0; within /config.php.
1395             redirect($this->_url);
1396         }
1397     }
1399     // Initialisation methods =====================================================
1400     // These set various things up in a default way.
1402     /**
1403      * This method is called when the page first moves out of the STATE_BEFORE_HEADER
1404      * state. This is our last change to initialise things.
1405      */
1406     protected function starting_output() {
1407         global $CFG;
1409         if (!during_initial_install()) {
1410             $this->blocks->load_blocks();
1411             if (empty($this->_block_actions_done)) {
1412                 $this->_block_actions_done = true;
1413                 if ($this->blocks->process_url_actions($this)) {
1414                     redirect($this->url->out(false));
1415                 }
1416             }
1417             $this->blocks->create_all_block_instances();
1418         }
1420         // If maintenance mode is on, change the page header.
1421         if (!empty($CFG->maintenance_enabled)) {
1422             $this->set_button('<a href="' . $CFG->wwwroot . '/' . $CFG->admin .
1423                     '/settings.php?section=maintenancemode">' . get_string('maintenancemode', 'admin') .
1424                     '</a> ' . $this->button);
1426             $title = $this->title;
1427             if ($title) {
1428                 $title .= ' - ';
1429             }
1430             $this->set_title($title . get_string('maintenancemode', 'admin'));
1431         } else {
1432             // Show the messaging popup if there are messages.
1433             message_popup_window();
1434         }
1436         $this->initialise_standard_body_classes();
1437     }
1439     /**
1440      * Method for use by Moodle core to set up the theme. Do not
1441      * use this in your own code.
1442      *
1443      * Make sure the right theme for this page is loaded. Tell our
1444      * blocks_manager about the theme block regions, and then, if
1445      * we are $PAGE, set up the global $OUTPUT.
1446      *
1447      * @return void
1448      */
1449     public function initialise_theme_and_output() {
1450         global $OUTPUT, $PAGE, $SITE, $CFG;
1452         if (!empty($this->_wherethemewasinitialised)) {
1453             return;
1454         }
1456         if (!during_initial_install()) {
1457             // Detect PAGE->context mess.
1458             $this->magic_get_context();
1459         }
1461         if (!$this->_course && !during_initial_install()) {
1462             $this->set_course($SITE);
1463         }
1465         if (is_null($this->_theme)) {
1466             $themename = $this->resolve_theme();
1467             $this->_theme = theme_config::load($themename);
1468         }
1470         $this->_theme->setup_blocks($this->pagelayout, $this->blocks);
1471         if ($this->_theme->enable_dock && !empty($CFG->allowblockstodock)) {
1472             $this->requires->strings_for_js(array('addtodock', 'undockitem', 'dockblock', 'undockblock', 'undockall', 'hidedockpanel', 'hidepanel'), 'block');
1473             $this->requires->string_for_js('thisdirectionvertical', 'langconfig');
1474             $this->requires->yui_module('moodle-core-dock-loader', 'M.core.dock.loader.initLoader');
1475         }
1477         if ($this === $PAGE) {
1478             $OUTPUT = $this->get_renderer('core');
1479         }
1481         $this->_wherethemewasinitialised = debug_backtrace();
1482     }
1484     /**
1485      * Work out the theme this page should use.
1486      *
1487      * This depends on numerous $CFG settings, and the properties of this page.
1488      *
1489      * @return string the name of the theme that should be used on this page.
1490      */
1491     protected function resolve_theme() {
1492         global $CFG, $USER, $SESSION;
1494         if (empty($CFG->themeorder)) {
1495             $themeorder = array('course', 'category', 'session', 'user', 'site');
1496         } else {
1497             $themeorder = $CFG->themeorder;
1498             // Just in case, make sure we always use the site theme if nothing else matched.
1499             $themeorder[] = 'site';
1500         }
1502         $mnetpeertheme = '';
1503         if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id) {
1504             require_once($CFG->dirroot.'/mnet/peer.php');
1505             $mnetpeer = new mnet_peer();
1506             $mnetpeer->set_id($USER->mnethostid);
1507             if ($mnetpeer->force_theme == 1 && $mnetpeer->theme != '') {
1508                 $mnetpeertheme = $mnetpeer->theme;
1509             }
1510         }
1512         foreach ($themeorder as $themetype) {
1513             switch ($themetype) {
1514                 case 'course':
1515                     if (!empty($CFG->allowcoursethemes) && !empty($this->_course->theme) && $this->devicetypeinuse == 'default') {
1516                         return $this->_course->theme;
1517                     }
1518                 break;
1520                 case 'category':
1521                     if (!empty($CFG->allowcategorythemes) && $this->devicetypeinuse == 'default') {
1522                         $categories = $this->categories;
1523                         foreach ($categories as $category) {
1524                             if (!empty($category->theme)) {
1525                                 return $category->theme;
1526                             }
1527                         }
1528                     }
1529                 break;
1531                 case 'session':
1532                     if (!empty($SESSION->theme)) {
1533                         return $SESSION->theme;
1534                     }
1535                 break;
1537                 case 'user':
1538                     if (!empty($CFG->allowuserthemes) && !empty($USER->theme) && $this->devicetypeinuse == 'default') {
1539                         if ($mnetpeertheme) {
1540                             return $mnetpeertheme;
1541                         } else {
1542                             return $USER->theme;
1543                         }
1544                     }
1545                 break;
1547                 case 'site':
1548                     if ($mnetpeertheme) {
1549                         return $mnetpeertheme;
1550                     }
1551                     // First try for the device the user is using.
1552                     $devicetheme = get_selected_theme_for_device_type($this->devicetypeinuse);
1553                     if (!empty($devicetheme)) {
1554                         return $devicetheme;
1555                     }
1556                     // Next try for the default device (as a fallback).
1557                     $devicetheme = get_selected_theme_for_device_type('default');
1558                     if (!empty($devicetheme)) {
1559                         return $devicetheme;
1560                     }
1561                     // The default device theme isn't set up - use the overall default theme.
1562                     return theme_config::DEFAULT_THEME;
1563             }
1564         }
1566         // We should most certainly have resolved a theme by now. Something has gone wrong.
1567         debugging('Error resolving the theme to use for this page.', DEBUG_DEVELOPER);
1568         return theme_config::DEFAULT_THEME;
1569     }
1572     /**
1573      * Sets ->pagetype from the script name. For example, if the script that was
1574      * run is mod/quiz/view.php, ->pagetype will be set to 'mod-quiz-view'.
1575      *
1576      * @param string $script the path to the script that should be used to
1577      * initialise ->pagetype. If not passed the $SCRIPT global will be used.
1578      * If legacy code has set $CFG->pagepath that will be used instead, and a
1579      * developer warning issued.
1580      */
1581     protected function initialise_default_pagetype($script = null) {
1582         global $CFG, $SCRIPT;
1584         if (isset($CFG->pagepath)) {
1585             debugging('Some code appears to have set $CFG->pagepath. That was a horrible deprecated thing. ' .
1586                     'Don\'t do it! Try calling $PAGE->set_pagetype() instead.');
1587             $script = $CFG->pagepath;
1588             unset($CFG->pagepath);
1589         }
1591         if (is_null($script)) {
1592             $script = ltrim($SCRIPT, '/');
1593             $len = strlen($CFG->admin);
1594             if (substr($script, 0, $len) == $CFG->admin) {
1595                 $script = 'admin' . substr($script, $len);
1596             }
1597         }
1599         $path = str_replace('.php', '', $script);
1600         if (substr($path, -1) == '/') {
1601             $path .= 'index';
1602         }
1604         if (empty($path) || $path == 'index') {
1605             $this->_pagetype = 'site-index';
1606         } else {
1607             $this->_pagetype = str_replace('/', '-', $path);
1608         }
1609     }
1611     /**
1612      * Initialises the CSS classes that will be added to body tag of the page.
1613      *
1614      * The function is responsible for adding all of the critical CSS classes
1615      * that describe the current page, and its state.
1616      * This includes classes that describe the following for example:
1617      *    - Current language
1618      *    - Language direction
1619      *    - YUI CSS initialisation
1620      *    - Pagelayout
1621      * These are commonly used in CSS to target specific types of pages.
1622      */
1623     protected function initialise_standard_body_classes() {
1624         global $CFG, $USER;
1626         $pagetype = $this->pagetype;
1627         if ($pagetype == 'site-index') {
1628             $this->_legacyclass = 'course';
1629         } else if (substr($pagetype, 0, 6) == 'admin-') {
1630             $this->_legacyclass = 'admin';
1631         }
1632         $this->add_body_class($this->_legacyclass);
1634         $pathbits = explode('-', trim($pagetype));
1635         for ($i = 1; $i < count($pathbits); $i++) {
1636             $this->add_body_class('path-' . join('-', array_slice($pathbits, 0, $i)));
1637         }
1639         $this->add_body_classes(get_browser_version_classes());
1640         $this->add_body_class('dir-' . get_string('thisdirection', 'langconfig'));
1641         $this->add_body_class('lang-' . current_language());
1642         $this->add_body_class('yui-skin-sam'); // Make YUI happy, if it is used.
1643         $this->add_body_class('yui3-skin-sam'); // Make YUI3 happy, if it is used.
1644         $this->add_body_class($this->url_to_class_name($CFG->wwwroot));
1646         // Extra class describing current page layout.
1647         $this->add_body_class('pagelayout-' . $this->_pagelayout);
1649         if (!during_initial_install()) {
1650             $this->add_body_class('course-' . $this->_course->id);
1651             $this->add_body_class('context-' . $this->_context->id);
1652         }
1654         if (!empty($this->_cm)) {
1655             $this->add_body_class('cmid-' . $this->_cm->id);
1656         }
1658         if (!empty($CFG->allowcategorythemes)) {
1659             $this->ensure_category_loaded();
1660             foreach ($this->_categories as $catid => $notused) {
1661                 $this->add_body_class('category-' . $catid);
1662             }
1663         } else {
1664             $catid = 0;
1665             if (is_array($this->_categories)) {
1666                 $catids = array_keys($this->_categories);
1667                 $catid = reset($catids);
1668             } else if (!empty($this->_course->category)) {
1669                 $catid = $this->_course->category;
1670             }
1671             if ($catid) {
1672                 $this->add_body_class('category-' . $catid);
1673             }
1674         }
1676         if (!isloggedin()) {
1677             $this->add_body_class('notloggedin');
1678         }
1680         if (!empty($USER->editing)) {
1681             $this->add_body_class('editing');
1682             if (optional_param('bui_moveid', false, PARAM_INT)) {
1683                 $this->add_body_class('blocks-moving');
1684             }
1685         }
1687         if (!empty($CFG->blocksdrag)) {
1688             $this->add_body_class('drag');
1689         }
1691         if ($this->_devicetypeinuse != 'default') {
1692             $this->add_body_class($this->_devicetypeinuse . 'theme');
1693         }
1694     }
1696     /**
1697      * Loads the activity record for the current CM object associated with this
1698      * page.
1699      *
1700      * This will load {@link moodle_page::$_module} with a row from the related
1701      * module table in the database.
1702      * For instance if {@link moodle_page::$_cm} is a forum then a row from the
1703      * forum table will be loaded.
1704      */
1705     protected function load_activity_record() {
1706         global $DB;
1707         if (is_null($this->_cm)) {
1708             return;
1709         }
1710         $this->_module = $DB->get_record($this->_cm->modname, array('id' => $this->_cm->instance));
1711     }
1713     /**
1714      * This function ensures that the category of the current course has been
1715      * loaded, and if not, the function loads it now.
1716      *
1717      * @return void
1718      * @throws coding_exception
1719      */
1720     protected function ensure_category_loaded() {
1721         if (is_array($this->_categories)) {
1722             return; // Already done.
1723         }
1724         if (is_null($this->_course)) {
1725             throw new coding_exception('Attempt to get the course category for this page before the course was set.');
1726         }
1727         if ($this->_course->category == 0) {
1728             $this->_categories = array();
1729         } else {
1730             $this->load_category($this->_course->category);
1731         }
1732     }
1734     /**
1735      * Loads the requested category into the pages categories array.
1736      *
1737      * @param int $categoryid
1738      * @throws moodle_exception
1739      */
1740     protected function load_category($categoryid) {
1741         global $DB;
1742         $category = $DB->get_record('course_categories', array('id' => $categoryid));
1743         if (!$category) {
1744             throw new moodle_exception('unknowncategory');
1745         }
1746         $this->_categories[$category->id] = $category;
1747         $parentcategoryids = explode('/', trim($category->path, '/'));
1748         array_pop($parentcategoryids);
1749         foreach (array_reverse($parentcategoryids) as $catid) {
1750             $this->_categories[$catid] = null;
1751         }
1752     }
1754     /**
1755      * Ensures that the category the current course is within, as well as all of
1756      * its parent categories, have been loaded.
1757      *
1758      * @return void
1759      */
1760     protected function ensure_categories_loaded() {
1761         global $DB;
1762         $this->ensure_category_loaded();
1763         if (!is_null(end($this->_categories))) {
1764             return; // Already done.
1765         }
1766         $idstoload = array_keys($this->_categories);
1767         array_shift($idstoload);
1768         $categories = $DB->get_records_list('course_categories', 'id', $idstoload);
1769         foreach ($idstoload as $catid) {
1770             $this->_categories[$catid] = $categories[$catid];
1771         }
1772     }
1774     /**
1775      * Ensure the theme has not been loaded yet. If it has an exception is thrown.
1776      * @source
1777      *
1778      * @throws coding_exception
1779      */
1780     protected function ensure_theme_not_set() {
1781         if (!is_null($this->_theme)) {
1782             throw new coding_exception('The theme has already been set up for this page ready for output. ' .
1783                     'Therefore, you can no longer change the theme, or anything that might affect what ' .
1784                     'the current theme is, for example, the course.',
1785                     'Stack trace when the theme was set up: ' . format_backtrace($this->_wherethemewasinitialised));
1786         }
1787     }
1789     /**
1790      * Converts the provided URL into a CSS class that be used within the page.
1791      * This is primarily used to add the wwwroot to the body tag as a CSS class.
1792      *
1793      * @param string $url
1794      * @return string
1795      */
1796     protected function url_to_class_name($url) {
1797         $bits = parse_url($url);
1798         $class = str_replace('.', '-', $bits['host']);
1799         if (!empty($bits['port'])) {
1800             $class .= '--' . $bits['port'];
1801         }
1802         if (!empty($bits['path'])) {
1803             $path = trim($bits['path'], '/');
1804             if ($path) {
1805                 $class .= '--' . str_replace('/', '-', $path);
1806             }
1807         }
1808         return $class;
1809     }
1811     /**
1812      * Combines all of the required editing caps for the page and returns them
1813      * as an array.
1814      *
1815      * @return array
1816      */
1817     protected function all_editing_caps() {
1818         $caps = $this->_othereditingcaps;
1819         $caps[] = $this->_blockseditingcap;
1820         return $caps;
1821     }
1823     /**
1824      * Returns true if the page URL has beem set.
1825      *
1826      * @return bool
1827      */
1828     public function has_set_url() {
1829         return ($this->_url!==null);
1830     }
1832     /**
1833      * Gets set when the block actions for the page have been processed.
1834      *
1835      * @param bool $setting
1836      */
1837     public function set_block_actions_done($setting = true) {
1838         $this->_block_actions_done = $setting;
1839     }
1841     /**
1842      * Are popup notifications allowed on this page?
1843      * Popup notifications may be disallowed in situations such as while upgrading or completing a quiz
1844      *
1845      * @return bool true if popup notifications may be displayed
1846      */
1847     public function get_popup_notification_allowed() {
1848         return $this->_popup_notification_allowed;
1849     }
1851     /**
1852      * Allow or disallow popup notifications on this page. Popups are allowed by default.
1853      *
1854      * @param bool $allowed true if notifications are allowed. False if not allowed. They are allowed by default.
1855      */
1856     public function set_popup_notification_allowed($allowed) {
1857         $this->_popup_notification_allowed = $allowed;
1858     }
1860     /**
1861      * Returns the block region having made any required theme manipulations.
1862      *
1863      * @since 2.5.1 2.6
1864      * @param string $region
1865      * @return string
1866      */
1867     public function apply_theme_region_manipulations($region) {
1868         if ($this->blockmanipulations && isset($this->blockmanipulations[$region])) {
1869             $regionwas = $region;
1870             $regionnow = $this->blockmanipulations[$region];
1871             if ($this->blocks->is_known_region($regionwas) && $this->blocks->is_known_region($regionnow)) {
1872                 // Both the before and after regions are known so we can swap them over.
1873                 return $regionnow;
1874             }
1875             // We didn't know about both, we won't swap them over.
1876             return $regionwas;
1877         }
1878         return $region;
1879     }