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

/lib/outputlib.php

https://github.com/nfreear/moodle
PHP | 1307 lines | 658 code | 139 blank | 510 comment | 135 complexity | 6e641212528f546d871bc734ec10a33b MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause
  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. * Functions for generating the HTML that Moodle should output.
  18. *
  19. * Please see http://docs.moodle.org/en/Developement:How_Moodle_outputs_HTML
  20. * for an overview.
  21. *
  22. * @package core
  23. * @subpackage lib
  24. * @copyright 2009 Tim Hunt
  25. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  26. */
  27. defined('MOODLE_INTERNAL') || die();
  28. require_once($CFG->libdir.'/outputcomponents.php');
  29. require_once($CFG->libdir.'/outputactions.php');
  30. require_once($CFG->libdir.'/outputfactories.php');
  31. require_once($CFG->libdir.'/outputrenderers.php');
  32. require_once($CFG->libdir.'/outputrequirementslib.php');
  33. /**
  34. * Invalidate all server and client side caches.
  35. * @return void
  36. */
  37. function theme_reset_all_caches() {
  38. global $CFG;
  39. require_once("$CFG->libdir/filelib.php");
  40. set_config('themerev', empty($CFG->themerev) ? 1 : $CFG->themerev+1);
  41. fulldelete("$CFG->dataroot/cache/theme");
  42. }
  43. /**
  44. * Enable or disable theme designer mode.
  45. * @param bool $state
  46. * @return void
  47. */
  48. function theme_set_designer_mod($state) {
  49. theme_reset_all_caches();
  50. set_config('themedesignermode', (int)!empty($state));
  51. }
  52. /**
  53. * Returns current theme revision number.
  54. * @return int
  55. */
  56. function theme_get_revision() {
  57. global $CFG;
  58. if (empty($CFG->themedesignermode)) {
  59. if (empty($CFG->themerev)) {
  60. return -1;
  61. } else {
  62. return $CFG->themerev;
  63. }
  64. } else {
  65. return -1;
  66. }
  67. }
  68. /**
  69. * This class represents the configuration variables of a Moodle theme.
  70. *
  71. * All the variables with access: public below (with a few exceptions that are marked)
  72. * are the properties you can set in your theme's config.php file.
  73. *
  74. * There are also some methods and protected variables that are part of the inner
  75. * workings of Moodle's themes system. If you are just editing a theme's config.php
  76. * file, you can just ignore those, and the following information for developers.
  77. *
  78. * Normally, to create an instance of this class, you should use the
  79. * {@link theme_config::load()} factory method to load a themes config.php file.
  80. * However, normally you don't need to bother, because moodle_page (that is, $PAGE)
  81. * will create one for you, accessible as $PAGE->theme.
  82. *
  83. * @copyright 2009 Tim Hunt
  84. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  85. * @since Moodle 2.0
  86. */
  87. class theme_config {
  88. /**
  89. * @var string default theme, used when requested theme not found
  90. */
  91. const DEFAULT_THEME = 'standard';
  92. /**
  93. * You can base your theme on other themes by linking to the other theme as
  94. * parents. This lets you use the CSS and layouts from the other themes
  95. * (see {@link $layouts}).
  96. * That makes it easy to create a new theme that is similar to another one
  97. * but with a few changes. In this theme's CSS you only need to override
  98. * those rules you want to change.
  99. *
  100. * @var array
  101. */
  102. public $parents;
  103. /**
  104. * The names of all the stylesheets from this theme that you would
  105. * like included, in order. Give the names of the files without .css.
  106. *
  107. * @var array
  108. */
  109. public $sheets = array();
  110. /**
  111. * The names of all the stylesheets from parents that should be excluded.
  112. * true value may be used to specify all parents or all themes from one parent.
  113. * If no value specified value from parent theme used.
  114. *
  115. * @var array or arrays, true means all, null means use value from parent
  116. */
  117. public $parents_exclude_sheets = null;
  118. /**
  119. * List of plugin sheets to be excluded.
  120. * If no value specified value from parent theme used.
  121. *
  122. * @var array of full plugin names, null means use value from parent
  123. */
  124. public $plugins_exclude_sheets = null;
  125. /**
  126. * List of style sheets that are included in the text editor bodies.
  127. * Sheets from parent themes are used automatically and can not be excluded.
  128. *
  129. * @var array
  130. */
  131. public $editor_sheets = array();
  132. /**
  133. * The names of all the javascript files this theme that you would
  134. * like included from head, in order. Give the names of the files without .js.
  135. *
  136. * @var array
  137. */
  138. public $javascripts = array();
  139. /**
  140. * The names of all the javascript files this theme that you would
  141. * like included from footer, in order. Give the names of the files without .js.
  142. *
  143. * @var array
  144. */
  145. public $javascripts_footer = array();
  146. /**
  147. * The names of all the javascript files from parents that should be excluded.
  148. * true value may be used to specify all parents or all themes from one parent.
  149. * If no value specified value from parent theme used.
  150. *
  151. * @var array or arrays, true means all, null means use value from parent
  152. */
  153. public $parents_exclude_javascripts = null;
  154. /**
  155. * Which file to use for each page layout.
  156. *
  157. * This is an array of arrays. The keys of the outer array are the different layouts.
  158. * Pages in Moodle are using several different layouts like 'normal', 'course', 'home',
  159. * 'popup', 'form', .... The most reliable way to get a complete list is to look at
  160. * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}.
  161. * That file also has a good example of how to set this setting.
  162. *
  163. * For each layout, the value in the outer array is an array that describes
  164. * how you want that type of page to look. For example
  165. * <pre>
  166. * $THEME->layouts = array(
  167. * // Most pages - if we encounter an unknown or a missing page type, this one is used.
  168. * 'standard' => array(
  169. * 'theme' = 'mytheme',
  170. * 'file' => 'normal.php',
  171. * 'regions' => array('side-pre', 'side-post'),
  172. * 'defaultregion' => 'side-post'
  173. * ),
  174. * // The site home page.
  175. * 'home' => array(
  176. * 'theme' = 'mytheme',
  177. * 'file' => 'home.php',
  178. * 'regions' => array('side-pre', 'side-post'),
  179. * 'defaultregion' => 'side-post'
  180. * ),
  181. * // ...
  182. * );
  183. * </pre>
  184. *
  185. * 'theme' name of the theme where is the layout located
  186. * 'file' is the layout file to use for this type of page.
  187. * layout files are stored in layout subfolder
  188. * 'regions' This lists the regions on the page where blocks may appear. For
  189. * each region you list here, your layout file must include a call to
  190. * <pre>
  191. * echo $OUTPUT->blocks_for_region($regionname);
  192. * </pre>
  193. * or equivalent so that the blocks are actually visible.
  194. *
  195. * 'defaultregion' If the list of regions is non-empty, then you must pick
  196. * one of the one of them as 'default'. This has two meanings. First, this is
  197. * where new blocks are added. Second, if there are any blocks associated with
  198. * the page, but in non-existent regions, they appear here. (Imaging, for example,
  199. * that someone added blocks using a different theme that used different region
  200. * names, and then switched to this theme.)
  201. *
  202. * @var array
  203. */
  204. public $layouts = array();
  205. /**
  206. * Name of the renderer factory class to use.
  207. *
  208. * This is an advanced feature. Moodle output is generated by 'renderers',
  209. * you can customise the HTML that is output by writing custom renderers,
  210. * and then you need to specify 'renderer factory' so that Moodle can find
  211. * your renderers.
  212. *
  213. * There are some renderer factories supplied with Moodle. Please follow these
  214. * links to see what they do.
  215. * <ul>
  216. * <li>{@link standard_renderer_factory} - the default.</li>
  217. * <li>{@link theme_overridden_renderer_factory} - use this if you want to write
  218. * your own custom renderers in a lib.php file in this theme (or the parent theme).</li>
  219. * </ul>
  220. *
  221. * @var string name of a class implementing the {@link renderer_factory} interface.
  222. */
  223. public $rendererfactory = 'standard_renderer_factory';
  224. /**
  225. * Function to do custom CSS post-processing.
  226. *
  227. * This is an advanced feature. If you want to do custom post-processing on the
  228. * CSS before it is output (for example, to replace certain variable names
  229. * with particular values) you can give the name of a function here.
  230. *
  231. * @var string the name of a function.
  232. */
  233. public $csspostprocess = null;
  234. /**
  235. * Accessibility: Right arrow-like character is
  236. * used in the breadcrumb trail, course navigation menu
  237. * (previous/next activity), calendar, and search forum block.
  238. * If the theme does not set characters, appropriate defaults
  239. * are set automatically. Please DO NOT
  240. * use &lt; &gt; &raquo; - these are confusing for blind users.
  241. *
  242. * @var string
  243. */
  244. public $rarrow = null;
  245. /**
  246. * Accessibility: Right arrow-like character is
  247. * used in the breadcrumb trail, course navigation menu
  248. * (previous/next activity), calendar, and search forum block.
  249. * If the theme does not set characters, appropriate defaults
  250. * are set automatically. Please DO NOT
  251. * use &lt; &gt; &raquo; - these are confusing for blind users.
  252. *
  253. * @var string
  254. */
  255. public $larrow = null;
  256. /**
  257. * Some themes may want to disable ajax course editing.
  258. * @var bool
  259. */
  260. public $enablecourseajax = true;
  261. //==Following properties are not configurable from theme config.php==
  262. /**
  263. * The name of this theme. Set automatically when this theme is
  264. * loaded. This can not be set in theme config.php
  265. * @var string
  266. */
  267. public $name;
  268. /**
  269. * the folder where this themes files are stored. This is set
  270. * automatically. This can not be set in theme config.php
  271. * @var string
  272. */
  273. public $dir;
  274. /**
  275. * Theme settings stored in config_plugins table.
  276. * This can not be set in theme config.php
  277. * @var object
  278. */
  279. public $setting = null;
  280. /**
  281. * If set to true and the theme enables the dock then blocks will be able
  282. * to be moved to the special dock
  283. * @var bool
  284. */
  285. public $enable_dock = false;
  286. /**
  287. * If set to true then this theme will not be shown in the theme selector unless
  288. * theme designer mode is turned on.
  289. * @var bool
  290. */
  291. public $hidefromselector = false;
  292. /**
  293. * Instance of the renderer_factory implementation
  294. * we are using. Implementation detail.
  295. * @var renderer_factory
  296. */
  297. protected $rf = null;
  298. /**
  299. * List of parent config objects.
  300. * @var array list of parent configs
  301. **/
  302. protected $parent_configs = array();
  303. /**
  304. * Load the config.php file for a particular theme, and return an instance
  305. * of this class. (That is, this is a factory method.)
  306. *
  307. * @param string $themename the name of the theme.
  308. * @return theme_config an instance of this class.
  309. */
  310. public static function load($themename) {
  311. global $CFG;
  312. // load theme settings from db
  313. try {
  314. $settings = get_config('theme_'.$themename);
  315. } catch (dml_exception $e) {
  316. // most probably moodle tables not created yet
  317. $settings = new stdClass();
  318. }
  319. if ($config = theme_config::find_theme_config($themename, $settings)) {
  320. return new theme_config($config);
  321. } else if ($themename == theme_config::DEFAULT_THEME) {
  322. throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!');
  323. } else {
  324. // bad luck, the requested theme has some problems - admin see details in theme config
  325. return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings));
  326. }
  327. }
  328. /**
  329. * Theme diagnostic code. It is very problematic to send debug output
  330. * to the actual CSS file, instead this functions is supposed to
  331. * diagnose given theme and highlights all potential problems.
  332. * This information should be available from the theme selection page
  333. * or some other debug page for theme designers.
  334. *
  335. * @param string $themename
  336. * @return array description of problems
  337. */
  338. public static function diagnose($themename) {
  339. //TODO: MDL-21108
  340. return array();
  341. }
  342. /**
  343. * Private constructor, can be called only from the factory method.
  344. * @param stdClass $config
  345. */
  346. private function __construct($config) {
  347. global $CFG; //needed for included lib.php files
  348. $this->settings = $config->settings;
  349. $this->name = $config->name;
  350. $this->dir = $config->dir;
  351. if ($this->name != 'base') {
  352. $baseconfig = theme_config::find_theme_config('base', $this->settings);
  353. } else {
  354. $baseconfig = $config;
  355. }
  356. $configurable = array('parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'javascripts', 'javascripts_footer',
  357. 'parents_exclude_javascripts', 'layouts', 'enable_dock', 'enablecourseajax',
  358. 'rendererfactory', 'csspostprocess', 'editor_sheets', 'rarrow', 'larrow', 'hidefromselector');
  359. foreach ($config as $key=>$value) {
  360. if (in_array($key, $configurable)) {
  361. $this->$key = $value;
  362. }
  363. }
  364. // verify all parents and load configs and renderers
  365. foreach ($this->parents as $parent) {
  366. if ($parent == 'base') {
  367. $parent_config = $baseconfig;
  368. } else if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) {
  369. // this is not good - better exclude faulty parents
  370. continue;
  371. }
  372. $libfile = $parent_config->dir.'/lib.php';
  373. if (is_readable($libfile)) {
  374. // theme may store various function here
  375. include_once($libfile);
  376. }
  377. $renderersfile = $parent_config->dir.'/renderers.php';
  378. if (is_readable($renderersfile)) {
  379. // may contain core and plugin renderers and renderer factory
  380. include_once($renderersfile);
  381. }
  382. $this->parent_configs[$parent] = $parent_config;
  383. $rendererfile = $parent_config->dir.'/renderers.php';
  384. if (is_readable($rendererfile)) {
  385. // may contain core and plugin renderers and renderer factory
  386. include_once($rendererfile);
  387. }
  388. }
  389. $libfile = $this->dir.'/lib.php';
  390. if (is_readable($libfile)) {
  391. // theme may store various function here
  392. include_once($libfile);
  393. }
  394. $rendererfile = $this->dir.'/renderers.php';
  395. if (is_readable($rendererfile)) {
  396. // may contain core and plugin renderers and renderer factory
  397. include_once($rendererfile);
  398. }
  399. // cascade all layouts properly
  400. foreach ($baseconfig->layouts as $layout=>$value) {
  401. if (!isset($this->layouts[$layout])) {
  402. foreach ($this->parent_configs as $parent_config) {
  403. if (isset($parent_config->layouts[$layout])) {
  404. $this->layouts[$layout] = $parent_config->layouts[$layout];
  405. continue 2;
  406. }
  407. }
  408. $this->layouts[$layout] = $value;
  409. }
  410. }
  411. //fix arrows if needed
  412. $this->check_theme_arrows();
  413. }
  414. /*
  415. * Checks if arrows $THEME->rarrow, $THEME->larrow have been set (theme/-/config.php).
  416. * If not it applies sensible defaults.
  417. *
  418. * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar,
  419. * search forum block, etc. Important: these are 'silent' in a screen-reader
  420. * (unlike &gt; &raquo;), and must be accompanied by text.
  421. */
  422. private function check_theme_arrows() {
  423. if (!isset($this->rarrow) and !isset($this->larrow)) {
  424. // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8...
  425. // Also OK in Win 9x/2K/IE 5.x
  426. $this->rarrow = '&#x25BA;';
  427. $this->larrow = '&#x25C4;';
  428. if (empty($_SERVER['HTTP_USER_AGENT'])) {
  429. $uagent = '';
  430. } else {
  431. $uagent = $_SERVER['HTTP_USER_AGENT'];
  432. }
  433. if (false !== strpos($uagent, 'Opera')
  434. || false !== strpos($uagent, 'Mac')) {
  435. // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari.
  436. // Not broken in Mac/IE 5, Mac/Netscape 7 (?).
  437. $this->rarrow = '&#x25B6;';
  438. $this->larrow = '&#x25C0;';
  439. }
  440. elseif (false !== strpos($uagent, 'Konqueror')) {
  441. $this->rarrow = '&rarr;';
  442. $this->larrow = '&larr;';
  443. }
  444. elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET'])
  445. && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) {
  446. // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.)
  447. // To be safe, non-Unicode browsers!
  448. $this->rarrow = '&gt;';
  449. $this->larrow = '&lt;';
  450. }
  451. /// RTL support - in RTL languages, swap r and l arrows
  452. if (right_to_left()) {
  453. $t = $this->rarrow;
  454. $this->rarrow = $this->larrow;
  455. $this->larrow = $t;
  456. }
  457. }
  458. }
  459. /**
  460. * Returns output renderer prefixes, these are used when looking
  461. * for the overridden renderers in themes.
  462. * @return array
  463. */
  464. public function renderer_prefixes() {
  465. global $CFG; // just in case the included files need it
  466. $prefixes = array('theme_'.$this->name);
  467. foreach ($this->parent_configs as $parent) {
  468. $prefixes[] = 'theme_'.$parent->name;
  469. }
  470. return $prefixes;
  471. }
  472. /**
  473. * Returns the stylesheet URL of this editor content
  474. * @param bool $encoded false means use & and true use &amp; in URLs
  475. * @return string
  476. */
  477. public function editor_css_url($encoded=true) {
  478. global $CFG;
  479. $rev = theme_get_revision();
  480. if ($rev > -1) {
  481. $params = array('theme'=>$this->name,'rev'=>$rev, 'type'=>'editor');
  482. return new moodle_url($CFG->httpswwwroot.'/theme/styles.php', $params);
  483. } else {
  484. $params = array('theme'=>$this->name, 'type'=>'editor');
  485. return new moodle_url($CFG->httpswwwroot.'/theme/styles_debug.php', $params);
  486. }
  487. }
  488. /**
  489. * Returns the content of the CSS to be used in editor content
  490. * @return string
  491. */
  492. public function editor_css_files() {
  493. global $CFG;
  494. $files = array();
  495. // first editor plugins
  496. $plugins = get_plugin_list('editor');
  497. foreach ($plugins as $plugin=>$fulldir) {
  498. $sheetfile = "$fulldir/editor_styles.css";
  499. if (is_readable($sheetfile)) {
  500. $files['plugin_'.$plugin] = $sheetfile;
  501. }
  502. }
  503. // then parent themes
  504. foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
  505. if (empty($parent_config->editor_sheets)) {
  506. continue;
  507. }
  508. foreach ($parent_config->editor_sheets as $sheet) {
  509. $sheetfile = "$parent_config->dir/style/$sheet.css";
  510. if (is_readable($sheetfile)) {
  511. $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile;
  512. }
  513. }
  514. }
  515. // finally this theme
  516. if (!empty($this->editor_sheets)) {
  517. foreach ($this->editor_sheets as $sheet) {
  518. $sheetfile = "$this->dir/style/$sheet.css";
  519. if (is_readable($sheetfile)) {
  520. $files['theme_'.$sheet] = $sheetfile;
  521. }
  522. }
  523. }
  524. return $files;
  525. }
  526. /**
  527. * Get the stylesheet URL of this theme
  528. * @param bool $encoded false means use & and true use &amp; in URLs
  529. * @return array of moodle_url
  530. */
  531. public function css_urls(moodle_page $page) {
  532. global $CFG;
  533. $rev = theme_get_revision();
  534. $urls = array();
  535. if ($rev > -1) {
  536. if (check_browser_version('MSIE', 5)) {
  537. // We need to split the CSS files for IE
  538. $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'plugins'));
  539. $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'parents'));
  540. $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev, 'type'=>'theme'));
  541. } else {
  542. $urls[] = new moodle_url($CFG->httpswwwroot.'/theme/styles.php', array('theme'=>$this->name,'rev'=>$rev));
  543. }
  544. } else {
  545. // find out the current CSS and cache it now for 5 seconds
  546. // the point is to construct the CSS only once and pass it through the
  547. // dataroot to the script that actually serves the sheets
  548. if (!defined('THEME_DESIGNER_CACHE_LIFETIME')) {
  549. define('THEME_DESIGNER_CACHE_LIFETIME', 4); // this can be also set in config.php
  550. }
  551. $candidatesheet = "$CFG->dataroot/cache/theme/$this->name/designer.ser";
  552. if (!file_exists($candidatesheet)) {
  553. $css = $this->css_content();
  554. check_dir_exists(dirname($candidatesheet));
  555. file_put_contents($candidatesheet, serialize($css));
  556. } else if (filemtime($candidatesheet) > time() - THEME_DESIGNER_CACHE_LIFETIME) {
  557. if ($css = file_get_contents($candidatesheet)) {
  558. $css = unserialize($css);
  559. } else {
  560. unlink($candidatesheet);
  561. $css = $this->css_content();
  562. }
  563. } else {
  564. unlink($candidatesheet);
  565. $css = $this->css_content();
  566. file_put_contents($candidatesheet, serialize($css));
  567. }
  568. $baseurl = $CFG->httpswwwroot.'/theme/styles_debug.php';
  569. if (check_browser_version('MSIE', 5)) {
  570. // lalala, IE does not allow more than 31 linked CSS files from main document
  571. $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins'));
  572. foreach ($css['parents'] as $parent=>$sheets) {
  573. // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096)
  574. $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent));
  575. }
  576. $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme'));
  577. } else {
  578. foreach ($css['plugins'] as $plugin=>$unused) {
  579. $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin));
  580. }
  581. foreach ($css['parents'] as $parent=>$sheets) {
  582. foreach ($sheets as $sheet=>$unused2) {
  583. $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet));
  584. }
  585. }
  586. foreach ($css['theme'] as $sheet=>$unused) {
  587. $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme')); // sheet first in order to make long urls easier to read
  588. }
  589. }
  590. }
  591. return $urls;
  592. }
  593. /**
  594. * Returns an array of organised CSS files required for this output
  595. * @return array
  596. */
  597. public function css_files() {
  598. $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array());
  599. // get all plugin sheets
  600. $excludes = $this->resolve_excludes('plugins_exclude_sheets');
  601. if ($excludes !== true) {
  602. foreach (get_plugin_types() as $type=>$unused) {
  603. if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) {
  604. continue;
  605. }
  606. $plugins = get_plugin_list($type);
  607. foreach ($plugins as $plugin=>$fulldir) {
  608. if (!empty($excludes[$type]) and is_array($excludes[$type])
  609. and in_array($plugin, $excludes[$type])) {
  610. continue;
  611. }
  612. $plugincontent = '';
  613. $sheetfile = "$fulldir/styles.css";
  614. if (is_readable($sheetfile)) {
  615. $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile;
  616. }
  617. $sheetthemefile = "$fulldir/styles_{$this->name}.css";
  618. if (is_readable($sheetthemefile)) {
  619. $cssfiles['plugins'][$type.'_'.$plugin.'_'.$this->name] = $sheetthemefile;
  620. }
  621. }
  622. }
  623. }
  624. // find out wanted parent sheets
  625. $excludes = $this->resolve_excludes('parents_exclude_sheets');
  626. if ($excludes !== true) {
  627. foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
  628. $parent = $parent_config->name;
  629. if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) {
  630. continue;
  631. }
  632. foreach ($parent_config->sheets as $sheet) {
  633. if (!empty($excludes[$parent]) and is_array($excludes[$parent])
  634. and in_array($sheet, $excludes[$parent])) {
  635. continue;
  636. }
  637. $sheetfile = "$parent_config->dir/style/$sheet.css";
  638. if (is_readable($sheetfile)) {
  639. $cssfiles['parents'][$parent][$sheet] = $sheetfile;
  640. }
  641. }
  642. }
  643. }
  644. // current theme sheets
  645. if (is_array($this->sheets)) {
  646. foreach ($this->sheets as $sheet) {
  647. $sheetfile = "$this->dir/style/$sheet.css";
  648. if (is_readable($sheetfile)) {
  649. $cssfiles['theme'][$sheet] = $sheetfile;
  650. }
  651. }
  652. }
  653. return $cssfiles;
  654. }
  655. /**
  656. * Returns the content of the one huge CSS merged from all style sheets.
  657. * @return string
  658. */
  659. public function css_content() {
  660. $files = array_merge($this->css_files(), array('editor'=>$this->editor_css_files()));
  661. $css = $this->css_files_get_contents($files, array());
  662. return $css;
  663. }
  664. /**
  665. * Given an array of file paths or a single file path loads the contents of
  666. * the CSS file, processes it then returns it in the same structure it was given.
  667. *
  668. * Can be used recursively on the results of {@see css_files}
  669. *
  670. * @param array|string $file An array of file paths or a single file path
  671. * @param array $keys An array of previous array keys [recursive addition]
  672. * @return The converted array or the contents of the single file ($file type)
  673. */
  674. protected function css_files_get_contents($file, array $keys) {
  675. if (is_array($file)) {
  676. foreach ($file as $key=>$f) {
  677. $file[$key] = $this->css_files_get_contents($f, array_merge($keys, array($key)));
  678. }
  679. return $file;
  680. } else {
  681. $comment = '/** Path: '.implode(' ', $keys).' **/'."\n";
  682. return $comment.$this->post_process(file_get_contents($file));
  683. }
  684. }
  685. /**
  686. * Get the javascript URL of this theme
  687. * @param bool $inhead true means head url, false means footer
  688. * @return moodle_url
  689. */
  690. public function javascript_url($inhead) {
  691. global $CFG;
  692. $rev = theme_get_revision();
  693. $params = array('theme'=>$this->name,'rev'=>$rev);
  694. $params['type'] = $inhead ? 'head' : 'footer';
  695. return new moodle_url($CFG->httpswwwroot.'/theme/javascript.php', $params);
  696. }
  697. public function javascript_files($type) {
  698. if ($type === 'footer') {
  699. $type = 'javascripts_footer';
  700. } else {
  701. $type = 'javascripts';
  702. }
  703. $js = array();
  704. // find out wanted parent javascripts
  705. $excludes = $this->resolve_excludes('parents_exclude_javascripts');
  706. if ($excludes !== true) {
  707. foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
  708. $parent = $parent_config->name;
  709. if (empty($parent_config->$type)) {
  710. continue;
  711. }
  712. if (!empty($excludes[$parent]) and $excludes[$parent] === true) {
  713. continue;
  714. }
  715. foreach ($parent_config->$type as $javascript) {
  716. if (!empty($excludes[$parent]) and is_array($excludes[$parent])
  717. and in_array($javascript, $excludes[$parent])) {
  718. continue;
  719. }
  720. $javascriptfile = "$parent_config->dir/javascript/$javascript.js";
  721. if (is_readable($javascriptfile)) {
  722. $js[] = $javascriptfile;
  723. }
  724. }
  725. }
  726. }
  727. // current theme javascripts
  728. if (is_array($this->$type)) {
  729. foreach ($this->$type as $javascript) {
  730. $javascriptfile = "$this->dir/javascript/$javascript.js";
  731. if (is_readable($javascriptfile)) {
  732. $js[] = $javascriptfile;
  733. }
  734. }
  735. }
  736. return $js;
  737. }
  738. /**
  739. * Resolves an exclude setting to the theme's setting is applicable or the
  740. * setting of its closest parent.
  741. *
  742. * @param string $variable The name of the setting the exclude setting to resolve
  743. * @return mixed
  744. */
  745. protected function resolve_excludes($variable, $default=null) {
  746. $setting = $default;
  747. if (is_array($this->{$variable}) or $this->{$variable} === true) {
  748. $setting = $this->{$variable};
  749. } else {
  750. foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last
  751. if (!isset($parent_config->{$variable})) {
  752. continue;
  753. }
  754. if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) {
  755. $setting = $parent_config->{$variable};
  756. break;
  757. }
  758. }
  759. }
  760. return $setting;
  761. }
  762. /**
  763. * Returns the content of the one huge javascript file merged from all theme javascript files.
  764. * @param bool $inhead
  765. * @return string
  766. */
  767. public function javascript_content($type) {
  768. $jsfiles = $this->javascript_files($type);
  769. $js = '';
  770. foreach ($jsfiles as $jsfile) {
  771. $js .= file_get_contents($jsfile)."\n";
  772. }
  773. return $js;
  774. }
  775. public function post_process($css) {
  776. global $CFG;
  777. // now resolve all image locations
  778. if (preg_match_all('/\[\[pix:([a-z_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) {
  779. $replaced = array();
  780. foreach ($matches as $match) {
  781. if (isset($replaced[$match[0]])) {
  782. continue;
  783. }
  784. $replaced[$match[0]] = true;
  785. $imagename = $match[2];
  786. $component = rtrim($match[1], '|');
  787. $imageurl = $this->pix_url($imagename, $component)->out(false);
  788. // we do not need full url because the image.php is always in the same dir
  789. $imageurl = str_replace("$CFG->httpswwwroot/theme/", '', $imageurl);
  790. $css = str_replace($match[0], $imageurl, $css);
  791. }
  792. }
  793. // now resolve all theme settings or do any other postprocessing
  794. $csspostprocess = $this->csspostprocess;
  795. if (function_exists($csspostprocess)) {
  796. $css = $csspostprocess($css, $this);
  797. }
  798. return $css;
  799. }
  800. /**
  801. * Return the URL for an image
  802. *
  803. * @param string $imagename the name of the icon.
  804. * @param string $component, specification of one plugin like in get_string()
  805. * @return moodle_url
  806. */
  807. public function pix_url($imagename, $component) {
  808. global $CFG;
  809. $params = array('theme'=>$this->name, 'image'=>$imagename);
  810. $rev = theme_get_revision();
  811. if ($rev != -1) {
  812. $params['rev'] = $rev;
  813. }
  814. if (!empty($component) and $component !== 'moodle'and $component !== 'core') {
  815. $params['component'] = $component;
  816. }
  817. return new moodle_url("$CFG->httpswwwroot/theme/image.php", $params);
  818. }
  819. /**
  820. * Resolves the real image location.
  821. * @param string $image name of image, may contain relative path
  822. * @param string $component
  823. * @return string full file path
  824. */
  825. public function resolve_image_location($image, $component) {
  826. global $CFG;
  827. if ($component === 'moodle' or $component === 'core' or empty($component)) {
  828. if ($imagefile = $this->image_exists("$this->dir/pix_core/$image")) {
  829. return $imagefile;
  830. }
  831. foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
  832. if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image")) {
  833. return $imagefile;
  834. }
  835. }
  836. if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image")) {
  837. return $imagefile;
  838. }
  839. return null;
  840. } else if ($component === 'theme') { //exception
  841. if ($image === 'favicon') {
  842. return "$this->dir/pix/favicon.ico";
  843. }
  844. if ($imagefile = $this->image_exists("$this->dir/pix/$image")) {
  845. return $imagefile;
  846. }
  847. foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
  848. if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image")) {
  849. return $imagefile;
  850. }
  851. }
  852. return null;
  853. } else {
  854. if (strpos($component, '_') === false) {
  855. $component = 'mod_'.$component;
  856. }
  857. list($type, $plugin) = explode('_', $component, 2);
  858. if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image")) {
  859. return $imagefile;
  860. }
  861. foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last
  862. if ($imagefile = $this->image_exists("$parent_config->dir/pix_plugins/$type/$plugin/$image")) {
  863. return $imagefile;
  864. }
  865. }
  866. $dir = get_plugin_directory($type, $plugin);
  867. if ($imagefile = $this->image_exists("$dir/pix/$image")) {
  868. return $imagefile;
  869. }
  870. return null;
  871. }
  872. }
  873. /**
  874. * Checks if file with any image extension exists.
  875. * @param string $filepath
  876. * @return string image name with extension
  877. */
  878. private static function image_exists($filepath) {
  879. if (file_exists("$filepath.gif")) {
  880. return "$filepath.gif";
  881. } else if (file_exists("$filepath.png")) {
  882. return "$filepath.png";
  883. } else if (file_exists("$filepath.jpg")) {
  884. return "$filepath.jpg";
  885. } else if (file_exists("$filepath.jpeg")) {
  886. return "$filepath.jpeg";
  887. } else {
  888. return false;
  889. }
  890. }
  891. /**
  892. * Loads the theme config from config.php file.
  893. * @param string $themename
  894. * @param object $settings from config_plugins table
  895. * @return object
  896. */
  897. private static function find_theme_config($themename, $settings) {
  898. // We have to use the variable name $THEME (upper case) because that
  899. // is what is used in theme config.php files.
  900. if (!$dir = theme_config::find_theme_location($themename)) {
  901. return null;
  902. }
  903. $THEME = new stdClass();
  904. $THEME->name = $themename;
  905. $THEME->dir = $dir;
  906. $THEME->settings = $settings;
  907. global $CFG; // just in case somebody tries to use $CFG in theme config
  908. include("$THEME->dir/config.php");
  909. // verify the theme configuration is OK
  910. if (!is_array($THEME->parents)) {
  911. // parents option is mandatory now
  912. return null;
  913. }
  914. return $THEME;
  915. }
  916. /**
  917. * Finds the theme location and verifies the theme has all needed files
  918. * and is not obsoleted.
  919. * @param string $themename
  920. * @return string full dir path or null if not found
  921. */
  922. private static function find_theme_location($themename) {
  923. global $CFG;
  924. if (file_exists("$CFG->dirroot/theme/$themename/config.php")) {
  925. $dir = "$CFG->dirroot/theme/$themename";
  926. } else {
  927. return null;
  928. }
  929. if (file_exists("$dir/styles.php")) {
  930. //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page
  931. return null;
  932. }
  933. return $dir;
  934. }
  935. /**
  936. * Get the renderer for a part of Moodle for this theme.
  937. * @param moodle_page $page the page we are rendering
  938. * @param string $module the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'.
  939. * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news'
  940. * @param string $target one of rendering target constants
  941. * @return renderer_base the requested renderer.
  942. */
  943. public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) {
  944. if (is_null($this->rf)) {
  945. $classname = $this->rendererfactory;
  946. $this->rf = new $classname($this);
  947. }
  948. return $this->rf->get_renderer($page, $component, $subtype, $target);
  949. }
  950. /**
  951. * Get the information from {@link $layouts} for this type of page.
  952. * @param string $pagelayout the the page layout name.
  953. * @return array the appropriate part of {@link $layouts}.
  954. */
  955. protected function layout_info_for_page($pagelayout) {
  956. if (array_key_exists($pagelayout, $this->layouts)) {
  957. return $this->layouts[$pagelayout];
  958. } else {
  959. debugging('Invalid page layout specified: ' . $pagelayout);
  960. return $this->layouts['standard'];
  961. }
  962. }
  963. /**
  964. * Given the settings of this theme, and the page pagelayout, return the
  965. * full path of the page layout file to use.
  966. *
  967. * Used by {@link core_renderer::header()}.
  968. *
  969. * @param string $pagelayout the the page layout name.
  970. * @return string Full path to the lyout file to use
  971. */
  972. public function layout_file($pagelayout) {
  973. global $CFG;
  974. $layoutinfo = $this->layout_info_for_page($pagelayout);
  975. $layoutfile = $layoutinfo['file'];
  976. if (array_key_exists('theme', $layoutinfo)) {
  977. $themes = array($layoutinfo['theme']);
  978. } else {
  979. $themes = array_merge(array($this->name),$this->parents);
  980. }
  981. foreach ($themes as $theme) {
  982. if ($dir = $this->find_theme_location($theme)) {
  983. $path = "$dir/layout/$layoutfile";
  984. // Check the template exists, return general base theme template if not.
  985. if (is_readable($path)) {
  986. return $path;
  987. }
  988. }
  989. }
  990. debugging('Can not find layout file for: ' . $pagelayout);
  991. // fallback to standard normal layout
  992. return "$CFG->dirroot/theme/base/layout/general.php";
  993. }
  994. /**
  995. * Returns auxiliary page layout options specified in layout configuration array.
  996. * @param string $pagelayout
  997. * @return array
  998. */
  999. public function pagelayout_options($pagelayout) {
  1000. $info = $this->layout_info_for_page($pagelayout);
  1001. if (!empty($info['options'])) {
  1002. return $info['options'];
  1003. }
  1004. return array();
  1005. }
  1006. /**
  1007. * Inform a block_manager about the block regions this theme wants on this
  1008. * page layout.
  1009. * @param string $pagelayout the general type of the page.
  1010. * @param block_manager $blockmanager the block_manger to set up.
  1011. * @return void
  1012. */
  1013. public function setup_blocks($pagelayout, $blockmanager) {
  1014. $layoutinfo = $this->layout_info_for_page($pagelayout);
  1015. if (!empty($layoutinfo['regions'])) {
  1016. $blockmanager->add_regions($layoutinfo['regions']);
  1017. $blockmanager->set_default_region($layoutinfo['defaultregion']);
  1018. }
  1019. }
  1020. protected function get_region_name($region, $theme) {
  1021. $regionstring = get_string('region-' . $region, 'theme_' . $theme);
  1022. // A name exists in this theme, so use it
  1023. if (substr($regionstring, 0, 1) != '[') {
  1024. return $regionstring;
  1025. }
  1026. // Otherwise, try to find one elsewhere
  1027. // Check parents, if any
  1028. foreach ($this->parents as $parentthemename) {
  1029. $regionstring = get_string('region-' . $region, 'theme_' . $parentthemename);
  1030. if (substr($regionstring, 0, 1) != '[') {
  1031. return $regionstring;
  1032. }
  1033. }
  1034. // Last resort, try the base theme for names
  1035. return get_string('region-' . $region, 'theme_base');
  1036. }
  1037. /**
  1038. * Get the list of all block regions known to this theme in all templates.
  1039. * @return array internal region name => human readable name.
  1040. */
  1041. public function get_all_block_regions() {
  1042. $regions = array();
  1043. foreach ($this->layouts as $layoutinfo) {
  1044. foreach ($layoutinfo['regions'] as $region) {
  1045. $regions[$region] = $this->get_region_name($region, $this->name);
  1046. }
  1047. }
  1048. return $regions;
  1049. }
  1050. }
  1051. /**
  1052. * This class keeps track of which HTML tags are currently open.
  1053. *
  1054. * This makes it much easier to always generate well formed XHTML output, even
  1055. * if execution terminates abruptly. Any time you output some opening HTML
  1056. * without the matching closing HTML, you should push the necessary close tags
  1057. * onto the stack.
  1058. *
  1059. * @copyright 2009 Tim Hunt
  1060. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1061. * @since Moodle 2.0
  1062. */
  1063. class xhtml_container_stack {
  1064. /** @var array stores the list of open containers. */
  1065. protected $opencontainers = array();
  1066. /**
  1067. * @var array in developer debug mode, stores a stack trace of all opens and
  1068. * closes, so we can output helpful error messages when there is a mismatch.
  1069. */
  1070. protected $log = array();
  1071. /**
  1072. * Store whether we are developer debug mode. We need this in several places
  1073. * including in the destructor where we may not have access to $CFG.
  1074. * @var boolean
  1075. */
  1076. protected $isdebugging;
  1077. public function __construct() {
  1078. $this->isdebugging = debugging('', DEBUG_DEVELOPER);
  1079. }
  1080. /**
  1081. * Push the close HTML for a recently opened container onto the stack.
  1082. * @param string $type The type of container. This is checked when {@link pop()}
  1083. * is called and must match, otherwise a developer debug warning is output.
  1084. * @param string $closehtml The HTML required to close the container.
  1085. * @return void
  1086. */
  1087. public function push($type, $closehtml) {
  1088. $container = new stdClass;
  1089. $container->type = $type;
  1090. $container->closehtml = $closehtml;
  1091. if ($this->isdebugging) {
  1092. $this->log('Open', $type);
  1093. }
  1094. array_push($this->opencontainers, $container);
  1095. }
  1096. /**
  1097. * Pop the HTML for the next closing container from the stack. The $type
  1098. * must match the type passed when the container was opened, otherwise a
  1099. * warning will be output.
  1100. * @param string $type The type of container.
  1101. * @return string the HTML required to close the container.
  1102. */
  1103. public function pop($type) {
  1104. if (empty($this->opencontainers)) {
  1105. debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' .
  1106. $this->output_log(), DEBUG_DEVELOPER);
  1107. return;
  1108. }
  1109. $container = array_pop($this->opencontainers);
  1110. if ($container->type != $type) {
  1111. debugging('<p>The type of container to be closed (' . $container->type .
  1112. ') does not match the type of the next open container (' . $type .
  1113. '). This suggests there is a nesting problem.</p>' .
  1114. $this->output_log(), DEBUG_DEVELOPER);
  1115. }
  1116. if ($this->isdebugging) {
  1117. $this->log('Close', $type);
  1118. }
  1119. return $container->closehtml;
  1120. }
  1121. /**
  1122. * Close all but the last open container. This is useful in places like error
  1123. * handling, where you want to close all the open containers (apart from <body>)
  1124. * before outputting the error message.
  1125. * @param bool $shouldbenone assert that the stack should be empty now - causes a
  1126. * developer debug warning if it isn't.
  1127. * @return string the HTML required to close any open containers inside <body>.
  1128. */
  1129. public function pop_all_but_last($shouldbenone = false) {
  1130. if ($shouldbenone && count($this->opencontainers) != 1) {
  1131. debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' .
  1132. $this->output_log(), DEBUG_DEVELOPER);
  1133. }
  1134. $output = '';
  1135. while (count($this->opencontainers) > 1) {
  1136. $container = array_pop($this->opencontainers);
  1137. $output .= $container->closehtml;
  1138. }
  1139. return $output;
  1140. }
  1141. /**
  1142. * You can call this function if you want to throw away an instance of this
  1143. * class without properly emptying the stack (for example, in a unit test).
  1144. * Calling this method stops the destruct method from outputting a developer
  1145. * debug warning. After calling this method, the instance can no longer be used.
  1146. * @return void
  1147. */
  1148. public function discard() {
  1149. $this->opencontainers = null;
  1150. }
  1151. /**
  1152. * Adds an entry to the log.
  1153. * @param string $action The name of the action
  1154. * @param string $type The type of action
  1155. * @return void
  1156. */
  1157. protected function log($action, $type) {
  1158. $this->log[] = '<li>' . $action . ' ' . $type . ' at:' .
  1159. format_backtrace(debug_backtrace()) . '</li>';
  1160. }
  1161. /**
  1162. * Outputs the log's contents as a HTML list.
  1163. * @return string HTML list of the log
  1164. */
  1165. protected function output_log() {
  1166. return '<ul>' . implode("\n", $this->log) . '</ul>';
  1167. }
  1168. }