Differences Between: [Versions 310 and 403] [Versions 311 and 403] [Versions 39 and 403] [Versions 400 and 403] [Versions 401 and 403] [Versions 402 and 403]
1 <?php 2 // This file is part of Moodle - http://moodle.org/ 3 // 4 // Moodle is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // Moodle is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU General Public License for more details. 13 // 14 // You should have received a copy of the GNU General Public License 15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>. 16 17 /** 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 * 23 * @copyright 2009 Tim Hunt 24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 25 * @package core 26 * @category output 27 */ 28 29 defined('MOODLE_INTERNAL') || die(); 30 31 require_once($CFG->libdir.'/outputcomponents.php'); 32 require_once($CFG->libdir.'/outputactions.php'); 33 require_once($CFG->libdir.'/outputfactories.php'); 34 require_once($CFG->libdir.'/outputrenderers.php'); 35 require_once($CFG->libdir.'/outputrequirementslib.php'); 36 37 /** 38 * Returns current theme revision number. 39 * 40 * @return int 41 */ 42 function theme_get_revision() { 43 global $CFG; 44 45 if (empty($CFG->themedesignermode)) { 46 if (empty($CFG->themerev)) { 47 // This only happens during install. It doesn't matter what themerev we use as long as it's positive. 48 return 1; 49 } else { 50 return $CFG->themerev; 51 } 52 53 } else { 54 return -1; 55 } 56 } 57 58 /** 59 * Returns current theme sub revision number. This is the revision for 60 * this theme exclusively, not the global theme revision. 61 * 62 * @param string $themename The non-frankenstyle name of the theme 63 * @return int 64 */ 65 function theme_get_sub_revision_for_theme($themename) { 66 global $CFG; 67 68 if (empty($CFG->themedesignermode)) { 69 $pluginname = "theme_{$themename}"; 70 $revision = during_initial_install() ? null : get_config($pluginname, 'themerev'); 71 72 if (empty($revision)) { 73 // This only happens during install. It doesn't matter what themerev we use as long as it's positive. 74 return 1; 75 } else { 76 return $revision; 77 } 78 } else { 79 return -1; 80 } 81 } 82 83 /** 84 * Calculates and returns the next theme revision number. 85 * 86 * @return int 87 */ 88 function theme_get_next_revision() { 89 global $CFG; 90 91 $next = time(); 92 if (isset($CFG->themerev) and $next <= $CFG->themerev and $CFG->themerev - $next < 60*60) { 93 // This resolves problems when reset is requested repeatedly within 1s, 94 // the < 1h condition prevents accidental switching to future dates 95 // because we might not recover from it. 96 $next = $CFG->themerev+1; 97 } 98 99 return $next; 100 } 101 102 /** 103 * Calculates and returns the next theme revision number. 104 * 105 * @param string $themename The non-frankenstyle name of the theme 106 * @return int 107 */ 108 function theme_get_next_sub_revision_for_theme($themename) { 109 global $CFG; 110 111 $next = time(); 112 $current = theme_get_sub_revision_for_theme($themename); 113 if ($next <= $current and $current - $next < 60 * 60) { 114 // This resolves problems when reset is requested repeatedly within 1s, 115 // the < 1h condition prevents accidental switching to future dates 116 // because we might not recover from it. 117 $next = $current + 1; 118 } 119 120 return $next; 121 } 122 123 /** 124 * Sets the current theme revision number. 125 * 126 * @param int $revision The new theme revision number 127 */ 128 function theme_set_revision($revision) { 129 set_config('themerev', $revision); 130 } 131 132 /** 133 * Sets the current theme revision number for a specific theme. 134 * This does not affect the global themerev value. 135 * 136 * @param string $themename The non-frankenstyle name of the theme 137 * @param int $revision The new theme revision number 138 */ 139 function theme_set_sub_revision_for_theme($themename, $revision) { 140 set_config('themerev', $revision, "theme_{$themename}"); 141 } 142 143 /** 144 * Get the path to a theme config.php file. 145 * 146 * @param string $themename The non-frankenstyle name of the theme to check 147 */ 148 function theme_get_config_file_path($themename) { 149 global $CFG; 150 151 if (file_exists("{$CFG->dirroot}/theme/{$themename}/config.php")) { 152 return "{$CFG->dirroot}/theme/{$themename}/config.php"; 153 } else if (!empty($CFG->themedir) and file_exists("{$CFG->themedir}/{$themename}/config.php")) { 154 return "{$CFG->themedir}/{$themename}/config.php"; 155 } else { 156 return null; 157 } 158 } 159 160 /** 161 * Get the path to the local cached CSS file. 162 * 163 * @param string $themename The non-frankenstyle theme name. 164 * @param int $globalrevision The global theme revision. 165 * @param int $themerevision The theme specific revision. 166 * @param string $direction Either 'ltr' or 'rtl' (case sensitive). 167 */ 168 function theme_get_css_filename($themename, $globalrevision, $themerevision, $direction) { 169 global $CFG; 170 171 $path = "{$CFG->localcachedir}/theme/{$globalrevision}/{$themename}/css"; 172 $filename = $direction == 'rtl' ? "all-rtl_{$themerevision}" : "all_{$themerevision}"; 173 return "{$path}/{$filename}.css"; 174 } 175 176 /** 177 * Generates and saves the CSS files for the given theme configs. 178 * 179 * @param theme_config[] $themeconfigs An array of theme_config instances. 180 * @param array $directions Must be a subset of ['rtl', 'ltr']. 181 * @param bool $cache Should the generated files be stored in local cache. 182 * @return array The built theme content in a multi-dimensional array of name => direction => content 183 */ 184 function theme_build_css_for_themes($themeconfigs = [], $directions = ['rtl', 'ltr'], 185 $cache = true, $mtraceprogress = false): array { 186 global $CFG; 187 188 if (empty($themeconfigs)) { 189 return []; 190 } 191 192 require_once("{$CFG->libdir}/csslib.php"); 193 194 $themescss = []; 195 $themerev = theme_get_revision(); 196 // Make sure the local cache directory exists. 197 make_localcache_directory('theme'); 198 199 foreach ($themeconfigs as $themeconfig) { 200 $themecss = []; 201 $oldrevision = theme_get_sub_revision_for_theme($themeconfig->name); 202 $newrevision = theme_get_next_sub_revision_for_theme($themeconfig->name); 203 204 // First generate all the new css. 205 foreach ($directions as $direction) { 206 if ($mtraceprogress) { 207 $timestart = microtime(true); 208 mtrace('Building theme CSS for ' . $themeconfig->name . ' [' . 209 $direction . '] ...', ''); 210 } 211 // Lock it on. Technically we should build all themes for SVG and no SVG - but ie9 is out of support. 212 $themeconfig->force_svg_use(true); 213 $themeconfig->set_rtl_mode(($direction === 'rtl')); 214 215 $themecss[$direction] = $themeconfig->get_css_content(); 216 if ($cache) { 217 $themeconfig->set_css_content_cache($themecss[$direction]); 218 $filename = theme_get_css_filename($themeconfig->name, $themerev, $newrevision, $direction); 219 css_store_css($themeconfig, $filename, $themecss[$direction]); 220 } 221 if ($mtraceprogress) { 222 mtrace(' done in ' . round(microtime(true) - $timestart, 2) . ' seconds.'); 223 } 224 } 225 $themescss[$themeconfig->name] = $themecss; 226 227 if ($cache) { 228 // Only update the theme revision after we've successfully created the 229 // new CSS cache. 230 theme_set_sub_revision_for_theme($themeconfig->name, $newrevision); 231 232 // Now purge old files. We must purge all old files in the local cache 233 // because we've incremented the theme sub revision. This will leave any 234 // files with the old revision inaccessbile so we might as well removed 235 // them from disk. 236 foreach (['ltr', 'rtl'] as $direction) { 237 $oldcss = theme_get_css_filename($themeconfig->name, $themerev, $oldrevision, $direction); 238 if (file_exists($oldcss)) { 239 unlink($oldcss); 240 } 241 } 242 } 243 } 244 245 return $themescss; 246 } 247 248 /** 249 * Invalidate all server and client side caches. 250 * 251 * This method deletes the physical directory that is used to cache the theme 252 * files used for serving. 253 * Because it deletes the main theme cache directory all themes are reset by 254 * this function. 255 */ 256 function theme_reset_all_caches() { 257 global $CFG, $PAGE; 258 require_once("{$CFG->libdir}/filelib.php"); 259 260 $next = theme_get_next_revision(); 261 theme_set_revision($next); 262 263 if (!empty($CFG->themedesignermode)) { 264 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner'); 265 $cache->purge(); 266 } 267 268 // Purge compiled post processed css. 269 cache::make('core', 'postprocessedcss')->purge(); 270 271 // Delete all old theme localcaches. 272 $themecachedirs = glob("{$CFG->localcachedir}/theme/*", GLOB_ONLYDIR); 273 foreach ($themecachedirs as $localcachedir) { 274 fulldelete($localcachedir); 275 } 276 277 if ($PAGE) { 278 $PAGE->reload_theme(); 279 } 280 } 281 282 /** 283 * Reset static caches. 284 * 285 * This method indicates that all running cron processes should exit at the 286 * next opportunity. 287 */ 288 function theme_reset_static_caches() { 289 \core\task\manager::clear_static_caches(); 290 } 291 292 /** 293 * Enable or disable theme designer mode. 294 * 295 * @param bool $state 296 */ 297 function theme_set_designer_mod($state) { 298 set_config('themedesignermode', (int)!empty($state)); 299 // Reset caches after switching mode so that any designer mode caches get purged too. 300 theme_reset_all_caches(); 301 } 302 303 /** 304 * This class represents the configuration variables of a Moodle theme. 305 * 306 * All the variables with access: public below (with a few exceptions that are marked) 307 * are the properties you can set in your themes config.php file. 308 * 309 * There are also some methods and protected variables that are part of the inner 310 * workings of Moodle's themes system. If you are just editing a themes config.php 311 * file, you can just ignore those, and the following information for developers. 312 * 313 * Normally, to create an instance of this class, you should use the 314 * {@link theme_config::load()} factory method to load a themes config.php file. 315 * However, normally you don't need to bother, because moodle_page (that is, $PAGE) 316 * will create one for you, accessible as $PAGE->theme. 317 * 318 * @copyright 2009 Tim Hunt 319 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 320 * @since Moodle 2.0 321 * @package core 322 * @category output 323 */ 324 class theme_config { 325 326 /** 327 * @var string Default theme, used when requested theme not found. 328 */ 329 const DEFAULT_THEME = 'boost'; 330 331 /** The key under which the SCSS file is stored amongst the CSS files. */ 332 const SCSS_KEY = '__SCSS__'; 333 334 /** 335 * @var array You can base your theme on other themes by linking to the other theme as 336 * parents. This lets you use the CSS and layouts from the other themes 337 * (see {@link theme_config::$layouts}). 338 * That makes it easy to create a new theme that is similar to another one 339 * but with a few changes. In this themes CSS you only need to override 340 * those rules you want to change. 341 */ 342 public $parents; 343 344 /** 345 * @var array The names of all the stylesheets from this theme that you would 346 * like included, in order. Give the names of the files without .css. 347 */ 348 public $sheets = array(); 349 350 /** 351 * @var array The names of all the stylesheets from parents that should be excluded. 352 * true value may be used to specify all parents or all themes from one parent. 353 * If no value specified value from parent theme used. 354 */ 355 public $parents_exclude_sheets = null; 356 357 /** 358 * @var array List of plugin sheets to be excluded. 359 * If no value specified value from parent theme used. 360 */ 361 public $plugins_exclude_sheets = null; 362 363 /** 364 * @var array List of style sheets that are included in the text editor bodies. 365 * Sheets from parent themes are used automatically and can not be excluded. 366 */ 367 public $editor_sheets = array(); 368 369 /** 370 * @var bool Whether a fallback version of the stylesheet will be used 371 * whilst the final version is generated. 372 */ 373 public $usefallback = false; 374 375 /** 376 * @var array The names of all the javascript files this theme that you would 377 * like included from head, in order. Give the names of the files without .js. 378 */ 379 public $javascripts = array(); 380 381 /** 382 * @var array The names of all the javascript files this theme that you would 383 * like included from footer, in order. Give the names of the files without .js. 384 */ 385 public $javascripts_footer = array(); 386 387 /** 388 * @var array The names of all the javascript files from parents that should 389 * be excluded. true value may be used to specify all parents or all themes 390 * from one parent. 391 * If no value specified value from parent theme used. 392 */ 393 public $parents_exclude_javascripts = null; 394 395 /** 396 * @var array Which file to use for each page layout. 397 * 398 * This is an array of arrays. The keys of the outer array are the different layouts. 399 * Pages in Moodle are using several different layouts like 'normal', 'course', 'home', 400 * 'popup', 'form', .... The most reliable way to get a complete list is to look at 401 * {@link http://cvs.moodle.org/moodle/theme/base/config.php?view=markup the base theme config.php file}. 402 * That file also has a good example of how to set this setting. 403 * 404 * For each layout, the value in the outer array is an array that describes 405 * how you want that type of page to look. For example 406 * <pre> 407 * $THEME->layouts = array( 408 * // Most pages - if we encounter an unknown or a missing page type, this one is used. 409 * 'standard' => array( 410 * 'theme' = 'mytheme', 411 * 'file' => 'normal.php', 412 * 'regions' => array('side-pre', 'side-post'), 413 * 'defaultregion' => 'side-post' 414 * ), 415 * // The site home page. 416 * 'home' => array( 417 * 'theme' = 'mytheme', 418 * 'file' => 'home.php', 419 * 'regions' => array('side-pre', 'side-post'), 420 * 'defaultregion' => 'side-post' 421 * ), 422 * // ... 423 * ); 424 * </pre> 425 * 426 * 'theme' name of the theme where is the layout located 427 * 'file' is the layout file to use for this type of page. 428 * layout files are stored in layout subfolder 429 * 'regions' This lists the regions on the page where blocks may appear. For 430 * each region you list here, your layout file must include a call to 431 * <pre> 432 * echo $OUTPUT->blocks_for_region($regionname); 433 * </pre> 434 * or equivalent so that the blocks are actually visible. 435 * 436 * 'defaultregion' If the list of regions is non-empty, then you must pick 437 * one of the one of them as 'default'. This has two meanings. First, this is 438 * where new blocks are added. Second, if there are any blocks associated with 439 * the page, but in non-existent regions, they appear here. (Imaging, for example, 440 * that someone added blocks using a different theme that used different region 441 * names, and then switched to this theme.) 442 */ 443 public $layouts = array(); 444 445 /** 446 * @var string Name of the renderer factory class to use. Must implement the 447 * {@link renderer_factory} interface. 448 * 449 * This is an advanced feature. Moodle output is generated by 'renderers', 450 * you can customise the HTML that is output by writing custom renderers, 451 * and then you need to specify 'renderer factory' so that Moodle can find 452 * your renderers. 453 * 454 * There are some renderer factories supplied with Moodle. Please follow these 455 * links to see what they do. 456 * <ul> 457 * <li>{@link standard_renderer_factory} - the default.</li> 458 * <li>{@link theme_overridden_renderer_factory} - use this if you want to write 459 * your own custom renderers in a lib.php file in this theme (or the parent theme).</li> 460 * </ul> 461 */ 462 public $rendererfactory = 'standard_renderer_factory'; 463 464 /** 465 * @var string Function to do custom CSS post-processing. 466 * 467 * This is an advanced feature. If you want to do custom post-processing on the 468 * CSS before it is output (for example, to replace certain variable names 469 * with particular values) you can give the name of a function here. 470 */ 471 public $csspostprocess = null; 472 473 /** 474 * @var string Function to do custom CSS post-processing on a parsed CSS tree. 475 * 476 * This is an advanced feature. If you want to do custom post-processing on the 477 * CSS before it is output, you can provide the name of the function here. The 478 * function will receive a CSS tree document as first parameter, and the theme_config 479 * object as second parameter. A return value is not required, the tree can 480 * be edited in place. 481 */ 482 public $csstreepostprocessor = null; 483 484 /** 485 * @var string Accessibility: Right arrow-like character is 486 * used in the breadcrumb trail, course navigation menu 487 * (previous/next activity), calendar, and search forum block. 488 * If the theme does not set characters, appropriate defaults 489 * are set automatically. Please DO NOT 490 * use < > » - these are confusing for blind users. 491 */ 492 public $rarrow = null; 493 494 /** 495 * @var string Accessibility: Left arrow-like character is 496 * used in the breadcrumb trail, course navigation menu 497 * (previous/next activity), calendar, and search forum block. 498 * If the theme does not set characters, appropriate defaults 499 * are set automatically. Please DO NOT 500 * use < > » - these are confusing for blind users. 501 */ 502 public $larrow = null; 503 504 /** 505 * @var string Accessibility: Up arrow-like character is used in 506 * the book heirarchical navigation. 507 * If the theme does not set characters, appropriate defaults 508 * are set automatically. Please DO NOT 509 * use ^ - this is confusing for blind users. 510 */ 511 public $uarrow = null; 512 513 /** 514 * @var string Accessibility: Down arrow-like character. 515 * If the theme does not set characters, appropriate defaults 516 * are set automatically. 517 */ 518 public $darrow = null; 519 520 /** 521 * @var bool Some themes may want to disable ajax course editing. 522 */ 523 public $enablecourseajax = true; 524 525 /** 526 * @var string Determines served document types 527 * - 'html5' the only officially supported doctype in Moodle 528 * - 'xhtml5' may be used in development for validation (not intended for production servers!) 529 * - 'xhtml' XHTML 1.0 Strict for legacy themes only 530 */ 531 public $doctype = 'html5'; 532 533 /** 534 * @var string requiredblocks If set to a string, will list the block types that cannot be deleted. Defaults to 535 * navigation and settings. 536 */ 537 public $requiredblocks = false; 538 539 //==Following properties are not configurable from theme config.php== 540 541 /** 542 * @var string The name of this theme. Set automatically when this theme is 543 * loaded. This can not be set in theme config.php 544 */ 545 public $name; 546 547 /** 548 * @var string The folder where this themes files are stored. This is set 549 * automatically. This can not be set in theme config.php 550 */ 551 public $dir; 552 553 /** 554 * @var stdClass Theme settings stored in config_plugins table. 555 * This can not be set in theme config.php 556 */ 557 public $settings = null; 558 559 /** 560 * @var bool If set to true and the theme enables the dock then blocks will be able 561 * to be moved to the special dock 562 */ 563 public $enable_dock = false; 564 565 /** 566 * @var bool If set to true then this theme will not be shown in the theme selector unless 567 * theme designer mode is turned on. 568 */ 569 public $hidefromselector = false; 570 571 /** 572 * @var array list of YUI CSS modules to be included on each page. This may be used 573 * to remove cssreset and use cssnormalise module instead. 574 */ 575 public $yuicssmodules = array('cssreset', 'cssfonts', 'cssgrids', 'cssbase'); 576 577 /** 578 * An associative array of block manipulations that should be made if the user is using an rtl language. 579 * The key is the original block region, and the value is the block region to change to. 580 * This is used when displaying blocks for regions only. 581 * @var array 582 */ 583 public $blockrtlmanipulations = array(); 584 585 /** 586 * @var renderer_factory Instance of the renderer_factory implementation 587 * we are using. Implementation detail. 588 */ 589 protected $rf = null; 590 591 /** 592 * @var array List of parent config objects. 593 **/ 594 protected $parent_configs = array(); 595 596 /** 597 * Used to determine whether we can serve SVG images or not. 598 * @var bool 599 */ 600 private $usesvg = null; 601 602 /** 603 * Whether in RTL mode or not. 604 * @var bool 605 */ 606 protected $rtlmode = false; 607 608 /** 609 * The SCSS file to compile (without .scss), located in the scss/ folder of the theme. 610 * Or a Closure, which receives the theme_config as argument and must 611 * return the SCSS content. 612 * @var string|Closure 613 */ 614 public $scss = false; 615 616 /** 617 * Local cache of the SCSS property. 618 * @var false|array 619 */ 620 protected $scsscache = null; 621 622 /** 623 * The name of the function to call to get the SCSS code to inject. 624 * @var string 625 */ 626 public $extrascsscallback = null; 627 628 /** 629 * The name of the function to call to get SCSS to prepend. 630 * @var string 631 */ 632 public $prescsscallback = null; 633 634 /** 635 * Sets the render method that should be used for rendering custom block regions by scripts such as my/index.php 636 * Defaults to {@link core_renderer::blocks_for_region()} 637 * @var string 638 */ 639 public $blockrendermethod = null; 640 641 /** 642 * Remember the results of icon remapping for the current page. 643 * @var array 644 */ 645 public $remapiconcache = []; 646 647 /** 648 * The name of the function to call to get precompiled CSS. 649 * @var string 650 */ 651 public $precompiledcsscallback = null; 652 653 /** 654 * Whether the theme uses course index. 655 * @var bool 656 */ 657 public $usescourseindex = false; 658 659 /** 660 * Configuration for the page activity header 661 * @var array 662 */ 663 public $activityheaderconfig = []; 664 665 /** 666 * For backward compatibility with old themes. 667 * BLOCK_ADDBLOCK_POSITION_DEFAULT, BLOCK_ADDBLOCK_POSITION_FLATNAV. 668 * @var int 669 */ 670 public $addblockposition; 671 672 /** 673 * editor_scss file(s) provided by this theme. 674 * @var array 675 */ 676 public $editor_scss; 677 678 /** 679 * Name of the class extending \core\output\icon_system. 680 * @var string 681 */ 682 public $iconsystem; 683 684 /** 685 * Theme defines its own editing mode switch. 686 * @var bool 687 */ 688 public $haseditswitch = false; 689 690 /** 691 * Allows a theme to customise primary navigation by specifying the list of items to remove. 692 * @var array 693 */ 694 public $removedprimarynavitems = []; 695 696 /** 697 * Load the config.php file for a particular theme, and return an instance 698 * of this class. (That is, this is a factory method.) 699 * 700 * @param string $themename the name of the theme. 701 * @return theme_config an instance of this class. 702 */ 703 public static function load($themename) { 704 global $CFG; 705 706 // load theme settings from db 707 try { 708 $settings = get_config('theme_'.$themename); 709 } catch (dml_exception $e) { 710 // most probably moodle tables not created yet 711 $settings = new stdClass(); 712 } 713 714 if ($config = theme_config::find_theme_config($themename, $settings)) { 715 return new theme_config($config); 716 717 } else if ($themename == theme_config::DEFAULT_THEME) { 718 throw new coding_exception('Default theme '.theme_config::DEFAULT_THEME.' not available or broken!'); 719 720 } else if ($config = theme_config::find_theme_config($CFG->theme, $settings)) { 721 debugging('This page should be using theme ' . $themename . 722 ' which cannot be initialised. Falling back to the site theme ' . $CFG->theme, DEBUG_NORMAL); 723 return new theme_config($config); 724 725 } else { 726 // bad luck, the requested theme has some problems - admin see details in theme config 727 debugging('This page should be using theme ' . $themename . 728 ' which cannot be initialised. Nor can the site theme ' . $CFG->theme . 729 '. Falling back to ' . theme_config::DEFAULT_THEME, DEBUG_NORMAL); 730 return new theme_config(theme_config::find_theme_config(theme_config::DEFAULT_THEME, $settings)); 731 } 732 } 733 734 /** 735 * Theme diagnostic code. It is very problematic to send debug output 736 * to the actual CSS file, instead this functions is supposed to 737 * diagnose given theme and highlights all potential problems. 738 * This information should be available from the theme selection page 739 * or some other debug page for theme designers. 740 * 741 * @param string $themename 742 * @return array description of problems 743 */ 744 public static function diagnose($themename) { 745 //TODO: MDL-21108 746 return array(); 747 } 748 749 /** 750 * Private constructor, can be called only from the factory method. 751 * @param stdClass $config 752 */ 753 private function __construct($config) { 754 global $CFG; //needed for included lib.php files 755 756 $this->settings = $config->settings; 757 $this->name = $config->name; 758 $this->dir = $config->dir; 759 760 if ($this->name != self::DEFAULT_THEME) { 761 $baseconfig = self::find_theme_config(self::DEFAULT_THEME, $this->settings); 762 } else { 763 $baseconfig = $config; 764 } 765 766 // Ensure that each of the configurable properties defined below are also defined at the class level. 767 $configurable = [ 768 'parents', 'sheets', 'parents_exclude_sheets', 'plugins_exclude_sheets', 'usefallback', 769 'javascripts', 'javascripts_footer', 'parents_exclude_javascripts', 770 'layouts', 'enablecourseajax', 'requiredblocks', 771 'rendererfactory', 'csspostprocess', 'editor_sheets', 'editor_scss', 'rarrow', 'larrow', 'uarrow', 'darrow', 772 'hidefromselector', 'doctype', 'yuicssmodules', 'blockrtlmanipulations', 'blockrendermethod', 773 'scss', 'extrascsscallback', 'prescsscallback', 'csstreepostprocessor', 'addblockposition', 774 'iconsystem', 'precompiledcsscallback', 'haseditswitch', 'usescourseindex', 'activityheaderconfig', 775 'removedprimarynavitems', 776 ]; 777 778 foreach ($config as $key=>$value) { 779 if (in_array($key, $configurable)) { 780 $this->$key = $value; 781 } 782 } 783 784 // verify all parents and load configs and renderers 785 foreach ($this->parents as $parent) { 786 if (!$parent_config = theme_config::find_theme_config($parent, $this->settings)) { 787 // this is not good - better exclude faulty parents 788 continue; 789 } 790 $libfile = $parent_config->dir.'/lib.php'; 791 if (is_readable($libfile)) { 792 // theme may store various function here 793 include_once($libfile); 794 } 795 $renderersfile = $parent_config->dir.'/renderers.php'; 796 if (is_readable($renderersfile)) { 797 // may contain core and plugin renderers and renderer factory 798 include_once($renderersfile); 799 } 800 $this->parent_configs[$parent] = $parent_config; 801 } 802 $libfile = $this->dir.'/lib.php'; 803 if (is_readable($libfile)) { 804 // theme may store various function here 805 include_once($libfile); 806 } 807 $rendererfile = $this->dir.'/renderers.php'; 808 if (is_readable($rendererfile)) { 809 // may contain core and plugin renderers and renderer factory 810 include_once($rendererfile); 811 } else { 812 // check if renderers.php file is missnamed renderer.php 813 if (is_readable($this->dir.'/renderer.php')) { 814 debugging('Developer hint: '.$this->dir.'/renderer.php should be renamed to ' . $this->dir."/renderers.php. 815 See: http://docs.moodle.org/dev/Output_renderers#Theme_renderers.", DEBUG_DEVELOPER); 816 } 817 } 818 819 // cascade all layouts properly 820 foreach ($baseconfig->layouts as $layout=>$value) { 821 if (!isset($this->layouts[$layout])) { 822 foreach ($this->parent_configs as $parent_config) { 823 if (isset($parent_config->layouts[$layout])) { 824 $this->layouts[$layout] = $parent_config->layouts[$layout]; 825 continue 2; 826 } 827 } 828 $this->layouts[$layout] = $value; 829 } 830 } 831 832 //fix arrows if needed 833 $this->check_theme_arrows(); 834 } 835 836 /** 837 * Let the theme initialise the page object (usually $PAGE). 838 * 839 * This may be used for example to request jQuery in add-ons. 840 * 841 * @param moodle_page $page 842 */ 843 public function init_page(moodle_page $page) { 844 $themeinitfunction = 'theme_'.$this->name.'_page_init'; 845 if (function_exists($themeinitfunction)) { 846 $themeinitfunction($page); 847 } 848 } 849 850 /** 851 * Checks if arrows $THEME->rarrow, $THEME->larrow, $THEME->uarrow, $THEME->darrow have been set (theme/-/config.php). 852 * If not it applies sensible defaults. 853 * 854 * Accessibility: right and left arrow Unicode characters for breadcrumb, calendar, 855 * search forum block, etc. Important: these are 'silent' in a screen-reader 856 * (unlike > »), and must be accompanied by text. 857 */ 858 private function check_theme_arrows() { 859 if (!isset($this->rarrow) and !isset($this->larrow)) { 860 // Default, looks good in Win XP/IE 6, Win/Firefox 1.5, Win/Netscape 8... 861 // Also OK in Win 9x/2K/IE 5.x 862 $this->rarrow = '►'; 863 $this->larrow = '◄'; 864 $this->uarrow = '▲'; 865 $this->darrow = '▼'; 866 if (empty($_SERVER['HTTP_USER_AGENT'])) { 867 $uagent = ''; 868 } else { 869 $uagent = $_SERVER['HTTP_USER_AGENT']; 870 } 871 if (false !== strpos($uagent, 'Opera') 872 || false !== strpos($uagent, 'Mac')) { 873 // Looks good in Win XP/Mac/Opera 8/9, Mac/Firefox 2, Camino, Safari. 874 // Not broken in Mac/IE 5, Mac/Netscape 7 (?). 875 $this->rarrow = '▶︎'; 876 $this->larrow = '◀︎'; 877 } 878 elseif ((false !== strpos($uagent, 'Konqueror')) 879 || (false !== strpos($uagent, 'Android'))) { 880 // The fonts on Android don't include the characters required for this to work as expected. 881 // So we use the same ones Konqueror uses. 882 $this->rarrow = '→'; 883 $this->larrow = '←'; 884 $this->uarrow = '↑'; 885 $this->darrow = '↓'; 886 } 887 elseif (isset($_SERVER['HTTP_ACCEPT_CHARSET']) 888 && false === stripos($_SERVER['HTTP_ACCEPT_CHARSET'], 'utf-8')) { 889 // (Win/IE 5 doesn't set ACCEPT_CHARSET, but handles Unicode.) 890 // To be safe, non-Unicode browsers! 891 $this->rarrow = '>'; 892 $this->larrow = '<'; 893 $this->uarrow = '^'; 894 $this->darrow = 'v'; 895 } 896 897 // RTL support - in RTL languages, swap r and l arrows 898 if (right_to_left()) { 899 $t = $this->rarrow; 900 $this->rarrow = $this->larrow; 901 $this->larrow = $t; 902 } 903 } 904 } 905 906 /** 907 * Returns output renderer prefixes, these are used when looking 908 * for the overridden renderers in themes. 909 * 910 * @return array 911 */ 912 public function renderer_prefixes() { 913 global $CFG; // just in case the included files need it 914 915 $prefixes = array('theme_'.$this->name); 916 917 foreach ($this->parent_configs as $parent) { 918 $prefixes[] = 'theme_'.$parent->name; 919 } 920 921 return $prefixes; 922 } 923 924 /** 925 * Returns the stylesheet URL of this editor content 926 * 927 * @param bool $encoded false means use & and true use & in URLs 928 * @return moodle_url 929 */ 930 public function editor_css_url($encoded=true) { 931 global $CFG; 932 $rev = theme_get_revision(); 933 $type = 'editor'; 934 if (right_to_left()) { 935 $type .= '-rtl'; 936 } 937 938 if ($rev > -1) { 939 $themesubrevision = theme_get_sub_revision_for_theme($this->name); 940 941 // Provide the sub revision to allow us to invalidate cached theme CSS 942 // on a per theme basis, rather than globally. 943 if ($themesubrevision && $themesubrevision > 0) { 944 $rev .= "_{$themesubrevision}"; 945 } 946 947 $url = new moodle_url("/theme/styles.php"); 948 if (!empty($CFG->slasharguments)) { 949 $url->set_slashargument("/{$this->name}/{$rev}/{$type}", 'noparam', true); 950 } else { 951 $url->params([ 952 'theme' => $this->name, 953 'rev' => $rev, 954 'type' => $type, 955 ]); 956 } 957 } else { 958 $url = new moodle_url('/theme/styles_debug.php', [ 959 'theme' => $this->name, 960 'type' => $type, 961 ]); 962 } 963 return $url; 964 } 965 966 /** 967 * Returns the content of the CSS to be used in editor content 968 * 969 * @return array 970 */ 971 public function editor_css_files() { 972 $files = array(); 973 974 // First editor plugins. 975 $plugins = core_component::get_plugin_list('editor'); 976 foreach ($plugins as $plugin => $fulldir) { 977 $sheetfile = "$fulldir/editor_styles.css"; 978 if (is_readable($sheetfile)) { 979 $files['plugin_'.$plugin] = $sheetfile; 980 } 981 982 $subplugintypes = core_component::get_subplugins("editor_{$plugin}") ?? []; 983 // Fetch sheets for any editor subplugins. 984 foreach ($subplugintypes as $plugintype => $subplugins) { 985 foreach ($subplugins as $subplugin) { 986 $plugindir = core_component::get_plugin_directory($plugintype, $subplugin); 987 $sheetfile = "{$plugindir}/editor_styles.css"; 988 if (is_readable($sheetfile)) { 989 $files["{$plugintype}_{$subplugin}"] = $sheetfile; 990 } 991 } 992 } 993 } 994 995 // Then parent themes - base first, the immediate parent last. 996 foreach (array_reverse($this->parent_configs) as $parent_config) { 997 if (empty($parent_config->editor_sheets)) { 998 continue; 999 } 1000 foreach ($parent_config->editor_sheets as $sheet) { 1001 $sheetfile = "$parent_config->dir/style/$sheet.css"; 1002 if (is_readable($sheetfile)) { 1003 $files['parent_'.$parent_config->name.'_'.$sheet] = $sheetfile; 1004 } 1005 } 1006 } 1007 // Finally this theme. 1008 if (!empty($this->editor_sheets)) { 1009 foreach ($this->editor_sheets as $sheet) { 1010 $sheetfile = "$this->dir/style/$sheet.css"; 1011 if (is_readable($sheetfile)) { 1012 $files['theme_'.$sheet] = $sheetfile; 1013 } 1014 } 1015 } 1016 1017 return $files; 1018 } 1019 1020 /** 1021 * Compiles and returns the content of the SCSS to be used in editor content 1022 * 1023 * @return string Compiled CSS from the editor SCSS 1024 */ 1025 public function editor_scss_to_css() { 1026 $css = ''; 1027 $dir = $this->dir; 1028 $filenames = []; 1029 1030 // Use editor_scss file(s) provided by this theme if set. 1031 if (!empty($this->editor_scss)) { 1032 $filenames = $this->editor_scss; 1033 } else { 1034 // If no editor_scss set, move up theme hierarchy until one is found (if at all). 1035 // This is so child themes only need to set editor_scss if an override is required. 1036 foreach (array_reverse($this->parent_configs) as $parentconfig) { 1037 if (!empty($parentconfig->editor_scss)) { 1038 $dir = $parentconfig->dir; 1039 $filenames = $parentconfig->editor_scss; 1040 1041 // Config found, stop looking. 1042 break; 1043 } 1044 } 1045 } 1046 1047 if (!empty($filenames)) { 1048 $compiler = new core_scss(); 1049 1050 foreach ($filenames as $filename) { 1051 $compiler->set_file("{$dir}/scss/{$filename}.scss"); 1052 1053 try { 1054 $css .= $compiler->to_css(); 1055 } catch (\Exception $e) { 1056 debugging('Error while compiling editor SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER); 1057 } 1058 } 1059 } 1060 1061 return $css; 1062 } 1063 1064 /** 1065 * Get the stylesheet URL of this theme. 1066 * 1067 * @param moodle_page $page Not used... deprecated? 1068 * @return moodle_url[] 1069 */ 1070 public function css_urls(moodle_page $page) { 1071 global $CFG; 1072 1073 $rev = theme_get_revision(); 1074 1075 $urls = array(); 1076 1077 $svg = $this->use_svg_icons(); 1078 $separate = (core_useragent::is_ie() && !core_useragent::check_ie_version('10')); 1079 1080 if ($rev > -1) { 1081 $filename = right_to_left() ? 'all-rtl' : 'all'; 1082 $url = new moodle_url("/theme/styles.php"); 1083 $themesubrevision = theme_get_sub_revision_for_theme($this->name); 1084 1085 // Provide the sub revision to allow us to invalidate cached theme CSS 1086 // on a per theme basis, rather than globally. 1087 if ($themesubrevision && $themesubrevision > 0) { 1088 $rev .= "_{$themesubrevision}"; 1089 } 1090 1091 if (!empty($CFG->slasharguments)) { 1092 $slashargs = ''; 1093 if (!$svg) { 1094 // We add a simple /_s to the start of the path. 1095 // The underscore is used to ensure that it isn't a valid theme name. 1096 $slashargs .= '/_s'.$slashargs; 1097 } 1098 $slashargs .= '/'.$this->name.'/'.$rev.'/'.$filename; 1099 if ($separate) { 1100 $slashargs .= '/chunk0'; 1101 } 1102 $url->set_slashargument($slashargs, 'noparam', true); 1103 } else { 1104 $params = array('theme' => $this->name, 'rev' => $rev, 'type' => $filename); 1105 if (!$svg) { 1106 // We add an SVG param so that we know not to serve SVG images. 1107 // We do this because all modern browsers support SVG and this param will one day be removed. 1108 $params['svg'] = '0'; 1109 } 1110 if ($separate) { 1111 $params['chunk'] = '0'; 1112 } 1113 $url->params($params); 1114 } 1115 $urls[] = $url; 1116 1117 } else { 1118 $baseurl = new moodle_url('/theme/styles_debug.php'); 1119 1120 $css = $this->get_css_files(true); 1121 if (!$svg) { 1122 // We add an SVG param so that we know not to serve SVG images. 1123 // We do this because all modern browsers support SVG and this param will one day be removed. 1124 $baseurl->param('svg', '0'); 1125 } 1126 if (right_to_left()) { 1127 $baseurl->param('rtl', 1); 1128 } 1129 if ($separate) { 1130 // We might need to chunk long files. 1131 $baseurl->param('chunk', '0'); 1132 } 1133 if (core_useragent::is_ie()) { 1134 // Lalala, IE does not allow more than 31 linked CSS files from main document. 1135 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'plugins')); 1136 foreach ($css['parents'] as $parent=>$sheets) { 1137 // We need to serve parents individually otherwise we may easily exceed the style limit IE imposes (4096). 1138 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'ie', 'subtype'=>'parents', 'sheet'=>$parent)); 1139 } 1140 if ($this->get_scss_property()) { 1141 // No need to define the type as IE here. 1142 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss')); 1143 } 1144 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name, 'type'=>'ie', 'subtype'=>'theme')); 1145 1146 } else { 1147 foreach ($css['plugins'] as $plugin=>$unused) { 1148 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'plugin', 'subtype'=>$plugin)); 1149 } 1150 foreach ($css['parents'] as $parent=>$sheets) { 1151 foreach ($sheets as $sheet=>$unused2) { 1152 $urls[] = new moodle_url($baseurl, array('theme'=>$this->name,'type'=>'parent', 'subtype'=>$parent, 'sheet'=>$sheet)); 1153 } 1154 } 1155 foreach ($css['theme'] as $sheet => $filename) { 1156 if ($sheet === self::SCSS_KEY) { 1157 // This is the theme SCSS file. 1158 $urls[] = new moodle_url($baseurl, array('theme' => $this->name, 'type' => 'scss')); 1159 } else { 1160 // Sheet first in order to make long urls easier to read. 1161 $urls[] = new moodle_url($baseurl, array('sheet'=>$sheet, 'theme'=>$this->name, 'type'=>'theme')); 1162 } 1163 } 1164 } 1165 } 1166 1167 // Allow themes to change the css url to something like theme/mytheme/mycss.php. 1168 component_callback('theme_' . $this->name, 'alter_css_urls', [&$urls]); 1169 return $urls; 1170 } 1171 1172 /** 1173 * Get the whole css stylesheet for production mode. 1174 * 1175 * NOTE: this method is not expected to be used from any addons. 1176 * 1177 * @return string CSS markup compressed 1178 */ 1179 public function get_css_content() { 1180 1181 $csscontent = ''; 1182 foreach ($this->get_css_files(false) as $type => $value) { 1183 foreach ($value as $identifier => $val) { 1184 if (is_array($val)) { 1185 foreach ($val as $v) { 1186 $csscontent .= file_get_contents($v) . "\n"; 1187 } 1188 } else { 1189 if ($type === 'theme' && $identifier === self::SCSS_KEY) { 1190 // We need the content from SCSS because this is the SCSS file from the theme. 1191 if ($compiled = $this->get_css_content_from_scss(false)) { 1192 $csscontent .= $compiled; 1193 } else { 1194 // The compiler failed so default back to any precompiled css that might 1195 // exist. 1196 $csscontent .= $this->get_precompiled_css_content(); 1197 } 1198 } else { 1199 $csscontent .= file_get_contents($val) . "\n"; 1200 } 1201 } 1202 } 1203 } 1204 $csscontent = $this->post_process($csscontent); 1205 $csscontent = core_minify::css($csscontent); 1206 1207 return $csscontent; 1208 } 1209 /** 1210 * Set post processed CSS content cache. 1211 * 1212 * @param string $csscontent The post processed CSS content. 1213 * @return bool True if the content was successfully cached. 1214 */ 1215 public function set_css_content_cache($csscontent) { 1216 1217 $cache = cache::make('core', 'postprocessedcss'); 1218 $key = $this->get_css_cache_key(); 1219 1220 return $cache->set($key, $csscontent); 1221 } 1222 1223 /** 1224 * Return whether the post processed CSS content has been cached. 1225 * 1226 * @return bool Whether the post-processed CSS is available in the cache. 1227 */ 1228 public function has_css_cached_content() { 1229 1230 $key = $this->get_css_cache_key(); 1231 $cache = cache::make('core', 'postprocessedcss'); 1232 1233 return $cache->has($key); 1234 } 1235 1236 /** 1237 * Return cached post processed CSS content. 1238 * 1239 * @return bool|string The cached css content or false if not found. 1240 */ 1241 public function get_css_cached_content() { 1242 1243 $key = $this->get_css_cache_key(); 1244 $cache = cache::make('core', 'postprocessedcss'); 1245 1246 return $cache->get($key); 1247 } 1248 1249 /** 1250 * Generate the css content cache key. 1251 * 1252 * @return string The post processed css cache key. 1253 */ 1254 public function get_css_cache_key() { 1255 $nosvg = (!$this->use_svg_icons()) ? 'nosvg_' : ''; 1256 $rtlmode = ($this->rtlmode == true) ? 'rtl' : 'ltr'; 1257 1258 return $nosvg . $this->name . '_' . $rtlmode; 1259 } 1260 1261 /** 1262 * Get the theme designer css markup, 1263 * the parameters are coming from css_urls(). 1264 * 1265 * NOTE: this method is not expected to be used from any addons. 1266 * 1267 * @param string $type 1268 * @param string $subtype 1269 * @param string $sheet 1270 * @return string CSS markup 1271 */ 1272 public function get_css_content_debug($type, $subtype, $sheet) { 1273 if ($type === 'scss') { 1274 // The SCSS file of the theme is requested. 1275 $csscontent = $this->get_css_content_from_scss(true); 1276 if ($csscontent !== false) { 1277 return $this->post_process($csscontent); 1278 } 1279 return ''; 1280 } 1281 1282 $cssfiles = array(); 1283 $css = $this->get_css_files(true); 1284 1285 if ($type === 'ie') { 1286 // IE is a sloppy browser with weird limits, sorry. 1287 if ($subtype === 'plugins') { 1288 $cssfiles = $css['plugins']; 1289 1290 } else if ($subtype === 'parents') { 1291 if (empty($sheet)) { 1292 // Do not bother with the empty parent here. 1293 } else { 1294 // Build up the CSS for that parent so we can serve it as one file. 1295 foreach ($css[$subtype][$sheet] as $parent => $css) { 1296 $cssfiles[] = $css; 1297 } 1298 } 1299 } else if ($subtype === 'theme') { 1300 $cssfiles = $css['theme']; 1301 foreach ($cssfiles as $key => $value) { 1302 if (in_array($key, [self::SCSS_KEY])) { 1303 // Remove the SCSS file from the theme CSS files. 1304 // The SCSS files use the type 'scss', not 'ie'. 1305 unset($cssfiles[$key]); 1306 } 1307 } 1308 } 1309 1310 } else if ($type === 'plugin') { 1311 if (isset($css['plugins'][$subtype])) { 1312 $cssfiles[] = $css['plugins'][$subtype]; 1313 } 1314 1315 } else if ($type === 'parent') { 1316 if (isset($css['parents'][$subtype][$sheet])) { 1317 $cssfiles[] = $css['parents'][$subtype][$sheet]; 1318 } 1319 1320 } else if ($type === 'theme') { 1321 if (isset($css['theme'][$sheet])) { 1322 $cssfiles[] = $css['theme'][$sheet]; 1323 } 1324 } 1325 1326 $csscontent = ''; 1327 foreach ($cssfiles as $file) { 1328 $contents = file_get_contents($file); 1329 $contents = $this->post_process($contents); 1330 $comment = "/** Path: $type $subtype $sheet.' **/\n"; 1331 $stats = ''; 1332 $csscontent .= $comment.$stats.$contents."\n\n"; 1333 } 1334 1335 return $csscontent; 1336 } 1337 1338 /** 1339 * Get the whole css stylesheet for editor iframe. 1340 * 1341 * NOTE: this method is not expected to be used from any addons. 1342 * 1343 * @return string CSS markup 1344 */ 1345 public function get_css_content_editor() { 1346 $css = ''; 1347 $cssfiles = $this->editor_css_files(); 1348 1349 // If editor has static CSS, include it. 1350 foreach ($cssfiles as $file) { 1351 $css .= file_get_contents($file)."\n"; 1352 } 1353 1354 // If editor has SCSS, compile and include it. 1355 if (($convertedscss = $this->editor_scss_to_css())) { 1356 $css .= $convertedscss; 1357 } 1358 1359 $output = $this->post_process($css); 1360 1361 return $output; 1362 } 1363 1364 /** 1365 * Returns an array of organised CSS files required for this output. 1366 * 1367 * @param bool $themedesigner 1368 * @return array nested array of file paths 1369 */ 1370 protected function get_css_files($themedesigner) { 1371 global $CFG; 1372 1373 $cache = null; 1374 $cachekey = 'cssfiles'; 1375 if ($themedesigner) { 1376 require_once($CFG->dirroot.'/lib/csslib.php'); 1377 // We need some kind of caching here because otherwise the page navigation becomes 1378 // way too slow in theme designer mode. Feel free to create full cache definition later... 1379 $cache = cache::make_from_params(cache_store::MODE_APPLICATION, 'core', 'themedesigner', array('theme' => $this->name)); 1380 if ($files = $cache->get($cachekey)) { 1381 if ($files['created'] > time() - THEME_DESIGNER_CACHE_LIFETIME) { 1382 unset($files['created']); 1383 return $files; 1384 } 1385 } 1386 } 1387 1388 $cssfiles = array('plugins'=>array(), 'parents'=>array(), 'theme'=>array()); 1389 1390 // Get all plugin sheets. 1391 $excludes = $this->resolve_excludes('plugins_exclude_sheets'); 1392 if ($excludes !== true) { 1393 foreach (core_component::get_plugin_types() as $type=>$unused) { 1394 if ($type === 'theme' || (!empty($excludes[$type]) and $excludes[$type] === true)) { 1395 continue; 1396 } 1397 $plugins = core_component::get_plugin_list($type); 1398 foreach ($plugins as $plugin=>$fulldir) { 1399 if (!empty($excludes[$type]) and is_array($excludes[$type]) 1400 and in_array($plugin, $excludes[$type])) { 1401 continue; 1402 } 1403 1404 // Get the CSS from the plugin. 1405 $sheetfile = "$fulldir/styles.css"; 1406 if (is_readable($sheetfile)) { 1407 $cssfiles['plugins'][$type.'_'.$plugin] = $sheetfile; 1408 } 1409 1410 // Create a list of candidate sheets from parents (direct parent last) and current theme. 1411 $candidates = array(); 1412 foreach (array_reverse($this->parent_configs) as $parent_config) { 1413 $candidates[] = $parent_config->name; 1414 } 1415 $candidates[] = $this->name; 1416 1417 // Add the sheets found. 1418 foreach ($candidates as $candidate) { 1419 $sheetthemefile = "$fulldir/styles_{$candidate}.css"; 1420 if (is_readable($sheetthemefile)) { 1421 $cssfiles['plugins'][$type.'_'.$plugin.'_'.$candidate] = $sheetthemefile; 1422 } 1423 } 1424 } 1425 } 1426 } 1427 1428 // Find out wanted parent sheets. 1429 $excludes = $this->resolve_excludes('parents_exclude_sheets'); 1430 if ($excludes !== true) { 1431 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last. 1432 $parent = $parent_config->name; 1433 if (empty($parent_config->sheets) || (!empty($excludes[$parent]) and $excludes[$parent] === true)) { 1434 continue; 1435 } 1436 foreach ($parent_config->sheets as $sheet) { 1437 if (!empty($excludes[$parent]) && is_array($excludes[$parent]) 1438 && in_array($sheet, $excludes[$parent])) { 1439 continue; 1440 } 1441 1442 // We never refer to the parent LESS files. 1443 $sheetfile = "$parent_config->dir/style/$sheet.css"; 1444 if (is_readable($sheetfile)) { 1445 $cssfiles['parents'][$parent][$sheet] = $sheetfile; 1446 } 1447 } 1448 } 1449 } 1450 1451 1452 // Current theme sheets. 1453 // We first add the SCSS file because we want the CSS ones to 1454 // be included after the SCSS code. 1455 if ($this->get_scss_property()) { 1456 $cssfiles['theme'][self::SCSS_KEY] = true; 1457 } 1458 if (is_array($this->sheets)) { 1459 foreach ($this->sheets as $sheet) { 1460 $sheetfile = "$this->dir/style/$sheet.css"; 1461 if (is_readable($sheetfile) && !isset($cssfiles['theme'][$sheet])) { 1462 $cssfiles['theme'][$sheet] = $sheetfile; 1463 } 1464 } 1465 } 1466 1467 if ($cache) { 1468 $files = $cssfiles; 1469 $files['created'] = time(); 1470 $cache->set($cachekey, $files); 1471 } 1472 return $cssfiles; 1473 } 1474 1475 /** 1476 * Return the CSS content generated from the SCSS file. 1477 * 1478 * @param bool $themedesigner True if theme designer is enabled. 1479 * @return bool|string Return false when the compilation failed. Else the compiled string. 1480 */ 1481 protected function get_css_content_from_scss($themedesigner) { 1482 global $CFG; 1483 1484 list($paths, $scss) = $this->get_scss_property(); 1485 if (!$scss) { 1486 throw new coding_exception('The theme did not define a SCSS file, or it is not readable.'); 1487 } 1488 1489 // We might need more memory/time to do this, so let's play safe. 1490 raise_memory_limit(MEMORY_EXTRA); 1491 core_php_time_limit::raise(300); 1492 1493 // TODO: MDL-62757 When changing anything in this method please do not forget to check 1494 // if the validate() method in class admin_setting_configthemepreset needs updating too. 1495 1496 $cachedir = make_localcache_directory('scsscache-' . $this->name, false); 1497 $cacheoptions = []; 1498 if ($themedesigner) { 1499 $cacheoptions = array( 1500 'cacheDir' => $cachedir, 1501 'prefix' => 'scssphp_', 1502 'forceRefresh' => false, 1503 ); 1504 } else { 1505 if (file_exists($cachedir)) { 1506 remove_dir($cachedir); 1507 } 1508 } 1509 1510 // Set-up the compiler. 1511 $compiler = new core_scss($cacheoptions); 1512 1513 if ($this->supports_source_maps($themedesigner)) { 1514 // Enable source maps. 1515 $compiler->setSourceMapOptions([ 1516 'sourceMapBasepath' => str_replace('\\', '/', $CFG->dirroot), 1517 'sourceMapRootpath' => $CFG->wwwroot . '/' 1518 ]); 1519 $compiler->setSourceMap($compiler::SOURCE_MAP_INLINE); 1520 } 1521 1522 $compiler->prepend_raw_scss($this->get_pre_scss_code()); 1523 if (is_string($scss)) { 1524 $compiler->set_file($scss); 1525 } else { 1526 $compiler->append_raw_scss($scss($this)); 1527 $compiler->setImportPaths($paths); 1528 } 1529 $compiler->append_raw_scss($this->get_extra_scss_code()); 1530 1531 try { 1532 // Compile! 1533 $compiled = $compiler->to_css(); 1534 1535 } catch (\Exception $e) { 1536 $compiled = false; 1537 debugging('Error while compiling SCSS: ' . $e->getMessage(), DEBUG_DEVELOPER); 1538 } 1539 1540 // Try to save memory. 1541 $compiler = null; 1542 unset($compiler); 1543 1544 return $compiled; 1545 } 1546 1547 /** 1548 * Return the precompiled CSS if the precompiledcsscallback exists. 1549 * 1550 * @return string Return compiled css. 1551 */ 1552 public function get_precompiled_css_content() { 1553 $configs = array_reverse($this->parent_configs) + [$this]; 1554 $css = ''; 1555 1556 foreach ($configs as $config) { 1557 if (isset($config->precompiledcsscallback)) { 1558 $function = $config->precompiledcsscallback; 1559 if (function_exists($function)) { 1560 $css .= $function($this); 1561 } 1562 } 1563 } 1564 return $css; 1565 } 1566 1567 /** 1568 * Get the icon system to use. 1569 * 1570 * @return string 1571 */ 1572 public function get_icon_system() { 1573 1574 // Getting all the candidate functions. 1575 $system = false; 1576 if (isset($this->iconsystem) && \core\output\icon_system::is_valid_system($this->iconsystem)) { 1577 return $this->iconsystem; 1578 } 1579 foreach ($this->parent_configs as $parent_config) { 1580 if (isset($parent_config->iconsystem) && \core\output\icon_system::is_valid_system($parent_config->iconsystem)) { 1581 return $parent_config->iconsystem; 1582 } 1583 } 1584 return \core\output\icon_system::STANDARD; 1585 } 1586 1587 /** 1588 * Return extra SCSS code to add when compiling. 1589 * 1590 * This is intended to be used by themes to inject some SCSS code 1591 * before it gets compiled. If you want to inject variables you 1592 * should use {@link self::get_scss_variables()}. 1593 * 1594 * @return string The SCSS code to inject. 1595 */ 1596 public function get_extra_scss_code() { 1597 $content = ''; 1598 1599 // Getting all the candidate functions. 1600 $candidates = array(); 1601 foreach (array_reverse($this->parent_configs) as $parent_config) { 1602 if (!isset($parent_config->extrascsscallback)) { 1603 continue; 1604 } 1605 $candidates[] = $parent_config->extrascsscallback; 1606 } 1607 1608 if (isset($this->extrascsscallback)) { 1609 $candidates[] = $this->extrascsscallback; 1610 } 1611 1612 // Calling the functions. 1613 foreach ($candidates as $function) { 1614 if (function_exists($function)) { 1615 $content .= "\n/** Extra SCSS from $function **/\n" . $function($this) . "\n"; 1616 } 1617 } 1618 1619 return $content; 1620 } 1621 1622 /** 1623 * SCSS code to prepend when compiling. 1624 * 1625 * This is intended to be used by themes to inject SCSS code before it gets compiled. 1626 * 1627 * @return string The SCSS code to inject. 1628 */ 1629 public function get_pre_scss_code() { 1630 $content = ''; 1631 1632 // Getting all the candidate functions. 1633 $candidates = array(); 1634 foreach (array_reverse($this->parent_configs) as $parent_config) { 1635 if (!isset($parent_config->prescsscallback)) { 1636 continue; 1637 } 1638 $candidates[] = $parent_config->prescsscallback; 1639 } 1640 1641 if (isset($this->prescsscallback)) { 1642 $candidates[] = $this->prescsscallback; 1643 } 1644 1645 // Calling the functions. 1646 foreach ($candidates as $function) { 1647 if (function_exists($function)) { 1648 $content .= "\n/** Pre-SCSS from $function **/\n" . $function($this) . "\n"; 1649 } 1650 } 1651 1652 return $content; 1653 } 1654 1655 /** 1656 * Get the SCSS property. 1657 * 1658 * This resolves whether a SCSS file (or content) has to be used when generating 1659 * the stylesheet for the theme. It will look at parents themes and check the 1660 * SCSS properties there. 1661 * 1662 * @return False when SCSS is not used. 1663 * An array with the import paths, and the path to the SCSS file or Closure as second. 1664 */ 1665 public function get_scss_property() { 1666 if ($this->scsscache === null) { 1667 $configs = [$this] + $this->parent_configs; 1668 $scss = null; 1669 1670 foreach ($configs as $config) { 1671 $path = "{$config->dir}/scss"; 1672 1673 // We collect the SCSS property until we've found one. 1674 if (empty($scss) && !empty($config->scss)) { 1675 $candidate = is_string($config->scss) ? "{$path}/{$config->scss}.scss" : $config->scss; 1676 if ($candidate instanceof Closure) { 1677 $scss = $candidate; 1678 } else if (is_string($candidate) && is_readable($candidate)) { 1679 $scss = $candidate; 1680 } 1681 } 1682 1683 // We collect the import paths once we've found a SCSS property. 1684 if ($scss && is_dir($path)) { 1685 $paths[] = $path; 1686 } 1687 1688 } 1689 1690 $this->scsscache = $scss !== null ? [$paths, $scss] : false; 1691 } 1692 1693 return $this->scsscache; 1694 } 1695 1696 /** 1697 * Generate a URL to the file that serves theme JavaScript files. 1698 * 1699 * If we determine that the theme has no relevant files, then we return 1700 * early with a null value. 1701 * 1702 * @param bool $inhead true means head url, false means footer 1703 * @return moodle_url|null 1704 */ 1705 public function javascript_url($inhead) { 1706 global $CFG; 1707 1708 $rev = theme_get_revision(); 1709 $params = array('theme'=>$this->name,'rev'=>$rev); 1710 $params['type'] = $inhead ? 'head' : 'footer'; 1711 1712 // Return early if there are no files to serve 1713 if (count($this->javascript_files($params['type'])) === 0) { 1714 return null; 1715 } 1716 1717 if (!empty($CFG->slasharguments) and $rev > 0) { 1718 $url = new moodle_url("/theme/javascript.php"); 1719 $url->set_slashargument('/'.$this->name.'/'.$rev.'/'.$params['type'], 'noparam', true); 1720 return $url; 1721 } else { 1722 return new moodle_url('/theme/javascript.php', $params); 1723 } 1724 } 1725 1726 /** 1727 * Get the URL's for the JavaScript files used by this theme. 1728 * They won't be served directly, instead they'll be mediated through 1729 * theme/javascript.php. 1730 * 1731 * @param string $type Either javascripts_footer, or javascripts 1732 * @return array 1733 */ 1734 public function javascript_files($type) { 1735 if ($type === 'footer') { 1736 $type = 'javascripts_footer'; 1737 } else { 1738 $type = 'javascripts'; 1739 } 1740 1741 $js = array(); 1742 // find out wanted parent javascripts 1743 $excludes = $this->resolve_excludes('parents_exclude_javascripts'); 1744 if ($excludes !== true) { 1745 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last 1746 $parent = $parent_config->name; 1747 if (empty($parent_config->$type)) { 1748 continue; 1749 } 1750 if (!empty($excludes[$parent]) and $excludes[$parent] === true) { 1751 continue; 1752 } 1753 foreach ($parent_config->$type as $javascript) { 1754 if (!empty($excludes[$parent]) and is_array($excludes[$parent]) 1755 and in_array($javascript, $excludes[$parent])) { 1756 continue; 1757 } 1758 $javascriptfile = "$parent_config->dir/javascript/$javascript.js"; 1759 if (is_readable($javascriptfile)) { 1760 $js[] = $javascriptfile; 1761 } 1762 } 1763 } 1764 } 1765 1766 // current theme javascripts 1767 if (is_array($this->$type)) { 1768 foreach ($this->$type as $javascript) { 1769 $javascriptfile = "$this->dir/javascript/$javascript.js"; 1770 if (is_readable($javascriptfile)) { 1771 $js[] = $javascriptfile; 1772 } 1773 } 1774 } 1775 return $js; 1776 } 1777 1778 /** 1779 * Resolves an exclude setting to the themes setting is applicable or the 1780 * setting of its closest parent. 1781 * 1782 * @param string $variable The name of the setting the exclude setting to resolve 1783 * @param string $default 1784 * @return mixed 1785 */ 1786 protected function resolve_excludes($variable, $default = null) { 1787 $setting = $default; 1788 if (is_array($this->{$variable}) or $this->{$variable} === true) { 1789 $setting = $this->{$variable}; 1790 } else { 1791 foreach ($this->parent_configs as $parent_config) { // the immediate parent first, base last 1792 if (!isset($parent_config->{$variable})) { 1793 continue; 1794 } 1795 if (is_array($parent_config->{$variable}) or $parent_config->{$variable} === true) { 1796 $setting = $parent_config->{$variable}; 1797 break; 1798 } 1799 } 1800 } 1801 return $setting; 1802 } 1803 1804 /** 1805 * Returns the content of the one huge javascript file merged from all theme javascript files. 1806 * 1807 * @param bool $type 1808 * @return string 1809 */ 1810 public function javascript_content($type) { 1811 $jsfiles = $this->javascript_files($type); 1812 $js = ''; 1813 foreach ($jsfiles as $jsfile) { 1814 $js .= file_get_contents($jsfile)."\n"; 1815 } 1816 return $js; 1817 } 1818 1819 /** 1820 * Post processes CSS. 1821 * 1822 * This method post processes all of the CSS before it is served for this theme. 1823 * This is done so that things such as image URL's can be swapped in and to 1824 * run any specific CSS post process method the theme has requested. 1825 * This allows themes to use CSS settings. 1826 * 1827 * @param string $css The CSS to process. 1828 * @return string The processed CSS. 1829 */ 1830 public function post_process($css) { 1831 // now resolve all image locations 1832 if (preg_match_all('/\[\[pix:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) { 1833 $replaced = array(); 1834 foreach ($matches as $match) { 1835 if (isset($replaced[$match[0]])) { 1836 continue; 1837 } 1838 $replaced[$match[0]] = true; 1839 $imagename = $match[2]; 1840 $component = rtrim($match[1], '|'); 1841 $imageurl = $this->image_url($imagename, $component)->out(false); 1842 // we do not need full url because the image.php is always in the same dir 1843 $imageurl = preg_replace('|^http.?://[^/]+|', '', $imageurl); 1844 $css = str_replace($match[0], $imageurl, $css); 1845 } 1846 } 1847 1848 // Now resolve all font locations. 1849 if (preg_match_all('/\[\[font:([a-z0-9_]+\|)?([^\]]+)\]\]/', $css, $matches, PREG_SET_ORDER)) { 1850 $replaced = array(); 1851 foreach ($matches as $match) { 1852 if (isset($replaced[$match[0]])) { 1853 continue; 1854 } 1855 $replaced[$match[0]] = true; 1856 $fontname = $match[2]; 1857 $component = rtrim($match[1], '|'); 1858 $fonturl = $this->font_url($fontname, $component)->out(false); 1859 // We do not need full url because the font.php is always in the same dir. 1860 $fonturl = preg_replace('|^http.?://[^/]+|', '', $fonturl); 1861 $css = str_replace($match[0], $fonturl, $css); 1862 } 1863 } 1864 1865 // Now resolve all theme settings or do any other postprocessing. 1866 // This needs to be done before calling core parser, since the parser strips [[settings]] tags. 1867 $csspostprocess = $this->csspostprocess; 1868 if ($csspostprocess && function_exists($csspostprocess)) { 1869 $css = $csspostprocess($css, $this); 1870 } 1871 1872 // Post processing using an object representation of CSS. 1873 $treeprocessor = $this->get_css_tree_post_processor(); 1874 $needsparsing = !empty($treeprocessor) || !empty($this->rtlmode); 1875 if ($needsparsing) { 1876 1877 // We might need more memory/time to do this, so let's play safe. 1878 raise_memory_limit(MEMORY_EXTRA); 1879 core_php_time_limit::raise(300); 1880 1881 $parser = new core_cssparser($css); 1882 $csstree = $parser->parse(); 1883 unset($parser); 1884 1885 if ($this->rtlmode) { 1886 $this->rtlize($csstree); 1887 } 1888 1889 if ($treeprocessor) { 1890 $treeprocessor($csstree, $this); 1891 } 1892 1893 $css = $csstree->render(); 1894 unset($csstree); 1895 } 1896 1897 return $css; 1898 } 1899 1900 /** 1901 * Flip a stylesheet to RTL. 1902 * 1903 * @param Object $csstree The parsed CSS tree structure to flip. 1904 * @return void 1905 */ 1906 protected function rtlize($csstree) { 1907 $rtlcss = new core_rtlcss($csstree); 1908 $rtlcss->flip(); 1909 } 1910 1911 /** 1912 * Return the direct URL for an image from the pix folder. 1913 * 1914 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template. 1915 * 1916 * @deprecated since Moodle 3.3 1917 * @param string $imagename the name of the icon. 1918 * @param string $component specification of one plugin like in get_string() 1919 * @return moodle_url 1920 */ 1921 public function pix_url($imagename, $component) { 1922 debugging('pix_url is deprecated. Use image_url for images and pix_icon for icons.', DEBUG_DEVELOPER); 1923 return $this->image_url($imagename, $component); 1924 } 1925 1926 /** 1927 * Return the direct URL for an image from the pix folder. 1928 * 1929 * Use this function sparingly and never for icons. For icons use pix_icon or the pix helper in a mustache template. 1930 * 1931 * @param string $imagename the name of the icon. 1932 * @param string $component specification of one plugin like in get_string() 1933 * @return moodle_url 1934 */ 1935 public function image_url($imagename, $component) { 1936 global $CFG; 1937 1938 $params = array('theme'=>$this->name); 1939 $svg = $this->use_svg_icons(); 1940 1941 if (empty($component) or $component === 'moodle' or $component === 'core') { 1942 $params['component'] = 'core'; 1943 } else { 1944 $params['component'] = $component; 1945 } 1946 1947 $rev = theme_get_revision(); 1948 if ($rev != -1) { 1949 $params['rev'] = $rev; 1950 } 1951 1952 $params['image'] = $imagename; 1953 1954 $url = new moodle_url("/theme/image.php"); 1955 if (!empty($CFG->slasharguments) and $rev > 0) { 1956 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['image']; 1957 if (!$svg) { 1958 // We add a simple /_s to the start of the path. 1959 // The underscore is used to ensure that it isn't a valid theme name. 1960 $path = '/_s'.$path; 1961 } 1962 $url->set_slashargument($path, 'noparam', true); 1963 } else { 1964 if (!$svg) { 1965 // We add an SVG param so that we know not to serve SVG images. 1966 // We do this because all modern browsers support SVG and this param will one day be removed. 1967 $params['svg'] = '0'; 1968 } 1969 $url->params($params); 1970 } 1971 1972 return $url; 1973 } 1974 1975 /** 1976 * Return the URL for a font 1977 * 1978 * @param string $font the name of the font (including extension). 1979 * @param string $component specification of one plugin like in get_string() 1980 * @return moodle_url 1981 */ 1982 public function font_url($font, $component) { 1983 global $CFG; 1984 1985 $params = array('theme'=>$this->name); 1986 1987 if (empty($component) or $component === 'moodle' or $component === 'core') { 1988 $params['component'] = 'core'; 1989 } else { 1990 $params['component'] = $component; 1991 } 1992 1993 $rev = theme_get_revision(); 1994 if ($rev != -1) { 1995 $params['rev'] = $rev; 1996 } 1997 1998 $params['font'] = $font; 1999 2000 $url = new moodle_url("/theme/font.php"); 2001 if (!empty($CFG->slasharguments) and $rev > 0) { 2002 $path = '/'.$params['theme'].'/'.$params['component'].'/'.$params['rev'].'/'.$params['font']; 2003 $url->set_slashargument($path, 'noparam', true); 2004 } else { 2005 $url->params($params); 2006 } 2007 2008 return $url; 2009 } 2010 2011 /** 2012 * Returns URL to the stored file via pluginfile.php. 2013 * 2014 * Note the theme must also implement pluginfile.php handler, 2015 * theme revision is used instead of the itemid. 2016 * 2017 * @param string $setting 2018 * @param string $filearea 2019 * @return string protocol relative URL or null if not present 2020 */ 2021 public function setting_file_url($setting, $filearea) { 2022 global $CFG; 2023 2024 if (empty($this->settings->$setting)) { 2025 return null; 2026 } 2027 2028 $component = 'theme_'.$this->name; 2029 $itemid = theme_get_revision(); 2030 $filepath = $this->settings->$setting; 2031 $syscontext = context_system::instance(); 2032 2033 $url = moodle_url::make_file_url("$CFG->wwwroot/pluginfile.php", "/$syscontext->id/$component/$filearea/$itemid".$filepath); 2034 2035 // Now this is tricky because the we can not hardcode http or https here, lets use the relative link. 2036 // Note: unfortunately moodle_url does not support //urls yet. 2037 2038 $url = preg_replace('|^https?://|i', '//', $url->out(false)); 2039 2040 return $url; 2041 } 2042 2043 /** 2044 * Serve the theme setting file. 2045 * 2046 * @param string $filearea 2047 * @param array $args 2048 * @param bool $forcedownload 2049 * @param array $options 2050 * @return bool may terminate if file not found or donotdie not specified 2051 */ 2052 public function setting_file_serve($filearea, $args, $forcedownload, $options) { 2053 global $CFG; 2054 require_once("$CFG->libdir/filelib.php"); 2055 2056 $syscontext = context_system::instance(); 2057 $component = 'theme_'.$this->name; 2058 2059 $revision = array_shift($args); 2060 if ($revision < 0) { 2061 $lifetime = 0; 2062 } else { 2063 $lifetime = 60*60*24*60; 2064 // By default, theme files must be cache-able by both browsers and proxies. 2065 if (!array_key_exists('cacheability', $options)) { 2066 $options['cacheability'] = 'public'; 2067 } 2068 } 2069 2070 $fs = get_file_storage(); 2071 $relativepath = implode('/', $args); 2072 2073 $fullpath = "/{$syscontext->id}/{$component}/{$filearea}/0/{$relativepath}"; 2074 $fullpath = rtrim($fullpath, '/'); 2075 if ($file = $fs->get_file_by_hash(sha1($fullpath))) { 2076 send_stored_file($file, $lifetime, 0, $forcedownload, $options); 2077 return true; 2078 } else { 2079 send_file_not_found(); 2080 } 2081 } 2082 2083 /** 2084 * Resolves the real image location. 2085 * 2086 * $svg was introduced as an arg in 2.4. It is important because not all supported browsers support the use of SVG 2087 * and we need a way in which to turn it off. 2088 * By default SVG won't be used unless asked for. This is done for two reasons: 2089 * 1. It ensures that we don't serve svg images unless we really want to. The admin has selected to force them, of the users 2090 * browser supports SVG. 2091 * 2. We only serve SVG images from locations we trust. This must NOT include any areas where the image may have been uploaded 2092 * by the user due to security concerns. 2093 * 2094 * @param string $image name of image, may contain relative path 2095 * @param string $component 2096 * @param bool $svg|null Should SVG images also be looked for? If null, falls back to auto-detection of browser support 2097 * @return string full file path 2098 */ 2099 public function resolve_image_location($image, $component, $svg = false) { 2100 global $CFG; 2101 2102 if (!is_bool($svg)) { 2103 // If $svg isn't a bool then we need to decide for ourselves. 2104 $svg = $this->use_svg_icons(); 2105 } 2106 2107 if ($component === 'moodle' or $component === 'core' or empty($component)) { 2108 if ($imagefile = $this->image_exists("$this->dir/pix_core/$image", $svg)) { 2109 return $imagefile; 2110 } 2111 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last 2112 if ($imagefile = $this->image_exists("$parent_config->dir/pix_core/$image", $svg)) { 2113 return $imagefile; 2114 } 2115 } 2116 if ($imagefile = $this->image_exists("$CFG->dataroot/pix/$image", $svg)) { 2117 return $imagefile; 2118 } 2119 if ($imagefile = $this->image_exists("$CFG->dirroot/pix/$image", $svg)) { 2120 return $imagefile; 2121 } 2122 return null; 2123 2124 } else if ($component === 'theme') { //exception 2125 if ($image === 'favicon') { 2126 return "$this->dir/pix/favicon.ico"; 2127 } 2128 if ($imagefile = $this->image_exists("$this->dir/pix/$image", $svg)) { 2129 return $imagefile; 2130 } 2131 foreach (array_reverse($this->parent_configs) as $parent_config) { // base first, the immediate parent last 2132 if ($imagefile = $this->image_exists("$parent_config->dir/pix/$image", $svg)) { 2133 return $imagefile; 2134 } 2135 } 2136 return null; 2137 2138 } else { 2139 if (strpos($component, '_') === false) { 2140 $component = "mod_{$component}"; 2141 } 2142 list($type, $plugin) = explode('_', $component, 2); 2143 2144 // In Moodle 4.0 we introduced a new image format. 2145 // Support that image format here. 2146 $candidates = [$image]; 2147 2148 if ($type === 'mod') { 2149 if ($image === 'icon' || $image === 'monologo') { 2150 $candidates = ['monologo', 'icon']; 2151 if ($image === 'icon') { 2152 debugging( 2153 "The 'icon' image for activity modules has been replaced with a new 'monologo'. " . 2154 "Please update your calling code to fetch the new icon where possible. " . 2155 "Called for component {$component}.", 2156 DEBUG_DEVELOPER 2157 ); 2158 } 2159 } 2160 } 2161 foreach ($candidates as $image) { 2162 if ($imagefile = $this->image_exists("$this->dir/pix_plugins/$type/$plugin/$image", $svg)) { 2163 return $imagefile; 2164 } 2165 2166 // Base first, the immediate parent last. 2167 foreach (array_reverse($this->parent_configs) as $parentconfig) { 2168 if ($imagefile = $this->image_exists("$parentconfig->dir/pix_plugins/$type/$plugin/$image", $svg)) { 2169 return $imagefile; 2170 } 2171 } 2172 if ($imagefile = $this->image_exists("$CFG->dataroot/pix_plugins/$type/$plugin/$image", $svg)) { 2173 return $imagefile; 2174 } 2175 $dir = core_component::get_plugin_directory($type, $plugin); 2176 if ($imagefile = $this->image_exists("$dir/pix/$image", $svg)) { 2177 return $imagefile; 2178 } 2179 } 2180 return null; 2181 } 2182 } 2183 2184 /** 2185 * Resolves the real font location. 2186 * 2187 * @param string $font name of font file 2188 * @param string $component 2189 * @return string full file path 2190 */ 2191 public function resolve_font_location($font, $component) { 2192 global $CFG; 2193 2194 if ($component === 'moodle' or $component === 'core' or empty($component)) { 2195 if (file_exists("$this->dir/fonts_core/$font")) { 2196 return "$this->dir/fonts_core/$font"; 2197 } 2198 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last. 2199 if (file_exists("$parent_config->dir/fonts_core/$font")) { 2200 return "$parent_config->dir/fonts_core/$font"; 2201 } 2202 } 2203 if (file_exists("$CFG->dataroot/fonts/$font")) { 2204 return "$CFG->dataroot/fonts/$font"; 2205 } 2206 if (file_exists("$CFG->dirroot/lib/fonts/$font")) { 2207 return "$CFG->dirroot/lib/fonts/$font"; 2208 } 2209 return null; 2210 2211 } else if ($component === 'theme') { // Exception. 2212 if (file_exists("$this->dir/fonts/$font")) { 2213 return "$this->dir/fonts/$font"; 2214 } 2215 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last. 2216 if (file_exists("$parent_config->dir/fonts/$font")) { 2217 return "$parent_config->dir/fonts/$font"; 2218 } 2219 } 2220 return null; 2221 2222 } else { 2223 if (strpos($component, '_') === false) { 2224 $component = 'mod_'.$component; 2225 } 2226 list($type, $plugin) = explode('_', $component, 2); 2227 2228 if (file_exists("$this->dir/fonts_plugins/$type/$plugin/$font")) { 2229 return "$this->dir/fonts_plugins/$type/$plugin/$font"; 2230 } 2231 foreach (array_reverse($this->parent_configs) as $parent_config) { // Base first, the immediate parent last. 2232 if (file_exists("$parent_config->dir/fonts_plugins/$type/$plugin/$font")) { 2233 return "$parent_config->dir/fonts_plugins/$type/$plugin/$font"; 2234 } 2235 } 2236 if (file_exists("$CFG->dataroot/fonts_plugins/$type/$plugin/$font")) { 2237 return "$CFG->dataroot/fonts_plugins/$type/$plugin/$font"; 2238 } 2239 $dir = core_component::get_plugin_directory($type, $plugin); 2240 if (file_exists("$dir/fonts/$font")) { 2241 return "$dir/fonts/$font"; 2242 } 2243 return null; 2244 } 2245 } 2246 2247 /** 2248 * Return true if we should look for SVG images as well. 2249 * 2250 * @return bool 2251 */ 2252 public function use_svg_icons() { 2253 if ($this->usesvg === null) { 2254 $this->usesvg = core_useragent::supports_svg(); 2255 } 2256 2257 return $this->usesvg; 2258 } 2259 2260 /** 2261 * Forces the usesvg setting to either true or false, avoiding any decision making. 2262 * 2263 * This function should only ever be used when absolutely required, and before any generation of image URL's has occurred. 2264 * DO NOT ABUSE THIS FUNCTION... not that you'd want to right ;) 2265 * 2266 * @param bool $setting True to force the use of svg when available, null otherwise. 2267 */ 2268 public function force_svg_use($setting) { 2269 $this->usesvg = (bool)$setting; 2270 } 2271 2272 /** 2273 * Set to be in RTL mode. 2274 * 2275 * This will likely be used when post processing the CSS before serving it. 2276 * 2277 * @param bool $inrtl True when in RTL mode. 2278 */ 2279 public function set_rtl_mode($inrtl = true) { 2280 $this->rtlmode = $inrtl; 2281 } 2282 2283 /** 2284 * Checks if source maps are supported 2285 * 2286 * @param bool $themedesigner True if theme designer is enabled. 2287 * @return boolean True if source maps are supported. 2288 */ 2289 public function supports_source_maps($themedesigner): bool { 2290 if (empty($this->rtlmode) && $themedesigner) { 2291 return true; 2292 } 2293 return false; 2294 } 2295 2296 /** 2297 * Whether the theme is being served in RTL mode. 2298 * 2299 * @return bool True when in RTL mode. 2300 */ 2301 public function get_rtl_mode() { 2302 return $this->rtlmode; 2303 } 2304 2305 /** 2306 * Checks if file with any image extension exists. 2307 * 2308 * The order to these images was adjusted prior to the release of 2.4 2309 * At that point the were the following image counts in Moodle core: 2310 * 2311 * - png = 667 in pix dirs (1499 total) 2312 * - gif = 385 in pix dirs (606 total) 2313 * - jpg = 62 in pix dirs (74 total) 2314 * - jpeg = 0 in pix dirs (1 total) 2315 * 2316 * There is work in progress to move towards SVG presently hence that has been prioritiesed. 2317 * 2318 * @param string $filepath 2319 * @param bool $svg If set to true SVG images will also be looked for. 2320 * @return string image name with extension 2321 */ 2322 private static function image_exists($filepath, $svg = false) { 2323 if ($svg && file_exists("$filepath.svg")) { 2324 return "$filepath.svg"; 2325 } else if (file_exists("$filepath.png")) { 2326 return "$filepath.png"; 2327 } else if (file_exists("$filepath.gif")) { 2328 return "$filepath.gif"; 2329 } else if (file_exists("$filepath.jpg")) { 2330 return "$filepath.jpg"; 2331 } else if (file_exists("$filepath.jpeg")) { 2332 return "$filepath.jpeg"; 2333 } else { 2334 return false; 2335 } 2336 } 2337 2338 /** 2339 * Loads the theme config from config.php file. 2340 * 2341 * @param string $themename 2342 * @param stdClass $settings from config_plugins table 2343 * @param boolean $parentscheck true to also check the parents. . 2344 * @return stdClass The theme configuration 2345 */ 2346 private static function find_theme_config($themename, $settings, $parentscheck = true) { 2347 // We have to use the variable name $THEME (upper case) because that 2348 // is what is used in theme config.php files. 2349 2350 if (!$dir = theme_config::find_theme_location($themename)) { 2351 return null; 2352 } 2353 2354 $THEME = new stdClass(); 2355 $THEME->name = $themename; 2356 $THEME->dir = $dir; 2357 $THEME->settings = $settings; 2358 2359 global $CFG; // just in case somebody tries to use $CFG in theme config 2360 include("$THEME->dir/config.php"); 2361 2362 // verify the theme configuration is OK 2363 if (!is_array($THEME->parents)) { 2364 // parents option is mandatory now 2365 return null; 2366 } else { 2367 // We use $parentscheck to only check the direct parents (avoid infinite loop). 2368 if ($parentscheck) { 2369 // Find all parent theme configs. 2370 foreach ($THEME->parents as $parent) { 2371 $parentconfig = theme_config::find_theme_config($parent, $settings, false); 2372 if (empty($parentconfig)) { 2373 return null; 2374 } 2375 } 2376 } 2377 } 2378 2379 return $THEME; 2380 } 2381 2382 /** 2383 * Finds the theme location and verifies the theme has all needed files 2384 * and is not obsoleted. 2385 * 2386 * @param string $themename 2387 * @return string full dir path or null if not found 2388 */ 2389 private static function find_theme_location($themename) { 2390 global $CFG; 2391 2392 if (file_exists("$CFG->dirroot/theme/$themename/config.php")) { 2393 $dir = "$CFG->dirroot/theme/$themename"; 2394 2395 } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$themename/config.php")) { 2396 $dir = "$CFG->themedir/$themename"; 2397 2398 } else { 2399 return null; 2400 } 2401 2402 if (file_exists("$dir/styles.php")) { 2403 //legacy theme - needs to be upgraded - upgrade info is displayed on the admin settings page 2404 return null; 2405 } 2406 2407 return $dir; 2408 } 2409 2410 /** 2411 * Get the renderer for a part of Moodle for this theme. 2412 * 2413 * @param moodle_page $page the page we are rendering 2414 * @param string $component the name of part of moodle. E.g. 'core', 'quiz', 'qtype_multichoice'. 2415 * @param string $subtype optional subtype such as 'news' resulting to 'mod_forum_news' 2416 * @param string $target one of rendering target constants 2417 * @return renderer_base the requested renderer. 2418 */ 2419 public function get_renderer(moodle_page $page, $component, $subtype = null, $target = null) { 2420 if (is_null($this->rf)) { 2421 $classname = $this->rendererfactory; 2422 $this->rf = new $classname($this); 2423 } 2424 2425 return $this->rf->get_renderer($page, $component, $subtype, $target); 2426 } 2427 2428 /** 2429 * Get the information from {@link $layouts} for this type of page. 2430 * 2431 * @param string $pagelayout the the page layout name. 2432 * @return array the appropriate part of {@link $layouts}. 2433 */ 2434 protected function layout_info_for_page($pagelayout) { 2435 if (array_key_exists($pagelayout, $this->layouts)) { 2436 return $this->layouts[$pagelayout]; 2437 } else { 2438 debugging('Invalid page layout specified: ' . $pagelayout); 2439 return $this->layouts['standard']; 2440 } 2441 } 2442 2443 /** 2444 * Given the settings of this theme, and the page pagelayout, return the 2445 * full path of the page layout file to use. 2446 * 2447 * Used by {@link core_renderer::header()}. 2448 * 2449 * @param string $pagelayout the the page layout name. 2450 * @return string Full path to the lyout file to use 2451 */ 2452 public function layout_file($pagelayout) { 2453 global $CFG; 2454 2455 $layoutinfo = $this->layout_info_for_page($pagelayout); 2456 $layoutfile = $layoutinfo['file']; 2457 2458 if (array_key_exists('theme', $layoutinfo)) { 2459 $themes = array($layoutinfo['theme']); 2460 } else { 2461 $themes = array_merge(array($this->name),$this->parents); 2462 } 2463 2464 foreach ($themes as $theme) { 2465 if ($dir = $this->find_theme_location($theme)) { 2466 $path = "$dir/layout/$layoutfile"; 2467 2468 // Check the template exists, return general base theme template if not. 2469 if (is_readable($path)) { 2470 return $path; 2471 } 2472 } 2473 } 2474 2475 debugging('Can not find layout file for: ' . $pagelayout); 2476 // fallback to standard normal layout 2477 return "$CFG->dirroot/theme/base/layout/general.php"; 2478 } 2479 2480 /** 2481 * Returns auxiliary page layout options specified in layout configuration array. 2482 * 2483 * @param string $pagelayout 2484 * @return array 2485 */ 2486 public function pagelayout_options($pagelayout) { 2487 $info = $this->layout_info_for_page($pagelayout); 2488 if (!empty($info['options'])) { 2489 return $info['options']; 2490 } 2491 return array(); 2492 } 2493 2494 /** 2495 * Inform a block_manager about the block regions this theme wants on this 2496 * page layout. 2497 * 2498 * @param string $pagelayout the general type of the page. 2499 * @param block_manager $blockmanager the block_manger to set up. 2500 */ 2501 public function setup_blocks($pagelayout, $blockmanager) { 2502 $layoutinfo = $this->layout_info_for_page($pagelayout); 2503 if (!empty($layoutinfo['regions'])) { 2504 $blockmanager->add_regions($layoutinfo['regions'], false); 2505 $blockmanager->set_default_region($layoutinfo['defaultregion']); 2506 } 2507 } 2508 2509 /** 2510 * Gets the visible name for the requested block region. 2511 * 2512 * @param string $region The region name to get 2513 * @param string $theme The theme the region belongs to (may come from the parent theme) 2514 * @return string 2515 */ 2516 protected function get_region_name($region, $theme) { 2517 2518 $stringman = get_string_manager(); 2519 2520 // Check if the name is defined in the theme. 2521 if ($stringman->string_exists('region-' . $region, 'theme_' . $theme)) { 2522 return get_string('region-' . $region, 'theme_' . $theme); 2523 } 2524 2525 // Check the theme parents. 2526 foreach ($this->parents as $parentthemename) { 2527 if ($stringman->string_exists('region-' . $region, 'theme_' . $parentthemename)) { 2528 return get_string('region-' . $region, 'theme_' . $parentthemename); 2529 } 2530 } 2531 2532 // Last resort, try the boost theme for names. 2533 return get_string('region-' . $region, 'theme_boost'); 2534 } 2535 2536 /** 2537 * Get the list of all block regions known to this theme in all templates. 2538 * 2539 * @return array internal region name => human readable name. 2540 */ 2541 public function get_all_block_regions() { 2542 $regions = array(); 2543 foreach ($this->layouts as $layoutinfo) { 2544 foreach ($layoutinfo['regions'] as $region) { 2545 $regions[$region] = $this->get_region_name($region, $this->name); 2546 } 2547 } 2548 return $regions; 2549 } 2550 2551 /** 2552 * Returns the human readable name of the theme 2553 * 2554 * @return string 2555 */ 2556 public function get_theme_name() { 2557 return get_string('pluginname', 'theme_'.$this->name); 2558 } 2559 2560 /** 2561 * Returns the block render method. 2562 * 2563 * It is set by the theme via: 2564 * $THEME->blockrendermethod = '...'; 2565 * 2566 * It can be one of two values, blocks or blocks_for_region. 2567 * It should be set to the method being used by the theme layouts. 2568 * 2569 * @return string 2570 */ 2571 public function get_block_render_method() { 2572 if ($this->blockrendermethod) { 2573 // Return the specified block render method. 2574 return $this->blockrendermethod; 2575 } 2576 // Its not explicitly set, check the parent theme configs. 2577 foreach ($this->parent_configs as $config) { 2578 if (isset($config->blockrendermethod)) { 2579 return $config->blockrendermethod; 2580 } 2581 } 2582 // Default it to blocks. 2583 return 'blocks'; 2584 } 2585 2586 /** 2587 * Get the callable for CSS tree post processing. 2588 * 2589 * @return string|null 2590 */ 2591 public function get_css_tree_post_processor() { 2592 $configs = [$this] + $this->parent_configs; 2593 foreach ($configs as $config) { 2594 if (!empty($config->csstreepostprocessor) && is_callable($config->csstreepostprocessor)) { 2595 return $config->csstreepostprocessor; 2596 } 2597 } 2598 return null; 2599 } 2600 2601 } 2602 2603 /** 2604 * This class keeps track of which HTML tags are currently open. 2605 * 2606 * This makes it much easier to always generate well formed XHTML output, even 2607 * if execution terminates abruptly. Any time you output some opening HTML 2608 * without the matching closing HTML, you should push the necessary close tags 2609 * onto the stack. 2610 * 2611 * @copyright 2009 Tim Hunt 2612 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 2613 * @since Moodle 2.0 2614 * @package core 2615 * @category output 2616 */ 2617 class xhtml_container_stack { 2618 2619 /** 2620 * @var array Stores the list of open containers. 2621 */ 2622 protected $opencontainers = array(); 2623 2624 /** 2625 * @var array In developer debug mode, stores a stack trace of all opens and 2626 * closes, so we can output helpful error messages when there is a mismatch. 2627 */ 2628 protected $log = array(); 2629 2630 /** 2631 * @var boolean Store whether we are developer debug mode. We need this in 2632 * several places including in the destructor where we may not have access to $CFG. 2633 */ 2634 protected $isdebugging; 2635 2636 /** 2637 * Constructor 2638 */ 2639 public function __construct() { 2640 global $CFG; 2641 $this->isdebugging = $CFG->debugdeveloper; 2642 } 2643 2644 /** 2645 * Push the close HTML for a recently opened container onto the stack. 2646 * 2647 * @param string $type The type of container. This is checked when {@link pop()} 2648 * is called and must match, otherwise a developer debug warning is output. 2649 * @param string $closehtml The HTML required to close the container. 2650 */ 2651 public function push($type, $closehtml) { 2652 $container = new stdClass; 2653 $container->type = $type; 2654 $container->closehtml = $closehtml; 2655 if ($this->isdebugging) { 2656 $this->log('Open', $type); 2657 } 2658 array_push($this->opencontainers, $container); 2659 } 2660 2661 /** 2662 * Pop the HTML for the next closing container from the stack. The $type 2663 * must match the type passed when the container was opened, otherwise a 2664 * warning will be output. 2665 * 2666 * @param string $type The type of container. 2667 * @return string the HTML required to close the container. 2668 */ 2669 public function pop($type) { 2670 if (empty($this->opencontainers)) { 2671 debugging('<p>There are no more open containers. This suggests there is a nesting problem.</p>' . 2672 $this->output_log(), DEBUG_DEVELOPER); 2673 return; 2674 } 2675 2676 $container = array_pop($this->opencontainers); 2677 if ($container->type != $type) { 2678 debugging('<p>The type of container to be closed (' . $container->type . 2679 ') does not match the type of the next open container (' . $type . 2680 '). This suggests there is a nesting problem.</p>' . 2681 $this->output_log(), DEBUG_DEVELOPER); 2682 } 2683 if ($this->isdebugging) { 2684 $this->log('Close', $type); 2685 } 2686 return $container->closehtml; 2687 } 2688 2689 /** 2690 * Close all but the last open container. This is useful in places like error 2691 * handling, where you want to close all the open containers (apart from <body>) 2692 * before outputting the error message. 2693 * 2694 * @param bool $shouldbenone assert that the stack should be empty now - causes a 2695 * developer debug warning if it isn't. 2696 * @return string the HTML required to close any open containers inside <body>. 2697 */ 2698 public function pop_all_but_last($shouldbenone = false) { 2699 if ($shouldbenone && count($this->opencontainers) != 1) { 2700 debugging('<p>Some HTML tags were opened in the body of the page but not closed.</p>' . 2701 $this->output_log(), DEBUG_DEVELOPER); 2702 } 2703 $output = ''; 2704 while (count($this->opencontainers) > 1) { 2705 $container = array_pop($this->opencontainers); 2706 $output .= $container->closehtml; 2707 } 2708 return $output; 2709 } 2710 2711 /** 2712 * You can call this function if you want to throw away an instance of this 2713 * class without properly emptying the stack (for example, in a unit test). 2714 * Calling this method stops the destruct method from outputting a developer 2715 * debug warning. After calling this method, the instance can no longer be used. 2716 */ 2717 public function discard() { 2718 $this->opencontainers = null; 2719 } 2720 2721 /** 2722 * Adds an entry to the log. 2723 * 2724 * @param string $action The name of the action 2725 * @param string $type The type of action 2726 */ 2727 protected function log($action, $type) { 2728 $this->log[] = '<li>' . $action . ' ' . $type . ' at:' . 2729 format_backtrace(debug_backtrace()) . '</li>'; 2730 } 2731 2732 /** 2733 * Outputs the log's contents as a HTML list. 2734 * 2735 * @return string HTML list of the log 2736 */ 2737 protected function output_log() { 2738 return '<ul>' . implode("\n", $this->log) . '</ul>'; 2739 } 2740 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body