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