PageRenderTime 34ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/outputlib.php

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