PageRenderTime 26ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 0ms

/moodle/lib/pagelib.php

#
PHP | 1924 lines | 965 code | 235 blank | 724 comment | 209 complexity | 3ad51e4b8031e72de1886561458f9141 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, Apache-2.0
  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/>.
  16. /**
  17. * This file contains the moodle_page class. There is normally a single instance
  18. * of this class in the $PAGE global variable. This class is a central repository
  19. * of information about the page we are building up to send back to the user.
  20. *
  21. * @package core
  22. * @subpackage lib
  23. * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
  24. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  25. */
  26. defined('MOODLE_INTERNAL') || die();
  27. /**
  28. * $PAGE is a central store of information about the current page we are
  29. * generating in response to the user's request.
  30. *
  31. * It does not do very much itself
  32. * except keep track of information, however, it serves as the access point to
  33. * some more significant components like $PAGE->theme, $PAGE->requires,
  34. * $PAGE->blocks, etc.
  35. *
  36. * @copyright 2009 Tim Hunt
  37. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  38. * @since Moodle 2.0
  39. *
  40. * @property-read string $activityname The type of activity we are in, for example 'forum' or 'quiz'.
  41. * Will be null if this page is not within a module.
  42. * @property-read object $activityrecord The row from the activities own database table (for example
  43. * the forum or quiz table) that this page belongs to. Will be null
  44. * if this page is not within a module.
  45. * @property-read array $alternativeversions Mime type => object with ->url and ->title.
  46. * @property-read blocks_manager $blocks The blocks manager object for this page.
  47. * @property-read string $bodyclasses Returns a string to use within the class attribute on the body tag.
  48. * @property-read string $button The HTML to go where the Turn editing on button normally goes.
  49. * @property-read bool $cacheable Defaults to true. Set to false to stop the page being cached at all.
  50. * @property-read array $categories An array of all the categories the page course belongs to,
  51. * starting with the immediately containing category, and working out to
  52. * the top-level category. This may be the empty array if we are in the
  53. * front page course.
  54. * @property-read mixed $category The category that the page course belongs to. If there isn't one returns null.
  55. * @property-read object $cm The course_module that this page belongs to. Will be null
  56. * if this page is not within a module. This is a full cm object, as loaded
  57. * by get_coursemodule_from_id or get_coursemodule_from_instance,
  58. * so the extra modname and name fields are present.
  59. * @property-read object $context The main context to which this page belongs.
  60. * @property-read object $course The current course that we are inside - a row from the
  61. * course table. (Also available as $COURSE global.) If we are not inside
  62. * an actual course, this will be the site course.
  63. * @property-read string $devicetypeinuse The name of the device type in use
  64. * @property-read string $docspath The path to the Moodle docs for this page.
  65. * @property-read string $focuscontrol The id of the HTML element to be focused when the page has loaded.
  66. * @property-read bool $headerprinted
  67. * @property-read string $heading The main heading that should be displayed at the top of the <body>.
  68. * @property-read string $headingmenu The menu (or actions) to display in the heading
  69. * @property-read array $layout_options Returns arrays with options for layout file.
  70. * @property-read navbar $navbar Returns the navbar object used to display the navbar
  71. * @property-read global_navigation $navigation Returns the global navigation structure
  72. * @property-read xml_container_stack $opencontainers Tracks XHTML tags on this page that have been opened but not closed.
  73. * mainly for internal use by the rendering code.
  74. * @property-read string $pagelayout The general type of page this is. For example 'normal', 'popup', 'home'.
  75. * Allows the theme to display things differently, if it wishes to.
  76. * @property-read string $pagetype Returns the page type string, should be used as the id for the body tag in the theme.
  77. * @property-read int $periodicrefreshdelay The periodic refresh delay to use with meta refresh
  78. * @property-read page_requirements_manager $requires Tracks the JavaScript, CSS files, etc. required by this page.
  79. * @property-read settings_navigation $settingsnav
  80. * @property-read int $state One of the STATE_... constants
  81. * @property-read string $subpage The subpage identifier, if any.
  82. * @property-read theme_config $theme Returns the initialised theme for this page.
  83. * @property-read string $title The title that should go in the <head> section of the HTML of this page.
  84. * @property-read moodle_url $url The moodle url object for this page.
  85. */
  86. class moodle_page {
  87. /**#@+ Tracks the where we are in the generation of the page. */
  88. const STATE_BEFORE_HEADER = 0;
  89. const STATE_PRINTING_HEADER = 1;
  90. const STATE_IN_BODY = 2;
  91. const STATE_DONE = 3;
  92. /**#@-*/
  93. /// Field declarations =========================================================
  94. protected $_state = self::STATE_BEFORE_HEADER;
  95. protected $_course = null;
  96. /**
  97. * If this page belongs to a module, this is the cm_info module description object.
  98. * @var cm_info
  99. */
  100. protected $_cm = null;
  101. /**
  102. * If $_cm is not null, then this will hold the corresponding row from the
  103. * modname table. For example, if $_cm->modname is 'quiz', this will be a
  104. * row from the quiz table.
  105. */
  106. protected $_module = null;
  107. /**
  108. * The context that this page belongs to.
  109. */
  110. protected $_context = null;
  111. /**
  112. * This holds any categories that $_course belongs to, starting with the
  113. * particular category it belongs to, and working out through any parent
  114. * categories to the top level. These are loaded progressively, if needed.
  115. * There are three states. $_categories = null initially when nothing is
  116. * loaded; $_categories = array($id => $cat, $parentid => null) when we have
  117. * loaded $_course->category, but not any parents; and a complete array once
  118. * everything is loaded.
  119. */
  120. protected $_categories = null;
  121. protected $_bodyclasses = array();
  122. protected $_title = '';
  123. protected $_heading = '';
  124. protected $_pagetype = null;
  125. protected $_pagelayout = 'base';
  126. /**
  127. * List of theme layout options, these are ignored by core.
  128. * To be used in individual theme layout files only.
  129. * @var array
  130. */
  131. protected $_layout_options = array();
  132. protected $_subpage = '';
  133. protected $_docspath = null;
  134. /** @var string|null A legacy class that will be added to the body tag */
  135. protected $_legacyclass = null;
  136. protected $_url = null;
  137. protected $_alternateversions = array();
  138. protected $_blocks = null;
  139. protected $_requires = null;
  140. protected $_blockseditingcap = 'moodle/site:manageblocks';
  141. protected $_block_actions_done = false;
  142. protected $_othereditingcaps = array();
  143. protected $_cacheable = true;
  144. protected $_focuscontrol = '';
  145. protected $_button = '';
  146. protected $_theme = null;
  147. /** @var global_navigation Contains the global navigation structure*/
  148. protected $_navigation = null;
  149. /** @var null|settings_navigation Contains the settings navigation structure*/
  150. protected $_settingsnav = null;
  151. /** @var null|navbar Contains the navbar structure*/
  152. protected $_navbar = null;
  153. /** @var string */
  154. protected $_headingmenu = null;
  155. /**
  156. * Then the theme is initialised, we save the stack trace, for use in error messages.
  157. * @var array stack trace.
  158. */
  159. protected $_wherethemewasinitialised = null;
  160. /** @var xhtml_container_stack tracks XHTML tags on this page that have been opened but not closed. */
  161. protected $_opencontainers;
  162. /**
  163. * Sets the page to refresh after a given delay (in seconds) using meta refresh
  164. * in {@link standard_head_html()} in outputlib.php
  165. * If set to null(default) the page is not refreshed
  166. * @var int|null
  167. */
  168. protected $_periodicrefreshdelay = null;
  169. /**
  170. * This is simply to improve backwards compatibility. If old code relies on
  171. * a page class that implements print_header, or complex logic in
  172. * user_allowed_editing then we stash an instance of that other class here,
  173. * and delegate to it in certain situations.
  174. */
  175. protected $_legacypageobject = null;
  176. /**
  177. * Associative array of browser shortnames (as used by check_browser_version)
  178. * and their minimum required versions
  179. * @var array
  180. */
  181. protected $_legacybrowsers = array('MSIE' => 6.0);
  182. /**
  183. * Is set to the name of the device type in use.
  184. * This will we worked out when it is first used.
  185. *
  186. * @var string
  187. */
  188. protected $_devicetypeinuse = null;
  189. protected $_https_login_required = false;
  190. protected $_popup_notification_allowed = true;
  191. /// Magic getter methods =============================================================
  192. /// Due to the __get magic below, you normally do not call these as $PAGE->magic_get_x
  193. /// methods, but instead use the $PAGE->x syntax.
  194. /**
  195. * Please do not call this method directly, use the ->state syntax. {@link __get()}.
  196. * @return integer one of the STATE_... constants. You should not normally need
  197. * to use this in your code. It is intended for internal use by this class
  198. * and its friends like print_header, to check that everything is working as
  199. * expected. Also accessible as $PAGE->state.
  200. */
  201. protected function magic_get_state() {
  202. return $this->_state;
  203. }
  204. /**
  205. * Please do not call this method directly, use the ->headerprinted syntax. {@link __get()}.
  206. * @return boolean has the header already been printed?
  207. */
  208. protected function magic_get_headerprinted() {
  209. return $this->_state >= self::STATE_IN_BODY;
  210. }
  211. /**
  212. * Please do not call this method directly, use the ->course syntax. {@link __get()}.
  213. *
  214. * @global object
  215. * @return object the current course that we are inside - a row from the
  216. * course table. (Also available as $COURSE global.) If we are not inside
  217. * an actual course, this will be the site course.
  218. */
  219. protected function magic_get_course() {
  220. global $SITE;
  221. if (is_null($this->_course)) {
  222. return $SITE;
  223. }
  224. return $this->_course;
  225. }
  226. /**
  227. * Please do not call this method directly, use the ->cm syntax. {@link __get()}.
  228. * @return object the course_module that this page belongs to. Will be null
  229. * if this page is not within a module. This is a full cm object, as loaded
  230. * by get_coursemodule_from_id or get_coursemodule_from_instance,
  231. * so the extra modname and name fields are present.
  232. * @return cm_info
  233. */
  234. protected function magic_get_cm() {
  235. return $this->_cm;
  236. }
  237. /**
  238. * Please do not call this method directly, use the ->activityrecord syntax. {@link __get()}.
  239. * @return object the row from the activities own database table (for example
  240. * the forum or quiz table) that this page belongs to. Will be null
  241. * if this page is not within a module.
  242. */
  243. protected function magic_get_activityrecord() {
  244. if (is_null($this->_module) && !is_null($this->_cm)) {
  245. $this->load_activity_record();
  246. }
  247. return $this->_module;
  248. }
  249. /**
  250. * Please do not call this method directly, use the ->activityname syntax. {@link __get()}.
  251. * @return string|null the The type of activity we are in, for example 'forum' or 'quiz'.
  252. * Will be null if this page is not within a module.
  253. */
  254. protected function magic_get_activityname() {
  255. if (is_null($this->_cm)) {
  256. return null;
  257. }
  258. return $this->_cm->modname;
  259. }
  260. /**
  261. * Please do not call this method directly, use the ->category syntax. {@link __get()}.
  262. * @return mixed the category that the page course belongs to. If there isn't one
  263. * (that is, if this is the front page course) returns null.
  264. */
  265. protected function magic_get_category() {
  266. $this->ensure_category_loaded();
  267. if (!empty($this->_categories)) {
  268. return reset($this->_categories);
  269. } else {
  270. return null;
  271. }
  272. }
  273. /**
  274. * Please do not call this method directly, use the ->categories syntax. {@link __get()}.
  275. * @return array an array of all the categories the page course belongs to,
  276. * starting with the immediately containing category, and working out to
  277. * the top-level category. This may be the empty array if we are in the
  278. * front page course.
  279. */
  280. protected function magic_get_categories() {
  281. $this->ensure_categories_loaded();
  282. return $this->_categories;
  283. }
  284. /**
  285. * Please do not call this method directly, use the ->context syntax. {@link __get()}.
  286. * @return object the main context to which this page belongs.
  287. */
  288. protected function magic_get_context() {
  289. if (is_null($this->_context)) {
  290. if (CLI_SCRIPT or NO_MOODLE_COOKIES) {
  291. // cli scripts work in system context, do not annoy devs with debug info
  292. // very few scripts do not use cookies, we can safely use system as default context there
  293. } else {
  294. debugging('Coding problem: $PAGE->context was not set. You may have forgotten '
  295. .'to call require_login() or $PAGE->set_context(). The page may not display '
  296. .'correctly as a result');
  297. }
  298. $this->_context = get_context_instance(CONTEXT_SYSTEM);
  299. }
  300. return $this->_context;
  301. }
  302. /**
  303. * Please do not call this method directly, use the ->pagetype syntax. {@link __get()}.
  304. * @return string e.g. 'my-index' or 'mod-quiz-attempt'.
  305. */
  306. protected function magic_get_pagetype() {
  307. global $CFG;
  308. if (is_null($this->_pagetype) || isset($CFG->pagepath)) {
  309. $this->initialise_default_pagetype();
  310. }
  311. return $this->_pagetype;
  312. }
  313. /**
  314. * Please do not call this method directly, use the ->pagetype syntax. {@link __get()}.
  315. * @return string The id to use on the body tag, uses {@link magic_get_pagetype()}.
  316. */
  317. protected function magic_get_bodyid() {
  318. return 'page-'.$this->pagetype;
  319. }
  320. /**
  321. * Please do not call this method directly, use the ->pagelayout syntax. {@link __get()}.
  322. * @return string the general type of page this is. For example 'standard', 'popup', 'home'.
  323. * Allows the theme to display things differently, if it wishes to.
  324. */
  325. protected function magic_get_pagelayout() {
  326. return $this->_pagelayout;
  327. }
  328. /**
  329. * Please do not call this method directly, use the ->layout_tions syntax. {@link __get()}.
  330. * @return array returns arrys with options for layout file
  331. */
  332. protected function magic_get_layout_options() {
  333. return $this->_layout_options;
  334. }
  335. /**
  336. * Please do not call this method directly, use the ->subpage syntax. {@link __get()}.
  337. * @return string|null The subpage identifier, if any.
  338. */
  339. protected function magic_get_subpage() {
  340. return $this->_subpage;
  341. }
  342. /**
  343. * Please do not call this method directly, use the ->bodyclasses syntax. {@link __get()}.
  344. * @return string the class names to put on the body element in the HTML.
  345. */
  346. protected function magic_get_bodyclasses() {
  347. return implode(' ', array_keys($this->_bodyclasses));
  348. }
  349. /**
  350. * Please do not call this method directly, use the ->title syntax. {@link __get()}.
  351. * @return string the title that should go in the <head> section of the HTML of this page.
  352. */
  353. protected function magic_get_title() {
  354. return $this->_title;
  355. }
  356. /**
  357. * Please do not call this method directly, use the ->heading syntax. {@link __get()}.
  358. * @return string the main heading that should be displayed at the top of the <body>.
  359. */
  360. protected function magic_get_heading() {
  361. return $this->_heading;
  362. }
  363. /**
  364. * Please do not call this method directly, use the ->heading syntax. {@link __get()}.
  365. * @return string The menu (or actions) to display in the heading
  366. */
  367. protected function magic_get_headingmenu() {
  368. return $this->_headingmenu;
  369. }
  370. /**
  371. * Please do not call this method directly, use the ->docspath syntax. {@link __get()}.
  372. * @return string the path to the Moodle docs for this page.
  373. */
  374. protected function magic_get_docspath() {
  375. if (is_string($this->_docspath)) {
  376. return $this->_docspath;
  377. } else {
  378. return str_replace('-', '/', $this->pagetype);
  379. }
  380. }
  381. /**
  382. * Please do not call this method directly, use the ->url syntax. {@link __get()}.
  383. * @return moodle_url the clean URL required to load the current page. (You
  384. * should normally use this in preference to $ME or $FULLME.)
  385. */
  386. protected function magic_get_url() {
  387. global $FULLME;
  388. if (is_null($this->_url)) {
  389. debugging('This page did not call $PAGE->set_url(...). Using '.s($FULLME), DEBUG_DEVELOPER);
  390. $this->_url = new moodle_url($FULLME);
  391. // Make sure the guessed URL cannot lead to dangerous redirects.
  392. $this->_url->remove_params('sesskey');
  393. }
  394. return new moodle_url($this->_url); // Return a clone for safety.
  395. }
  396. /**
  397. * The list of alternate versions of this page.
  398. * @return array mime type => object with ->url and ->title.
  399. */
  400. protected function magic_get_alternateversions() {
  401. return $this->_alternateversions;
  402. }
  403. /**
  404. * Please do not call this method directly, use the ->blocks syntax. {@link __get()}.
  405. * @return blocks_manager the blocks manager object for this page.
  406. */
  407. protected function magic_get_blocks() {
  408. global $CFG;
  409. if (is_null($this->_blocks)) {
  410. if (!empty($CFG->blockmanagerclass)) {
  411. $classname = $CFG->blockmanagerclass;
  412. } else {
  413. $classname = 'block_manager';
  414. }
  415. $this->_blocks = new $classname($this);
  416. }
  417. return $this->_blocks;
  418. }
  419. /**
  420. * Please do not call this method directly, use the ->requires syntax. {@link __get()}.
  421. * @return page_requirements_manager tracks the JavaScript, CSS files, etc. required by this page.
  422. */
  423. protected function magic_get_requires() {
  424. global $CFG;
  425. if (is_null($this->_requires)) {
  426. $this->_requires = new page_requirements_manager();
  427. }
  428. return $this->_requires;
  429. }
  430. /**
  431. * Please do not call this method directly, use the ->cacheable syntax. {@link __get()}.
  432. * @return boolean can this page be cached by the user's browser.
  433. */
  434. protected function magic_get_cacheable() {
  435. return $this->_cacheable;
  436. }
  437. /**
  438. * Please do not call this method directly, use the ->focuscontrol syntax. {@link __get()}.
  439. * @return string the id of the HTML element to be focused when the page has loaded.
  440. */
  441. protected function magic_get_focuscontrol() {
  442. return $this->_focuscontrol;
  443. }
  444. /**
  445. * Please do not call this method directly, use the ->button syntax. {@link __get()}.
  446. * @return string the HTML to go where the Turn editing on button normally goes.
  447. */
  448. protected function magic_get_button() {
  449. return $this->_button;
  450. }
  451. /**
  452. * Please do not call this method directly, use the ->theme syntax. {@link __get()}.
  453. * @return theme_config the initialised theme for this page.
  454. */
  455. protected function magic_get_theme() {
  456. if (is_null($this->_theme)) {
  457. $this->initialise_theme_and_output();
  458. }
  459. return $this->_theme;
  460. }
  461. /**
  462. * Please do not call this method directly, use the ->devicetypeinuse syntax. {@link __get()}.
  463. *
  464. * @return string The device type being used.
  465. */
  466. protected function magic_get_devicetypeinuse() {
  467. if (empty($this->_devicetypeinuse)) {
  468. $this->_devicetypeinuse = get_user_device_type();
  469. }
  470. return $this->_devicetypeinuse;
  471. }
  472. /**
  473. * Please do not call this method directly, use the ->legacythemeinuse syntax. {@link __get()}.
  474. * @deprecated since 2.1
  475. * @return bool
  476. */
  477. protected function magic_get_legacythemeinuse() {
  478. debugging('$PAGE->legacythemeinuse is a deprecated property - please use $PAGE->devicetypeinuse and check if it is equal to legacy.', DEBUG_DEVELOPER);
  479. return ($this->devicetypeinuse == 'legacy');
  480. }
  481. /**
  482. * Please do not call this method directly use the ->periodicrefreshdelay syntax
  483. * {@link __get()}
  484. * @return int The periodic refresh delay to use with meta refresh
  485. */
  486. protected function magic_get_periodicrefreshdelay() {
  487. return $this->_periodicrefreshdelay;
  488. }
  489. /**
  490. * Please do not call this method directly use the ->opencontainers syntax. {@link __get()}
  491. * @return xhtml_container_stack tracks XHTML tags on this page that have been opened but not closed.
  492. * mainly for internal use by the rendering code.
  493. */
  494. protected function magic_get_opencontainers() {
  495. if (is_null($this->_opencontainers)) {
  496. $this->_opencontainers = new xhtml_container_stack();
  497. }
  498. return $this->_opencontainers;
  499. }
  500. /**
  501. * Return the navigation object
  502. * @return global_navigation
  503. */
  504. protected function magic_get_navigation() {
  505. if ($this->_navigation === null) {
  506. $this->_navigation = new global_navigation($this);
  507. }
  508. return $this->_navigation;
  509. }
  510. /**
  511. * Return a navbar object
  512. * @return navbar
  513. */
  514. protected function magic_get_navbar() {
  515. if ($this->_navbar === null) {
  516. $this->_navbar = new navbar($this);
  517. }
  518. return $this->_navbar;
  519. }
  520. /**
  521. * Returns the settings navigation object
  522. * @return settings_navigation
  523. */
  524. protected function magic_get_settingsnav() {
  525. if ($this->_settingsnav === null) {
  526. $this->_settingsnav = new settings_navigation($this);
  527. $this->_settingsnav->initialise();
  528. }
  529. return $this->_settingsnav;
  530. }
  531. /**
  532. * PHP overloading magic to make the $PAGE->course syntax work by redirecting
  533. * it to the corresponding $PAGE->magic_get_course() method if there is one, and
  534. * throwing an exception if not.
  535. *
  536. * @param $name string property name
  537. * @return mixed
  538. */
  539. public function __get($name) {
  540. $getmethod = 'magic_get_' . $name;
  541. if (method_exists($this, $getmethod)) {
  542. return $this->$getmethod();
  543. } else {
  544. throw new coding_exception('Unknown property ' . $name . ' of $PAGE.');
  545. }
  546. }
  547. /**
  548. * PHP overloading magic which prevents the $PAGE->context = $context; syntax
  549. *
  550. * @param $name string property name
  551. * @param $name mixed value
  552. * @return void, throws exception if field not defined in page class
  553. */
  554. public function __set($name, $value) {
  555. if (method_exists($this, 'set_' . $name)) {
  556. throw new coding_exception('Invalid attempt to modify page object', "Use \$PAGE->set_$name() instead.");
  557. } else {
  558. throw new coding_exception('Invalid attempt to modify page object', "Unknown property $name");
  559. }
  560. }
  561. /// Other information getting methods ==========================================
  562. /**
  563. * Returns instance of page renderer
  564. * @param string $component name such as 'core', 'mod_forum' or 'qtype_multichoice'.
  565. * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
  566. * @param string $target one of rendering target constants
  567. * @return renderer_base
  568. */
  569. public function get_renderer($component, $subtype = null, $target = null) {
  570. return $this->magic_get_theme()->get_renderer($this, $component, $subtype, $target);
  571. }
  572. /**
  573. * Checks to see if there are any items on the navbar object
  574. * @return bool true if there are, false if not
  575. */
  576. public function has_navbar() {
  577. if ($this->_navbar === null) {
  578. $this->_navbar = new navbar($this);
  579. }
  580. return $this->_navbar->has_items();
  581. }
  582. /**
  583. * @return boolean should the current user see this page in editing mode.
  584. * That is, are they allowed to edit this page, and are they currently in
  585. * editing mode.
  586. */
  587. public function user_is_editing() {
  588. global $USER;
  589. return !empty($USER->editing) && $this->user_allowed_editing();
  590. }
  591. /**
  592. * @return boolean does the user have permission to edit blocks on this page.
  593. */
  594. public function user_can_edit_blocks() {
  595. return has_capability($this->_blockseditingcap, $this->_context);
  596. }
  597. /**
  598. * @return boolean does the user have permission to see this page in editing mode.
  599. */
  600. public function user_allowed_editing() {
  601. if ($this->_legacypageobject) {
  602. return $this->_legacypageobject->user_allowed_editing();
  603. }
  604. return has_any_capability($this->all_editing_caps(), $this->_context);
  605. }
  606. /**
  607. * @return string a description of this page. Normally displayed in the footer in
  608. * developer debug mode.
  609. */
  610. public function debug_summary() {
  611. $summary = '';
  612. $summary .= 'General type: ' . $this->pagelayout . '. ';
  613. if (!during_initial_install()) {
  614. $summary .= 'Context ' . print_context_name($this->_context) . ' (context id ' . $this->_context->id . '). ';
  615. }
  616. $summary .= 'Page type ' . $this->pagetype . '. ';
  617. if ($this->subpage) {
  618. 'Sub-page ' . $this->subpage . '. ';
  619. }
  620. return $summary;
  621. }
  622. /// Setter methods =============================================================
  623. /**
  624. * Set the state. The state must be one of that STATE_... constants, and
  625. * the state is only allowed to advance one step at a time.
  626. * @param integer $state the new state.
  627. */
  628. public function set_state($state) {
  629. if ($state != $this->_state + 1 || $state > self::STATE_DONE) {
  630. throw new coding_exception('Invalid state passed to moodle_page::set_state. We are in state ' .
  631. $this->_state . ' and state ' . $state . ' was requested.');
  632. }
  633. if ($state == self::STATE_PRINTING_HEADER) {
  634. $this->starting_output();
  635. }
  636. $this->_state = $state;
  637. }
  638. /**
  639. * Set the current course. This sets both $PAGE->course and $COURSE. It also
  640. * sets the right theme and locale.
  641. *
  642. * Normally you don't need to call this function yourself, require_login will
  643. * call it for you if you pass a $course to it. You can use this function
  644. * on pages that do need to call require_login().
  645. *
  646. * Sets $PAGE->context to the course context, if it is not already set.
  647. *
  648. * @param object the course to set as the global course.
  649. */
  650. public function set_course($course) {
  651. global $COURSE, $PAGE;
  652. if (empty($course->id)) {
  653. throw new coding_exception('$course passed to moodle_page::set_course does not look like a proper course object.');
  654. }
  655. $this->ensure_theme_not_set();
  656. if (!empty($this->_course->id) && $this->_course->id != $course->id) {
  657. $this->_categories = null;
  658. }
  659. $this->_course = clone($course);
  660. if ($this === $PAGE) {
  661. $COURSE = $this->_course;
  662. moodle_setlocale();
  663. }
  664. if (!$this->_context) {
  665. $this->set_context(get_context_instance(CONTEXT_COURSE, $this->_course->id));
  666. }
  667. }
  668. /**
  669. * Set the main context to which this page belongs.
  670. * @param object $context a context object, normally obtained with get_context_instance.
  671. */
  672. public function set_context($context) {
  673. if ($context === null) {
  674. // extremely ugly hack which sets context to some value in order to prevent warnings,
  675. // use only for core error handling!!!!
  676. if (!$this->_context) {
  677. $this->_context = get_context_instance(CONTEXT_SYSTEM);
  678. }
  679. return;
  680. }
  681. // ideally we should set context only once
  682. if (isset($this->_context)) {
  683. if ($context->id == $this->_context->id) {
  684. // fine - no change needed
  685. } else if ($this->_context->contextlevel == CONTEXT_SYSTEM or $this->_context->contextlevel == CONTEXT_COURSE) {
  686. // hmm - not ideal, but it might produce too many warnings due to the design of require_login
  687. } else if ($this->_context->contextlevel == CONTEXT_MODULE and $this->_context->id == get_parent_contextid($context)) {
  688. // hmm - most probably somebody did require_login() and after that set the block context
  689. } else {
  690. // we do not want devs to do weird switching of context levels on the fly,
  691. // because we might have used the context already such as in text filter in page title
  692. debugging('Coding problem: unsupported modification of PAGE->context from '.$this->_context->contextlevel.' to '.$context->contextlevel);
  693. }
  694. }
  695. $this->_context = $context;
  696. }
  697. /**
  698. * The course module that this page belongs to (if it does belong to one).
  699. *
  700. * @param stdClass|cm_info $cm a record from course_modules table or cm_info from get_fast_modinfo().
  701. * @param stdClass $course
  702. * @param stdClass $module
  703. * @return void
  704. */
  705. public function set_cm($cm, $course = null, $module = null) {
  706. global $DB;
  707. if (!isset($cm->id) || !isset($cm->course)) {
  708. 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.');
  709. }
  710. if (!$this->_course || $this->_course->id != $cm->course) {
  711. if (!$course) {
  712. $course = $DB->get_record('course', array('id' => $cm->course), '*', MUST_EXIST);
  713. }
  714. if ($course->id != $cm->course) {
  715. throw new coding_exception('The course you passed to $PAGE->set_cm does not correspond to the $cm.');
  716. }
  717. $this->set_course($course);
  718. }
  719. // make sure we have a $cm from get_fast_modinfo as this contains activity access details
  720. if (!($cm instanceof cm_info)) {
  721. $modinfo = get_fast_modinfo($this->_course);
  722. $cm = $modinfo->get_cm($cm->id);
  723. }
  724. $this->_cm = $cm;
  725. // unfortunately the context setting is a mess, let's try to work around some common block problems and show some debug messages
  726. if (empty($this->_context) or $this->_context->contextlevel != CONTEXT_BLOCK) {
  727. $context = get_context_instance(CONTEXT_MODULE, $cm->id);
  728. $this->set_context($context);
  729. }
  730. if ($module) {
  731. $this->set_activity_record($module);
  732. }
  733. }
  734. /**
  735. * @param $module a row from the main database table for the module that this
  736. * page belongs to. For example, if ->cm is a forum, then you can pass the
  737. * corresponding row from the forum table here if you have it (saves a database
  738. * query sometimes).
  739. */
  740. public function set_activity_record($module) {
  741. if (is_null($this->_cm)) {
  742. throw new coding_exception('You cannot call $PAGE->set_activity_record until after $PAGE->cm has been set.');
  743. }
  744. if ($module->id != $this->_cm->instance || $module->course != $this->_course->id) {
  745. throw new coding_exception('The activity record your are trying to set does not seem to correspond to the cm that has been set.');
  746. }
  747. $this->_module = $module;
  748. }
  749. /**
  750. * @param string $pagetype e.g. 'my-index' or 'mod-quiz-attempt'. Normally
  751. * you do not need to set this manually, it is automatically created from the
  752. * script name. However, on some pages this is overridden. For example, the
  753. * page type for course/view.php includes the course format, for example
  754. * 'course-view-weeks'. This gets used as the id attribute on <body> and
  755. * also for determining which blocks are displayed.
  756. */
  757. public function set_pagetype($pagetype) {
  758. $this->_pagetype = $pagetype;
  759. }
  760. /**
  761. * @param string $pagelayout the page layout this is. For example 'popup', 'home'.
  762. * This properly defaults to 'base', so you only need to call this function if
  763. * you want something different. The exact range of supported layouts is specified
  764. * in the standard theme.
  765. */
  766. public function set_pagelayout($pagelayout) {
  767. /**
  768. * Uncomment this to debug theme pagelayout issues like missing blocks.
  769. *
  770. * if (!empty($this->_wherethemewasinitialised) && $pagelayout != $this->_pagelayout) {
  771. * debugging('Page layout has already been set and cannot be changed.', DEBUG_DEVELOPER);
  772. * }
  773. */
  774. $this->_pagelayout = $pagelayout;
  775. }
  776. /**
  777. * If context->id and pagetype are not enough to uniquely identify this page,
  778. * then you can set a subpage id as well. For example, the tags page sets
  779. * @param string $subpage an arbitrary identifier that, along with context->id
  780. * and pagetype, uniquely identifies this page.
  781. */
  782. public function set_subpage($subpage) {
  783. if (empty($subpage)) {
  784. $this->_subpage = '';
  785. } else {
  786. $this->_subpage = $subpage;
  787. }
  788. }
  789. /**
  790. * @param string $class add this class name ot the class attribute on the body tag.
  791. */
  792. public function add_body_class($class) {
  793. if ($this->_state > self::STATE_BEFORE_HEADER) {
  794. throw new coding_exception('Cannot call moodle_page::add_body_class after output has been started.');
  795. }
  796. $this->_bodyclasses[$class] = 1;
  797. }
  798. /**
  799. * @param array $classes this utility method calls add_body_class for each array element.
  800. */
  801. public function add_body_classes($classes) {
  802. foreach ($classes as $class) {
  803. $this->add_body_class($class);
  804. }
  805. }
  806. /**
  807. * @param string $title the title that should go in the <head> section of the HTML of this page.
  808. */
  809. public function set_title($title) {
  810. $title = format_string($title);
  811. $title = str_replace('"', '&quot;', $title);
  812. $this->_title = $title;
  813. }
  814. /**
  815. * @param string $heading the main heading that should be displayed at the top of the <body>.
  816. */
  817. public function set_heading($heading) {
  818. $this->_heading = format_string($heading);
  819. }
  820. /**
  821. * @param string $menu The menu/content to show in the heading
  822. */
  823. public function set_headingmenu($menu) {
  824. $this->_headingmenu = $menu;
  825. }
  826. /**
  827. * Set the course category this page belongs to manually. This automatically
  828. * sets $PAGE->course to be the site course. You cannot use this method if
  829. * you have already set $PAGE->course - in that case, the category must be
  830. * the one that the course belongs to. This also automatically sets the
  831. * page context to the category context.
  832. * @param integer $categoryid The id of the category to set.
  833. */
  834. public function set_category_by_id($categoryid) {
  835. global $SITE, $DB;
  836. if (!is_null($this->_course)) {
  837. throw new coding_exception('Attempt to manually set the course category when the course has been set. This is not allowed.');
  838. }
  839. if (is_array($this->_categories)) {
  840. throw new coding_exception('Course category has already been set. You are not allowed to change it.');
  841. }
  842. $this->ensure_theme_not_set();
  843. $this->set_course($SITE);
  844. $this->load_category($categoryid);
  845. $this->set_context(get_context_instance(CONTEXT_COURSECAT, $categoryid));
  846. }
  847. /**
  848. * Set a different path to use for the 'Moodle docs for this page' link.
  849. * By default, it uses the pagetype, which is normally the same as the
  850. * script name. So, for example, for mod/quiz/attempt.php, pagetype is
  851. * mod-quiz-attempt, and so docspath is mod/quiz/attempt.
  852. * @param string $path the path to use at the end of the moodle docs URL.
  853. */
  854. public function set_docs_path($path) {
  855. $this->_docspath = $path;
  856. }
  857. /**
  858. * You should call this method from every page to set the cleaned-up URL
  859. * that should be used to return to this page. Used, for example, by the
  860. * blocks editing UI to know where to return the user after an action.
  861. * For example, course/view.php does:
  862. * $id = optional_param('id', 0, PARAM_INT);
  863. * $PAGE->set_url('/course/view.php', array('id' => $id));
  864. * @param moodle_url|string $url URL relative to $CFG->wwwroot or {@link moodle_url} instance
  865. * @param array $params parameters to add to the URL
  866. */
  867. public function set_url($url, array $params = null) {
  868. global $CFG;
  869. if (is_string($url)) {
  870. if (strpos($url, 'http') === 0) {
  871. // ok
  872. } else if (strpos($url, '/') === 0) {
  873. // we have to use httpswwwroot here, because of loginhttps pages
  874. $url = $CFG->httpswwwroot . $url;
  875. } else {
  876. throw new coding_exception('Invalid parameter $url, has to be full url or in shortened form starting with /.');
  877. }
  878. }
  879. $this->_url = new moodle_url($url, $params);
  880. $fullurl = $this->_url->out_omit_querystring();
  881. if (strpos($fullurl, "$CFG->httpswwwroot/") !== 0) {
  882. debugging('Most probably incorrect set_page() url argument, it does not match the httpswwwroot!');
  883. }
  884. $shorturl = str_replace("$CFG->httpswwwroot/", '', $fullurl);
  885. if (is_null($this->_pagetype)) {
  886. $this->initialise_default_pagetype($shorturl);
  887. }
  888. if (!is_null($this->_legacypageobject)) {
  889. $this->_legacypageobject->set_url($url, $params);
  890. }
  891. }
  892. /**
  893. * Make sure page URL does not contain the given URL parameter.
  894. *
  895. * This should not be necessary if the script has called set_url properly.
  896. * However, in some situations like the block editing actions; when the URL
  897. * has been guessed, it will contain dangerous block-related actions.
  898. * Therefore, the blocks code calls this function to clean up such parameters
  899. * before doing any redirect.
  900. *
  901. * @param string $param the name of the parameter to make sure is not in the
  902. * page URL.
  903. */
  904. public function ensure_param_not_in_url($param) {
  905. $discard = $this->url; // Make sure $this->url is lazy-loaded;
  906. $this->_url->remove_params($param);
  907. }
  908. /**
  909. * There can be alternate versions of some pages (for example an RSS feed version).
  910. * If such other version exist, call this method, and a link to the alternate
  911. * version will be included in the <head> of the page.
  912. *
  913. * @param $title The title to give the alternate version.
  914. * @param $url The URL of the alternate version.
  915. * @param $mimetype The mime-type of the alternate version.
  916. */
  917. public function add_alternate_version($title, $url, $mimetype) {
  918. if ($this->_state > self::STATE_BEFORE_HEADER) {
  919. throw new coding_exception('Cannot call moodle_page::add_alternate_version after output has been started.');
  920. }
  921. $alt = new stdClass;
  922. $alt->title = $title;
  923. $alt->url = $url;
  924. $this->_alternateversions[$mimetype] = $alt;
  925. }
  926. /**
  927. * Specify a form control should be focused when the page has loaded.
  928. *
  929. * @param string $controlid the id of the HTML element to be focused.
  930. */
  931. public function set_focuscontrol($controlid) {
  932. $this->_focuscontrol = $controlid;
  933. }
  934. /**
  935. * Specify a fragment of HTML that goes where the 'Turn editing on' button normally goes.
  936. *
  937. * @param string $html the HTML to display there.
  938. */
  939. public function set_button($html) {
  940. $this->_button = $html;
  941. }
  942. /**
  943. * Set the capability that allows users to edit blocks on this page. Normally
  944. * the default of 'moodle/site:manageblocks' is used, but a few pages like
  945. * the My Moodle page need to use a different capability like 'moodle/my:manageblocks'.
  946. * @param string $capability a capability.
  947. */
  948. public function set_blocks_editing_capability($capability) {
  949. $this->_blockseditingcap = $capability;
  950. }
  951. /**
  952. * Some pages let you turn editing on for reasons other than editing blocks.
  953. * If that is the case, you can pass other capabilities that let the user
  954. * edit this page here.
  955. * @param string|array $capability either a capability, or an array of capabilities.
  956. */
  957. public function set_other_editing_capability($capability) {
  958. if (is_array($capability)) {
  959. $this->_othereditingcaps = array_unique($this->_othereditingcaps + $capability);
  960. } else {
  961. $this->_othereditingcaps[] = $capability;
  962. }
  963. }
  964. /**
  965. * @return boolean $cacheable can this page be cached by the user's browser.
  966. */
  967. public function set_cacheable($cacheable) {
  968. $this->_cacheable = $cacheable;
  969. }
  970. /**
  971. * Sets the page to periodically refresh
  972. *
  973. * This function must be called before $OUTPUT->header has been called or
  974. * a coding exception will be thrown.
  975. *
  976. * @param int $delay Sets the delay before refreshing the page, if set to null
  977. * refresh is cancelled
  978. */
  979. public function set_periodic_refresh_delay($delay=null) {
  980. if ($this->_state > self::STATE_BEFORE_HEADER) {
  981. throw new coding_exception('You cannot set a periodic refresh delay after the header has been printed');
  982. }
  983. if ($delay===null) {
  984. $this->_periodicrefreshdelay = null;
  985. } else if (is_int($delay)) {
  986. $this->_periodicrefreshdelay = $delay;
  987. }
  988. }
  989. /**
  990. * Force this page to use a particular theme.
  991. *
  992. * Please use this cautiously. It is only intended to be used by the themes selector admin page.
  993. *
  994. * @param $themename the name of the theme to use.
  995. */
  996. public function force_theme($themename) {
  997. $this->ensure_theme_not_set();
  998. $this->_theme = theme_config::load($themename);
  999. }
  1000. /**
  1001. * This function indicates that current page requires the https
  1002. * when $CFG->loginhttps enabled.
  1003. *
  1004. * By using this function properly, we can ensure 100% https-ized pages
  1005. * at our entire discretion (login, forgot_password, change_password)
  1006. * @return void
  1007. */
  1008. public function https_required() {
  1009. global $CFG;
  1010. if (!is_null($this->_url)) {
  1011. throw new coding_exception('https_required() must be used before setting page url!');
  1012. }
  1013. $this->ensure_theme_not_set();
  1014. $this->_https_login_required = true;
  1015. if (!empty($CFG->loginhttps)) {
  1016. $CFG->httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
  1017. } else {
  1018. $CFG->httpswwwroot = $CFG->wwwroot;
  1019. }
  1020. }
  1021. /**
  1022. * Makes sure that page previously marked with https_required()
  1023. * is really using https://, if not it redirects to https://
  1024. *
  1025. * @return void (may redirect to https://self)
  1026. */
  1027. public function verify_https_required() {
  1028. global $CFG, $FULLME;
  1029. if (is_null($this->_url)) {
  1030. throw new coding_exception('verify_https_required() must be called after setting page url!');
  1031. }
  1032. if (!$this->_https_login_required) {
  1033. throw new coding_exception('verify_https_required() must be called only after https_required()!');
  1034. }
  1035. if (empty($CFG->loginhttps)) {
  1036. // https not required, so stop checking
  1037. return;
  1038. }
  1039. if (strpos($this->_url, 'https://')) {
  1040. // detect if incorrect PAGE->set_url() used, it is recommended to use root-relative paths there
  1041. throw new coding_exception('Invalid page url specified, it must start with https:// for pages that set https_required()!');
  1042. }
  1043. if (!empty($CFG->sslproxy)) {
  1044. // it does not make much sense to use sslproxy and loginhttps at the same time
  1045. return;
  1046. }
  1047. // now the real test and redirect!
  1048. // NOTE: do NOT use this test for detection of https on current page because this code is not compatible with SSL proxies,
  1049. // instead use strpos($CFG->httpswwwroot, 'https:') === 0
  1050. if (strpos($FULLME, 'https:') !== 0) {
  1051. // this may lead to infinite redirect on misconfigured sites, in that case use $CFG->loginhttps=0; in /config.php
  1052. redirect($this->_url);
  1053. }
  1054. }
  1055. /// Initialisation methods =====================================================
  1056. /// These set various things up in a default way.
  1057. /**
  1058. * This method is called when the page first moves out of the STATE_BEFORE_HEADER
  1059. * state. This is our last change to initialise things.
  1060. */
  1061. protected function starting_output() {
  1062. global $CFG;
  1063. if (!during_initial_install()) {
  1064. $this->blocks->load_blocks();
  1065. if (empty($this->_block_actions_done)) {
  1066. $this->_block_actions_done = true;
  1067. if ($this->blocks->process_url_actions($this)) {
  1068. redirect($this->url->out(false));
  1069. }
  1070. }
  1071. $this->blocks->create_all_block_instances();
  1072. }
  1073. // If maintenance mode is on, change the page header.
  1074. if (!empty($CFG->maintenance_enabled)) {
  1075. $this->set_button('<a href="' . $CFG->wwwroot . '/' . $CFG->admin .
  1076. '/settings.php?section=maintenancemode">' . get_string('maintenancemode', 'admin') .
  1077. '</a> ' . $this->button);
  1078. $title = $this->title;
  1079. if ($title) {
  1080. $title .= ' - ';
  1081. }
  1082. $this->set_title($title . get_string('maintenancemode', 'admin'));
  1083. } else {
  1084. // Show the messaging popup if there are messages
  1085. message_popup_window();
  1086. }
  1087. $this->initialise_standard_body_classes();
  1088. }
  1089. /**
  1090. * Method for use by Moodle core to set up the theme. Do not
  1091. * use this in your own code.
  1092. *
  1093. * Make sure the right theme for this page is loaded. Tell our
  1094. * blocks_manager about the theme block regions, and then, if
  1095. * we are $PAGE, set up the global $OUTPUT.
  1096. */
  1097. public function initialise_theme_and_output() {
  1098. global $OUTPUT, $PAGE, $SITE;
  1099. if (!empty($this->_wherethemewasinitialised)) {
  1100. return;
  1101. }
  1102. if (!during_initial_install()) {
  1103. // detect PAGE->context mess
  1104. $this->magic_get_context();
  1105. }
  1106. if (!$this->_course && !during_initial_install()) {
  1107. $this->set_course($SITE);
  1108. }
  1109. if (is_null($this->_theme)) {
  1110. $themename = $this->resolve_theme();
  1111. $this->_theme = theme_config::load($themename);
  1112. $this->_layout_options = $this->_theme->pagelayout_options($this->pagelayout);
  1113. }
  1114. $this->_theme->setup_blocks($this->pagelayout, $this->blocks);
  1115. if ($this === $PAGE) {
  1116. $OUTPUT = $this->get_renderer('core');
  1117. }
  1118. $this->_wherethemewasinitialised = debug_backtrace();
  1119. }
  1120. /**
  1121. * Work out the theme this page should use.
  1122. *
  1123. * This depends on numerous $CFG settings, and the properties of this page.
  1124. *
  1125. * @return string the name of the theme that should be used on this page.
  1126. */
  1127. protected function resolve_theme() {
  1128. global $CFG, $USER, $SESSION;
  1129. if (empty($CFG->themeorder)) {
  1130. $themeorder = array('course', 'category', 'session', 'user', 'site');
  1131. } else {
  1132. $themeorder = $CFG->themeorder;
  1133. // Just in case, make sure we always use the site theme if nothing else matched.
  1134. $themeorder[] = 'site';
  1135. }
  1136. $mnetpeertheme = '';
  1137. if (isloggedin() and isset($CFG->mnet_localhost_id) and $USER->mnethostid != $CFG->mnet_localhost_id) {
  1138. require_once($CFG->dirroot.'/mnet/peer.php');
  1139. $mnetpeer = new mnet_peer();
  1140. $mnetpeer->set_id($USER->mnethostid);
  1141. if ($mnetpeer->force_theme == 1 && $mnetpeer->theme != '') {
  1142. $mnetpeertheme = $mnetpeer->theme;
  1143. }
  1144. }
  1145. foreach ($themeorder as $themetype) {
  1146. switch ($themetype) {
  1147. case 'course':
  1148. if (!empty($CFG->allowcoursethemes) && !empty($this->_course->theme) && $this->devicetypeinuse == 'default') {
  1149. return $this->_course->theme;
  1150. }
  1151. break;
  1152. case 'category':
  1153. if (!empty($CFG->allowcategorythemes) && $this->devicetypeinuse == 'default') {
  1154. $categories = $this->categories;
  1155. foreach ($categories as $category) {
  1156. if (!empty($category->theme)) {
  1157. return $category->theme;
  1158. }
  1159. }
  1160. }
  1161. break;
  1162. case 'session':
  1163. if (!empty($SESSION->theme)) {
  1164. return $SESSION->theme;
  1165. }
  1166. break;
  1167. case 'user':
  1168. if (!empty($CFG->allowuserthemes) && !empty($USER->theme) && $this->devicetypeinuse == 'default') {
  1169. if ($mnetpeertheme) {
  1170. return $mnetpeertheme;
  1171. } else {
  1172. return $USER->theme;
  1173. }
  1174. }
  1175. break;
  1176. case 'site':
  1177. if ($mnetpeertheme) {
  1178. return $mnetpeertheme;
  1179. }
  1180. // First try for the device the user is using.
  1181. $devicetheme = get_selected_theme_for_device_type($this->devicetypeinuse);
  1182. if (!empty($devicetheme)) {
  1183. return $devicetheme;
  1184. }
  1185. // Next try for the default device (as a fallback)
  1186. $devicetheme = get_selected_theme_for_device_type('default');
  1187. if (!empty($devicetheme)) {
  1188. return $devicetheme;
  1189. }
  1190. // The default device theme isn't set up - use the overall default theme.
  1191. return theme_config::DEFAULT_THEME;
  1192. }
  1193. }
  1194. }
  1195. /**
  1196. * Sets ->pagetype from the script name. For example, if the script that was
  1197. * run is mod/quiz/view.php, ->pagetype will be set to 'mod-quiz-view'.
  1198. * @param string $script the path to the script that should be used to
  1199. * initialise ->pagetype. If not passed the $SCRIPT global will be used.
  1200. * If legacy code has set $CFG->pagepath that will be used instead, and a
  1201. * developer warning issued.
  1202. */
  1203. protected function initialise_default_pagetype($script = null) {
  1204. global $CFG, $SCRIPT;
  1205. if (isset($CFG->pagepath)) {
  1206. debugging('Some code appears to have set $CFG->pagepath. That was a horrible deprecated thing. ' .
  1207. 'Don\'t do it! Try calling $PAGE->set_pagetype() instead.');
  1208. $script = $CFG->pagepath;
  1209. unset($CFG->pagepath);
  1210. }
  1211. if (is_null($script)) {
  1212. $script = ltrim($SCRIPT, '/');
  1213. $len = strlen($CFG->admin);
  1214. if (substr($script, 0, $len) == $CFG->admin) {
  1215. $script = 'admin' . substr($script, $len);
  1216. }
  1217. }
  1218. $path = str_replace('.php', '', $script);
  1219. if (substr($path, -1) == '/') {
  1220. $path .= 'index';
  1221. }
  1222. if (empty($path) || $path == 'index') {
  1223. $this->_pagetype = 'site-index';
  1224. } else {
  1225. $this->_pagetype = str_replace('/', '-', $path);
  1226. }
  1227. }
  1228. protected function initialise_standard_body_classes() {
  1229. global $CFG, $USER;
  1230. $pagetype = $this->pagetype;
  1231. if ($pagetype == 'site-index') {
  1232. $this->_legacyclass = 'course';
  1233. } else if (substr($pagetype, 0, 6) == 'admin-') {
  1234. $this->_legacyclass = 'admin';
  1235. }
  1236. $this->add_body_class($this->_legacyclass);
  1237. $pathbits = explode('-', trim($pagetype));
  1238. for ($i=1;$i<count($pathbits);$i++) {
  1239. $this->add_body_class('path-'.join('-',array_slice($pathbits, 0, $i)));
  1240. }
  1241. $this->add_body_classes(get_browser_version_classes());
  1242. $this->add_body_class('dir-' . get_string('thisdirection', 'langconfig'));
  1243. $this->add_body_class('lang-' . current_language());
  1244. $this->add_body_class('yui-skin-sam'); // Make YUI happy, if it is used.
  1245. $this->add_body_class('yui3-skin-sam'); // Make YUI3 happy, if it is used.
  1246. $this->add_body_class($this->url_to_class_name($CFG->wwwroot));
  1247. $this->add_body_class('pagelayout-' . $this->_pagelayout); // extra class describing current page layout
  1248. if (!during_initial_install()) {
  1249. $this->add_body_class('course-' . $this->_course->id);
  1250. $this->add_body_class('context-' . $this->_context->id);
  1251. }
  1252. if (!empty($this->_cm)) {
  1253. $this->add_body_class('cmid-' . $this->_cm->id);
  1254. }
  1255. if (!empty($CFG->allowcategorythemes)) {
  1256. $this->ensure_category_loaded();
  1257. foreach ($this->_categories as $catid => $notused) {
  1258. $this->add_body_class('category-' . $catid);
  1259. }
  1260. } else {
  1261. $catid = 0;
  1262. if (is_array($this->_categories)) {
  1263. $catids = array_keys($this->_categories);
  1264. $catid = reset($catids);
  1265. } else if (!empty($this->_course->category)) {
  1266. $catid = $this->_course->category;
  1267. }
  1268. if ($catid) {
  1269. $this->add_body_class('category-' . $catid);
  1270. }
  1271. }
  1272. if (!isloggedin()) {
  1273. $this->add_body_class('notloggedin');
  1274. }
  1275. if (!empty($USER->editing)) {
  1276. $this->add_body_class('editing');
  1277. if (optional_param('bui_moveid', false, PARAM_INT)) {
  1278. $this->add_body_class('blocks-moving');
  1279. }
  1280. }
  1281. if (!empty($CFG->blocksdrag)) {
  1282. $this->add_body_class('drag');
  1283. }
  1284. if ($this->_devicetypeinuse != 'default') {
  1285. $this->add_body_class($this->_devicetypeinuse . 'theme');
  1286. }
  1287. }
  1288. protected function load_activity_record() {
  1289. global $DB;
  1290. if (is_null($this->_cm)) {
  1291. return;
  1292. }
  1293. $this->_module = $DB->get_record($this->_cm->modname, array('id' => $this->_cm->instance));
  1294. }
  1295. protected function ensure_category_loaded() {
  1296. if (is_array($this->_categories)) {
  1297. return; // Already done.
  1298. }
  1299. if (is_null($this->_course)) {
  1300. throw new coding_exception('Attempt to get the course category for this page before the course was set.');
  1301. }
  1302. if ($this->_course->category == 0) {
  1303. $this->_categories = array();
  1304. } else {
  1305. $this->load_category($this->_course->category);
  1306. }
  1307. }
  1308. protected function load_category($categoryid) {
  1309. global $DB;
  1310. $category = $DB->get_record('course_categories', array('id' => $categoryid));
  1311. if (!$category) {
  1312. throw new moodle_exception('unknowncategory');
  1313. }
  1314. $this->_categories[$category->id] = $category;
  1315. $parentcategoryids = explode('/', trim($category->path, '/'));
  1316. array_pop($parentcategoryids);
  1317. foreach (array_reverse($parentcategoryids) as $catid) {
  1318. $this->_categories[$catid] = null;
  1319. }
  1320. }
  1321. protected function ensure_categories_loaded() {
  1322. global $DB;
  1323. $this->ensure_category_loaded();
  1324. if (!is_null(end($this->_categories))) {
  1325. return; // Already done.
  1326. }
  1327. $idstoload = array_keys($this->_categories);
  1328. array_shift($idstoload);
  1329. $categories = $DB->get_records_list('course_categories', 'id', $idstoload);
  1330. foreach ($idstoload as $catid) {
  1331. $this->_categories[$catid] = $categories[$catid];
  1332. }
  1333. }
  1334. protected function ensure_theme_not_set() {
  1335. if (!is_null($this->_theme)) {
  1336. throw new coding_exception('The theme has already been set up for this page ready for output. ' .
  1337. 'Therefore, you can no longer change the theme, or anything that might affect what ' .
  1338. 'the current theme is, for example, the course.',
  1339. 'Stack trace when the theme was set up: ' . format_backtrace($this->_wherethemewasinitialised));
  1340. }
  1341. }
  1342. protected function url_to_class_name($url) {
  1343. $bits = parse_url($url);
  1344. $class = str_replace('.', '-', $bits['host']);
  1345. if (!empty($bits['port'])) {
  1346. $class .= '--' . $bits['port'];
  1347. }
  1348. if (!empty($bits['path'])) {
  1349. $path = trim($bits['path'], '/');
  1350. if ($path) {
  1351. $class .= '--' . str_replace('/', '-', $path);
  1352. }
  1353. }
  1354. return $class;
  1355. }
  1356. protected function all_editing_caps() {
  1357. $caps = $this->_othereditingcaps;
  1358. $caps[] = $this->_blockseditingcap;
  1359. return $caps;
  1360. }
  1361. /// Deprecated fields and methods for backwards compatibility ==================
  1362. /**
  1363. * @deprecated since Moodle 2.0 - use $PAGE->pagetype instead.
  1364. * @return string page type.
  1365. */
  1366. public function get_type() {
  1367. debugging('Call to deprecated method moodle_page::get_type. Please use $PAGE->pagetype instead.');
  1368. return $this->get_pagetype();
  1369. }
  1370. /**
  1371. * @deprecated since Moodle 2.0 - use $PAGE->pagetype instead.
  1372. * @return string this is what page_id_and_class used to return via the $getclass parameter.
  1373. */
  1374. function get_format_name() {
  1375. return $this->get_pagetype();
  1376. }
  1377. /**
  1378. * @deprecated since Moodle 2.0 - use $PAGE->course instead.
  1379. * @return object course.
  1380. */
  1381. public function get_courserecord() {
  1382. debugging('Call to deprecated method moodle_page::get_courserecord. Please use $PAGE->course instead.');
  1383. return $this->get_course();
  1384. }
  1385. /**
  1386. * @deprecated since Moodle 2.0
  1387. * @return string this is what page_id_and_class used to return via the $getclass parameter.
  1388. */
  1389. public function get_legacyclass() {
  1390. if (is_null($this->_legacyclass)) {
  1391. $this->initialise_standard_body_classes();
  1392. }
  1393. debugging('Call to deprecated method moodle_page::get_legacyclass.');
  1394. return $this->_legacyclass;
  1395. }
  1396. /**
  1397. * @deprecated since Moodle 2.0 - use $PAGE->blocks->get_regions() instead
  1398. * @return string the places on this page where blocks can go.
  1399. */
  1400. function blocks_get_positions() {
  1401. debugging('Call to deprecated method moodle_page::blocks_get_positions. Use $PAGE->blocks->get_regions() instead.');
  1402. return $this->blocks->get_regions();
  1403. }
  1404. /**
  1405. * @deprecated since Moodle 2.0 - use $PAGE->blocks->get_default_region() instead
  1406. * @return string the default place for blocks on this page.
  1407. */
  1408. function blocks_default_position() {
  1409. debugging('Call to deprecated method moodle_page::blocks_default_position. Use $PAGE->blocks->get_default_region() instead.');
  1410. return $this->blocks->get_default_region();
  1411. }
  1412. /**
  1413. * @deprecated since Moodle 2.0 - no longer used.
  1414. */
  1415. function blocks_get_default() {
  1416. debugging('Call to deprecated method moodle_page::blocks_get_default. This method has no function any more.');
  1417. }
  1418. /**
  1419. * @deprecated since Moodle 2.0 - no longer used.
  1420. */
  1421. function blocks_move_position(&$instance, $move) {
  1422. debugging('Call to deprecated method moodle_page::blocks_move_position. This method has no function any more.');
  1423. }
  1424. /**
  1425. * @deprecated since Moodle 2.0 - use $this->url->params() instead.
  1426. * @return array URL parameters for this page.
  1427. */
  1428. function url_get_parameters() {
  1429. debugging('Call to deprecated method moodle_page::url_get_parameters. Use $this->url->params() instead.');
  1430. return $this->url->params();
  1431. }
  1432. /**
  1433. * @deprecated since Moodle 2.0 - use $this->url->params() instead.
  1434. * @return string URL for this page without parameters.
  1435. */
  1436. function url_get_path() {
  1437. debugging('Call to deprecated method moodle_page::url_get_path. Use $this->url->out() instead.');
  1438. return $this->url->out();
  1439. }
  1440. /**
  1441. * @deprecated since Moodle 2.0 - use $this->url->out() instead.
  1442. * @return string full URL for this page.
  1443. */
  1444. function url_get_full($extraparams = array()) {
  1445. debugging('Call to deprecated method moodle_page::url_get_full. Use $this->url->out() instead.');
  1446. return $this->url->out(true, $extraparams);
  1447. }
  1448. /**
  1449. * @deprecated since Moodle 2.0 - just a backwards compatibility hook.
  1450. */
  1451. function set_legacy_page_object($pageobject) {
  1452. return $this->_legacypageobject = $pageobject;
  1453. }
  1454. /**
  1455. * @deprecated since Moodle 2.0 - page objects should no longer be doing print_header.
  1456. * @param $_,...
  1457. */
  1458. function print_header($_) {
  1459. if (is_null($this->_legacypageobject)) {
  1460. throw new coding_exception('You have called print_header on $PAGE when there is not a legacy page class present.');
  1461. }
  1462. debugging('You should not longer be doing print_header via a page class.', DEBUG_DEVELOPER);
  1463. $args = func_get_args();
  1464. call_user_func_array(array($this->_legacypageobject, 'print_header'), $args);
  1465. }
  1466. /**
  1467. * @deprecated since Moodle 2.0
  1468. * @return the 'page id'. This concept no longer exists.
  1469. */
  1470. function get_id() {
  1471. debugging('Call to deprecated method moodle_page::get_id(). It should not be necessary any more.', DEBUG_DEVELOPER);
  1472. if (!is_null($this->_legacypageobject)) {
  1473. return $this->_legacypageobject->get_id();
  1474. }
  1475. return 0;
  1476. }
  1477. /**
  1478. * @deprecated since Moodle 2.0
  1479. * @return the 'page id'. This concept no longer exists.
  1480. */
  1481. function get_pageid() {
  1482. debugging('Call to deprecated method moodle_page::get_pageid(). It should not be necessary any more.', DEBUG_DEVELOPER);
  1483. if (!is_null($this->_legacypageobject)) {
  1484. return $this->_legacypageobject->get_id();
  1485. }
  1486. return 0;
  1487. }
  1488. /**
  1489. * @deprecated since Moodle 2.0 - user $PAGE->cm instead.
  1490. * @return $this->cm;
  1491. */
  1492. function get_modulerecord() {
  1493. return $this->cm;
  1494. }
  1495. public function has_set_url() {
  1496. return ($this->_url!==null);
  1497. }
  1498. public function set_block_actions_done($setting = true) {
  1499. $this->_block_actions_done = $setting;
  1500. }
  1501. /**
  1502. * Are popup notifications allowed on this page?
  1503. * Popup notifications may be disallowed in situations such as while upgrading or completing a quiz
  1504. * @return boolean true if popup notifications may be displayed
  1505. */
  1506. public function get_popup_notification_allowed() {
  1507. return $this->_popup_notification_allowed;
  1508. }
  1509. /**
  1510. * Allow or disallow popup notifications on this page. Popups are allowed by default.
  1511. * @param boolean true if notifications are allowed. False if not allowed. They are allowed by default.
  1512. * @return null
  1513. */
  1514. public function set_popup_notification_allowed($allowed) {
  1515. $this->_popup_notification_allowed = $allowed;
  1516. }
  1517. }
  1518. /**
  1519. * @deprecated since Moodle 2.0
  1520. * Not needed any more.
  1521. * @param $path the folder path
  1522. * @return array an array of page types.
  1523. */
  1524. function page_import_types($path) {
  1525. global $CFG;
  1526. debugging('Call to deprecated function page_import_types.', DEBUG_DEVELOPER);
  1527. }
  1528. /**
  1529. * @deprecated since Moodle 2.0
  1530. * Do not use this any more. The global $PAGE is automatically created for you.
  1531. * If you need custom behaviour, you should just set properties of that object.
  1532. * @param integer $instance legacy page instance id.
  1533. * @return the global $PAGE object.
  1534. */
  1535. function page_create_instance($instance) {
  1536. global $PAGE;
  1537. return page_create_object($PAGE->pagetype, $instance);
  1538. }
  1539. /**
  1540. * @deprecated since Moodle 2.0
  1541. * Do not use this any more. The global $PAGE is automatically created for you.
  1542. * If you need custom behaviour, you should just set properties of that object.
  1543. */
  1544. function page_create_object($type, $id = NULL) {
  1545. global $CFG, $PAGE, $SITE, $ME;
  1546. debugging('Call to deprecated function page_create_object.', DEBUG_DEVELOPER);
  1547. $data = new stdClass;
  1548. $data->pagetype = $type;
  1549. $data->pageid = $id;
  1550. $classname = page_map_class($type);
  1551. if (!$classname) {
  1552. return $PAGE;
  1553. }
  1554. $legacypage = new $classname;
  1555. $legacypage->init_quick($data);
  1556. $course = $PAGE->course;
  1557. if ($course->id != $SITE->id) {
  1558. $legacypage->set_course($course);
  1559. } else {
  1560. try {
  1561. $category = $PAGE->category;
  1562. } catch (coding_exception $e) {
  1563. // Was not set before, so no need to try to set it again.
  1564. $category = false;
  1565. }
  1566. if ($category) {
  1567. $legacypage->set_category_by_id($category->id);
  1568. } else {
  1569. $legacypage->set_course($SITE);
  1570. }
  1571. }
  1572. $legacypage->set_pagetype($type);
  1573. $legacypage->set_url($ME);
  1574. $PAGE->set_url(str_replace($CFG->wwwroot . '/', '', $legacypage->url_get_full()));
  1575. $PAGE->set_pagetype($type);
  1576. $PAGE->set_legacy_page_object($legacypage);
  1577. return $PAGE;
  1578. }
  1579. /**
  1580. * @deprecated since Moodle 2.0
  1581. * You should not be writing page subclasses any more. Just set properties on the
  1582. * global $PAGE object to control its behaviour.
  1583. */
  1584. function page_map_class($type, $classname = NULL) {
  1585. global $CFG;
  1586. static $mappings = array(
  1587. PAGE_COURSE_VIEW => 'page_course',
  1588. );
  1589. if (!empty($type) && !empty($classname)) {
  1590. $mappings[$type] = $classname;
  1591. }
  1592. if (!isset($mappings[$type])) {
  1593. debugging('Page class mapping requested for unknown type: '.$type);
  1594. return null;
  1595. } else if (empty($classname) && !class_exists($mappings[$type])) {
  1596. debugging('Page class mapping for id "'.$type.'" exists but class "'.$mappings[$type].'" is not defined');
  1597. return null;
  1598. }
  1599. return $mappings[$type];
  1600. }
  1601. /**
  1602. * @deprecated since Moodle 2.0
  1603. * Parent class from which all Moodle page classes derive
  1604. *
  1605. * @package core
  1606. * @subpackage lib
  1607. * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
  1608. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1609. */
  1610. class page_base extends moodle_page {
  1611. /**
  1612. * The numeric identifier of the page being described.
  1613. * @var int $id
  1614. */
  1615. var $id = NULL;
  1616. /// Class Functions
  1617. // HTML OUTPUT SECTION
  1618. // SELF-REPORTING SECTION
  1619. // Simple stuff, do not override this.
  1620. function get_id() {
  1621. return $this->id;
  1622. }
  1623. // Initialize the data members of the parent class
  1624. function init_quick($data) {
  1625. $this->id = $data->pageid;
  1626. }
  1627. function init_full() {
  1628. }
  1629. }
  1630. /**
  1631. * @deprecated since Moodle 2.0
  1632. * Class that models the behavior of a moodle course.
  1633. * Although this does nothing, this class declaration should be left for now
  1634. * since there may be legacy class doing class page_... extends page_course
  1635. *
  1636. * @package core
  1637. * @subpackage lib
  1638. * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
  1639. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1640. */
  1641. class page_course extends page_base {
  1642. }
  1643. /**
  1644. * @deprecated since Moodle 2.0
  1645. * Class that models the common parts of all activity modules
  1646. *
  1647. * @package core
  1648. * @subpackage lib
  1649. * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
  1650. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1651. */
  1652. class page_generic_activity extends page_base {
  1653. // Although this function is deprecated, it should be left here because
  1654. // people upgrading legacy code need to copy it. See
  1655. // http://docs.moodle.org/dev/Migrating_your_code_to_the_2.0_rendering_API
  1656. function print_header($title, $morenavlinks = NULL, $bodytags = '', $meta = '') {
  1657. global $USER, $CFG, $PAGE, $OUTPUT;
  1658. $this->init_full();
  1659. $replacements = array(
  1660. '%fullname%' => format_string($this->activityrecord->name)
  1661. );
  1662. foreach ($replacements as $search => $replace) {
  1663. $title = str_replace($search, $replace, $title);
  1664. }
  1665. $buttons = '<table><tr><td>'.$OUTPUT->update_module_button($this->modulerecord->id, $this->activityname).'</td>';
  1666. if ($this->user_allowed_editing()) {
  1667. $buttons .= '<td><form method="get" action="view.php"><div>'.
  1668. '<input type="hidden" name="id" value="'.$this->modulerecord->id.'" />'.
  1669. '<input type="hidden" name="edit" value="'.($this->user_is_editing()?'off':'on').'" />'.
  1670. '<input type="submit" value="'.get_string($this->user_is_editing()?'blockseditoff':'blocksediton').'" /></div></form></td>';
  1671. }
  1672. $buttons .= '</tr></table>';
  1673. if (!empty($morenavlinks) && is_array($morenavlinks)) {
  1674. foreach ($morenavlinks as $navitem) {
  1675. if (is_array($navitem) && array_key_exists('name', $navitem)) {
  1676. $link = null;
  1677. if (array_key_exists('link', $navitem)) {
  1678. $link = $navitem['link'];
  1679. }
  1680. $PAGE->navbar->add($navitem['name'], $link);
  1681. }
  1682. }
  1683. }
  1684. $PAGE->set_title($title);
  1685. $PAGE->set_heading($this->course->fullname);
  1686. $PAGE->set_button($buttons);
  1687. echo $OUTPUT->header();
  1688. }
  1689. }