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